初始化项目,由ModelHub XC社区提供模型
Model: RinKana/aquila-135m-csqa Source: Original Platform
This commit is contained in:
35
.gitattributes
vendored
Normal file
35
.gitattributes
vendored
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
*.7z filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.arrow filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.bin filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.ftz filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.gz filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.h5 filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.joblib filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.model filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.npy filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.npz filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.onnx filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.ot filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.parquet filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.pb filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.pickle filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.pkl filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.pt filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.pth filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.rar filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
||||||
|
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.tar filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.tflite filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.tgz filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.wasm filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.xz filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.zip filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*.zst filter=lfs diff=lfs merge=lfs -text
|
||||||
|
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
||||||
251
README.md
Normal file
251
README.md
Normal file
@@ -0,0 +1,251 @@
|
|||||||
|
---
|
||||||
|
library_name: transformers
|
||||||
|
tags:
|
||||||
|
- trl
|
||||||
|
- sft
|
||||||
|
datasets:
|
||||||
|
- tau/commonsense_qa
|
||||||
|
base_model:
|
||||||
|
- BAAI/Aquila-135M-Instruct
|
||||||
|
license: apache-2.0
|
||||||
|
---
|
||||||
|
|
||||||
|
# Model Card for Model ID
|
||||||
|
|
||||||
|
<!-- Provide a quick summary of what the model is/does. -->
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Model Details
|
||||||
|
|
||||||
|
### Model Description
|
||||||
|
|
||||||
|
<!-- Provide a longer summary of what this model is. -->
|
||||||
|
|
||||||
|
This is the model card of a 🤗 transformers model that has been pushed on the Hub. This model card has been automatically generated.
|
||||||
|
|
||||||
|
- **Developed by:** Chakrabhuana Vishnu Deva
|
||||||
|
- **Funded by [optional]:** [More Information Needed]
|
||||||
|
- **Shared by [optional]:** [More Information Needed]
|
||||||
|
- **Model type:** Causal Language Model
|
||||||
|
- **Language(s) (NLP):** English
|
||||||
|
- **License:** Apache 2.0
|
||||||
|
- **Finetuned from model [optional]:** BAAI/Aquila-135M-Instruct
|
||||||
|
|
||||||
|
### Model Sources [optional]
|
||||||
|
|
||||||
|
<!-- Provide the basic links for the model. -->
|
||||||
|
|
||||||
|
- **Repository:** [More Information Needed]
|
||||||
|
- **Paper [optional]:** [More Information Needed]
|
||||||
|
- **Demo [optional]:** [More Information Needed]
|
||||||
|
|
||||||
|
## Uses
|
||||||
|
|
||||||
|
<!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
|
||||||
|
|
||||||
|
### Direct Use
|
||||||
|
|
||||||
|
<!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
|
||||||
|
|
||||||
|
The model is designed to answer multiple-choice questions. It is fine-tuned on the `tau/commonsense_qa` dataset.
|
||||||
|
|
||||||
|
### Downstream Use [optional]
|
||||||
|
|
||||||
|
<!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
### Out-of-Scope Use
|
||||||
|
|
||||||
|
<!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
## Bias, Risks, and Limitations
|
||||||
|
|
||||||
|
<!-- This section is meant to convey both technical and sociotechnical limitations. -->
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
### Recommendations
|
||||||
|
|
||||||
|
<!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
|
||||||
|
|
||||||
|
Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
|
||||||
|
|
||||||
|
## How to Get Started with the Model
|
||||||
|
|
||||||
|
Use the code below to get started with the model.
|
||||||
|
|
||||||
|
```python
|
||||||
|
import torch
|
||||||
|
from transformers import AutoTokenizer, AutoModelForCausalLM
|
||||||
|
|
||||||
|
model_id = "RinKana/aquila-135m-csqa" # Note: replace with your exact repo ID if different
|
||||||
|
|
||||||
|
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
||||||
|
model = AutoModelForCausalLM.from_pretrained(model_id, trust_remote_code=True, device_map="auto")
|
||||||
|
|
||||||
|
question = "What is the capital of France?"
|
||||||
|
options = "A. London\nB. Paris\nC. Berlin\nD. Madrid\nE. Rome"
|
||||||
|
|
||||||
|
user_prompt = (
|
||||||
|
"Answer the following multiple-choice question.\n\n"
|
||||||
|
f"Question: {question}\n"
|
||||||
|
f"Options:\n{options}\n\n"
|
||||||
|
"Answer with ONLY the letter (A, B, C, D, or E)."
|
||||||
|
)
|
||||||
|
|
||||||
|
messages = [{"role": "user", "content": user_prompt}]
|
||||||
|
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
||||||
|
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
|
||||||
|
|
||||||
|
with torch.no_grad():
|
||||||
|
outputs = model.generate(
|
||||||
|
**inputs,
|
||||||
|
max_new_tokens=5,
|
||||||
|
temperature=0.0,
|
||||||
|
do_sample=False,
|
||||||
|
)
|
||||||
|
|
||||||
|
input_length = inputs["input_ids"].shape[1]
|
||||||
|
response = tokenizer.decode(outputs[0][input_length:], skip_special_tokens=True).strip()
|
||||||
|
print(f"Predicted Answer: {response}")
|
||||||
|
```
|
||||||
|
|
||||||
|
## Training Details
|
||||||
|
|
||||||
|
### Training Data
|
||||||
|
|
||||||
|
<!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
|
||||||
|
|
||||||
|
The model was trained on the [tau/commonsense_qa](https://huggingface.co/datasets/tau/commonsense_qa) dataset.
|
||||||
|
|
||||||
|
### Training Procedure
|
||||||
|
|
||||||
|
<!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
|
||||||
|
|
||||||
|
#### Preprocessing [optional]
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
|
||||||
|
#### Training Hyperparameters
|
||||||
|
|
||||||
|
The model was trained with the following hyperparameters:
|
||||||
|
- **max_length:** 256
|
||||||
|
- **per_device_train_batch_size:** 16
|
||||||
|
- **per_device_eval_batch_size:** 16
|
||||||
|
- **gradient_accumulation_steps:** 2
|
||||||
|
- **num_train_epochs:** 3
|
||||||
|
- **learning_rate:** 2e-5
|
||||||
|
- **Training regime:** bf16 mixed precision <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
|
||||||
|
|
||||||
|
#### Speeds, Sizes, Times [optional]
|
||||||
|
|
||||||
|
<!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
## Evaluation
|
||||||
|
|
||||||
|
<!-- This section describes the evaluation protocols and provides the results. -->
|
||||||
|
|
||||||
|
### Testing Data, Factors & Metrics
|
||||||
|
|
||||||
|
#### Testing Data
|
||||||
|
|
||||||
|
<!-- This should link to a Dataset Card if possible. -->
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
#### Factors
|
||||||
|
|
||||||
|
<!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
#### Metrics
|
||||||
|
|
||||||
|
<!-- These are the evaluation metrics being used, ideally with a description of why. -->
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
### Results
|
||||||
|
|
||||||
|
| Epoch | Training Loss | Validation Loss | Entropy | Num Tokens | Mean Token Accuracy |
|
||||||
|
|---|---|---|---|---|---|
|
||||||
|
| 1 | 1.164672 | 1.156044 | 1.286664 | 864431.000000 | 0.786455 |
|
||||||
|
| 2 | 1.125324 | 1.123461 | 1.223981 | 1728862.000000 | 0.798904 |
|
||||||
|
| 3 | 1.110953 | 1.120729 | 1.214477 | 2593293.000000 | 0.798789 |
|
||||||
|
|
||||||
|
#### Summary
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Model Examination [optional]
|
||||||
|
|
||||||
|
<!-- Relevant interpretability work for the model goes here -->
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
## Environmental Impact
|
||||||
|
|
||||||
|
<!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
|
||||||
|
|
||||||
|
Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
|
||||||
|
|
||||||
|
- **Hardware Type:** [More Information Needed]
|
||||||
|
- **Hours used:** [More Information Needed]
|
||||||
|
- **Cloud Provider:** [More Information Needed]
|
||||||
|
- **Compute Region:** [More Information Needed]
|
||||||
|
- **Carbon Emitted:** [More Information Needed]
|
||||||
|
|
||||||
|
## Technical Specifications [optional]
|
||||||
|
|
||||||
|
### Model Architecture and Objective
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
### Compute Infrastructure
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
#### Hardware
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
#### Software
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
## Citation [optional]
|
||||||
|
|
||||||
|
<!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
|
||||||
|
|
||||||
|
**BibTeX:**
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
**APA:**
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
## Glossary [optional]
|
||||||
|
|
||||||
|
<!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
## More Information [optional]
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
## Model Card Authors [optional]
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
|
|
||||||
|
## Model Card Contact
|
||||||
|
|
||||||
|
[More Information Needed]
|
||||||
6
chat_template.jinja
Normal file
6
chat_template.jinja
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system
|
||||||
|
You are a helpful assistant<|im_end|>
|
||||||
|
' }}{% endif %}{{'<|im_start|>' + message['role'] + '
|
||||||
|
' + message['content'] + '<|im_end|>' + '
|
||||||
|
'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
||||||
|
' }}{% endif %}
|
||||||
31
config.json
Normal file
31
config.json
Normal file
@@ -0,0 +1,31 @@
|
|||||||
|
{
|
||||||
|
"architectures": [
|
||||||
|
"MistralForCausalLM"
|
||||||
|
],
|
||||||
|
"attention_bias": false,
|
||||||
|
"attention_dropout": 0.0,
|
||||||
|
"bos_token_id": 151849,
|
||||||
|
"dtype": "bfloat16",
|
||||||
|
"eos_token_id": 151645,
|
||||||
|
"head_dim": 64,
|
||||||
|
"hidden_act": "silu",
|
||||||
|
"hidden_size": 576,
|
||||||
|
"initializer_range": 0.02,
|
||||||
|
"intermediate_size": 1536,
|
||||||
|
"max_position_embeddings": 8192,
|
||||||
|
"model_type": "mistral",
|
||||||
|
"num_attention_heads": 9,
|
||||||
|
"num_hidden_layers": 30,
|
||||||
|
"num_key_value_heads": 3,
|
||||||
|
"pad_token_id": 151643,
|
||||||
|
"rms_norm_eps": 1e-05,
|
||||||
|
"rope_parameters": {
|
||||||
|
"rope_theta": 10000,
|
||||||
|
"rope_type": "default"
|
||||||
|
},
|
||||||
|
"sliding_window": 8192,
|
||||||
|
"tie_word_embeddings": true,
|
||||||
|
"transformers_version": "5.0.0",
|
||||||
|
"use_cache": false,
|
||||||
|
"vocab_size": 151851
|
||||||
|
}
|
||||||
13
generation_config.json
Normal file
13
generation_config.json
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
{
|
||||||
|
"bos_token_id": 151849,
|
||||||
|
"do_sample": true,
|
||||||
|
"eos_token_id": [
|
||||||
|
151645
|
||||||
|
],
|
||||||
|
"pad_token_id": 151643,
|
||||||
|
"repetition_penalty": 1.05,
|
||||||
|
"temperature": 0.7,
|
||||||
|
"top_k": 20,
|
||||||
|
"top_p": 0.8,
|
||||||
|
"transformers_version": "5.0.0"
|
||||||
|
}
|
||||||
3
model.safetensors
Normal file
3
model.safetensors
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
version https://git-lfs.github.com/spec/v1
|
||||||
|
oid sha256:380633de5ac71b4778ac1074f94c3df0b340ba7fab274cb32a2d91ef1c30ba17
|
||||||
|
size 562302352
|
||||||
151643
qwen.tiktoken
Normal file
151643
qwen.tiktoken
Normal file
File diff suppressed because it is too large
Load Diff
276
tokenization_qwen.py
Normal file
276
tokenization_qwen.py
Normal file
@@ -0,0 +1,276 @@
|
|||||||
|
# Copyright (c) Alibaba Cloud.
|
||||||
|
#
|
||||||
|
# This source code is licensed under the license found in the
|
||||||
|
# LICENSE file in the root directory of this source tree.
|
||||||
|
|
||||||
|
"""Tokenization classes for QWen."""
|
||||||
|
|
||||||
|
import base64
|
||||||
|
import logging
|
||||||
|
import os
|
||||||
|
import unicodedata
|
||||||
|
from typing import Collection, Dict, List, Set, Tuple, Union
|
||||||
|
|
||||||
|
import tiktoken
|
||||||
|
from transformers import PreTrainedTokenizer, AddedToken
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
|
||||||
|
VOCAB_FILES_NAMES = {"vocab_file": "qwen.tiktoken"}
|
||||||
|
|
||||||
|
PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
|
||||||
|
ENDOFTEXT = "<|endoftext|>"
|
||||||
|
IMSTART = "<|im_start|>"
|
||||||
|
IMEND = "<|im_end|>"
|
||||||
|
# as the default behavior is changed to allow special tokens in
|
||||||
|
# regular texts, the surface forms of special tokens need to be
|
||||||
|
# as different as possible to minimize the impact
|
||||||
|
EXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))
|
||||||
|
# changed to use actual index to avoid misconfiguration with vocabulary expansion
|
||||||
|
SPECIAL_START_ID = 151643
|
||||||
|
SPECIAL_TOKENS = tuple(
|
||||||
|
enumerate(
|
||||||
|
(
|
||||||
|
(
|
||||||
|
ENDOFTEXT,
|
||||||
|
IMSTART,
|
||||||
|
IMEND,
|
||||||
|
)
|
||||||
|
+ EXTRAS
|
||||||
|
),
|
||||||
|
start=SPECIAL_START_ID,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
SPECIAL_TOKENS_SET = set(t for i, t in SPECIAL_TOKENS)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_tiktoken_bpe(tiktoken_bpe_file: str) -> Dict[bytes, int]:
|
||||||
|
with open(tiktoken_bpe_file, "rb") as f:
|
||||||
|
contents = f.read()
|
||||||
|
return {
|
||||||
|
base64.b64decode(token): int(rank)
|
||||||
|
for token, rank in (line.split() for line in contents.splitlines() if line)
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class QWenTokenizer(PreTrainedTokenizer):
|
||||||
|
"""QWen tokenizer."""
|
||||||
|
|
||||||
|
vocab_files_names = VOCAB_FILES_NAMES
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
vocab_file,
|
||||||
|
errors="replace",
|
||||||
|
extra_vocab_file=None,
|
||||||
|
**kwargs,
|
||||||
|
):
|
||||||
|
super().__init__(**kwargs)
|
||||||
|
|
||||||
|
# how to handle errors in decoding UTF-8 byte sequences
|
||||||
|
# use ignore if you are in streaming inference
|
||||||
|
self.errors = errors
|
||||||
|
|
||||||
|
self.mergeable_ranks = _load_tiktoken_bpe(vocab_file) # type: Dict[bytes, int]
|
||||||
|
self.special_tokens = {
|
||||||
|
token: index
|
||||||
|
for index, token in SPECIAL_TOKENS
|
||||||
|
}
|
||||||
|
|
||||||
|
# try load extra vocab from file
|
||||||
|
if extra_vocab_file is not None:
|
||||||
|
used_ids = set(self.mergeable_ranks.values()) | set(self.special_tokens.values())
|
||||||
|
extra_mergeable_ranks = _load_tiktoken_bpe(extra_vocab_file)
|
||||||
|
for token, index in extra_mergeable_ranks.items():
|
||||||
|
if token in self.mergeable_ranks:
|
||||||
|
logger.info(f"extra token {token} exists, skipping")
|
||||||
|
continue
|
||||||
|
if index in used_ids:
|
||||||
|
logger.info(f'the index {index} for extra token {token} exists, skipping')
|
||||||
|
continue
|
||||||
|
self.mergeable_ranks[token] = index
|
||||||
|
# the index may be sparse after this, but don't worry tiktoken.Encoding will handle this
|
||||||
|
|
||||||
|
enc = tiktoken.Encoding(
|
||||||
|
"Qwen",
|
||||||
|
pat_str=PAT_STR,
|
||||||
|
mergeable_ranks=self.mergeable_ranks,
|
||||||
|
special_tokens=self.special_tokens,
|
||||||
|
)
|
||||||
|
assert (
|
||||||
|
len(self.mergeable_ranks) + len(self.special_tokens) == enc.n_vocab
|
||||||
|
), f"{len(self.mergeable_ranks) + len(self.special_tokens)} != {enc.n_vocab} in encoding"
|
||||||
|
|
||||||
|
self.decoder = {
|
||||||
|
v: k for k, v in self.mergeable_ranks.items()
|
||||||
|
} # type: dict[int, bytes|str]
|
||||||
|
self.decoder.update({v: k for k, v in self.special_tokens.items()})
|
||||||
|
|
||||||
|
self.tokenizer = enc # type: tiktoken.Encoding
|
||||||
|
|
||||||
|
self.eod_id = self.tokenizer.eot_token
|
||||||
|
self.im_start_id = self.special_tokens[IMSTART]
|
||||||
|
self.im_end_id = self.special_tokens[IMEND]
|
||||||
|
|
||||||
|
def __getstate__(self):
|
||||||
|
# for pickle lovers
|
||||||
|
state = self.__dict__.copy()
|
||||||
|
del state["tokenizer"]
|
||||||
|
return state
|
||||||
|
|
||||||
|
def __setstate__(self, state):
|
||||||
|
# tokenizer is not python native; don't pass it; rebuild it
|
||||||
|
self.__dict__.update(state)
|
||||||
|
enc = tiktoken.Encoding(
|
||||||
|
"Qwen",
|
||||||
|
pat_str=PAT_STR,
|
||||||
|
mergeable_ranks=self.mergeable_ranks,
|
||||||
|
special_tokens=self.special_tokens,
|
||||||
|
)
|
||||||
|
self.tokenizer = enc
|
||||||
|
|
||||||
|
def __len__(self) -> int:
|
||||||
|
return self.tokenizer.n_vocab
|
||||||
|
|
||||||
|
def get_vocab(self) -> Dict[bytes, int]:
|
||||||
|
return self.mergeable_ranks
|
||||||
|
|
||||||
|
def convert_tokens_to_ids(
|
||||||
|
self, tokens: Union[bytes, str, List[Union[bytes, str]]]
|
||||||
|
) -> List[int]:
|
||||||
|
ids = []
|
||||||
|
if isinstance(tokens, (str, bytes)):
|
||||||
|
if tokens in self.special_tokens:
|
||||||
|
return self.special_tokens[tokens]
|
||||||
|
else:
|
||||||
|
return self.mergeable_ranks.get(tokens)
|
||||||
|
for token in tokens:
|
||||||
|
if token in self.special_tokens:
|
||||||
|
ids.append(self.special_tokens[token])
|
||||||
|
else:
|
||||||
|
ids.append(self.mergeable_ranks.get(token))
|
||||||
|
return ids
|
||||||
|
|
||||||
|
def _add_tokens(
|
||||||
|
self,
|
||||||
|
new_tokens: Union[List[str], List[AddedToken]],
|
||||||
|
special_tokens: bool = False,
|
||||||
|
) -> int:
|
||||||
|
if not special_tokens and new_tokens:
|
||||||
|
raise ValueError("Adding regular tokens is not supported")
|
||||||
|
for token in new_tokens:
|
||||||
|
surface_form = token.content if isinstance(token, AddedToken) else token
|
||||||
|
if surface_form not in SPECIAL_TOKENS_SET:
|
||||||
|
raise ValueError("Adding unknown special tokens is not supported")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
def save_vocabulary(self, save_directory: str, **kwargs) -> Tuple[str]:
|
||||||
|
"""
|
||||||
|
Save only the vocabulary of the tokenizer (vocabulary).
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
`Tuple(str)`: Paths to the files saved.
|
||||||
|
"""
|
||||||
|
file_path = os.path.join(save_directory, "qwen.tiktoken")
|
||||||
|
with open(file_path, "w", encoding="utf8") as w:
|
||||||
|
for k, v in self.mergeable_ranks.items():
|
||||||
|
line = base64.b64encode(k).decode("utf8") + " " + str(v) + "\n"
|
||||||
|
w.write(line)
|
||||||
|
return (file_path,)
|
||||||
|
|
||||||
|
def tokenize(
|
||||||
|
self,
|
||||||
|
text: str,
|
||||||
|
allowed_special: Union[Set, str] = "all",
|
||||||
|
disallowed_special: Union[Collection, str] = (),
|
||||||
|
**kwargs,
|
||||||
|
) -> List[Union[bytes, str]]:
|
||||||
|
"""
|
||||||
|
Converts a string in a sequence of tokens.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
text (`str`):
|
||||||
|
The sequence to be encoded.
|
||||||
|
allowed_special (`Literal["all"]` or `set`):
|
||||||
|
The surface forms of the tokens to be encoded as special tokens in regular texts.
|
||||||
|
Default to "all".
|
||||||
|
disallowed_special (`Literal["all"]` or `Collection`):
|
||||||
|
The surface forms of the tokens that should not be in regular texts and trigger errors.
|
||||||
|
Default to an empty tuple.
|
||||||
|
|
||||||
|
kwargs (additional keyword arguments, *optional*):
|
||||||
|
Will be passed to the underlying model specific encode method.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
`List[bytes|str]`: The list of tokens.
|
||||||
|
"""
|
||||||
|
tokens = []
|
||||||
|
text = unicodedata.normalize("NFC", text)
|
||||||
|
|
||||||
|
# this implementation takes a detour: text -> token id -> token surface forms
|
||||||
|
for t in self.tokenizer.encode(
|
||||||
|
text, allowed_special=allowed_special, disallowed_special=disallowed_special
|
||||||
|
):
|
||||||
|
tokens.append(self.decoder[t])
|
||||||
|
return tokens
|
||||||
|
|
||||||
|
def convert_tokens_to_string(self, tokens: List[Union[bytes, str]]) -> str:
|
||||||
|
"""
|
||||||
|
Converts a sequence of tokens in a single string.
|
||||||
|
"""
|
||||||
|
text = ""
|
||||||
|
temp = b""
|
||||||
|
for t in tokens:
|
||||||
|
if isinstance(t, str):
|
||||||
|
if temp:
|
||||||
|
text += temp.decode("utf-8", errors=self.errors)
|
||||||
|
temp = b""
|
||||||
|
text += t
|
||||||
|
elif isinstance(t, bytes):
|
||||||
|
temp += t
|
||||||
|
else:
|
||||||
|
raise TypeError("token should only be of type types or str")
|
||||||
|
if temp:
|
||||||
|
text += temp.decode("utf-8", errors=self.errors)
|
||||||
|
return text
|
||||||
|
|
||||||
|
@property
|
||||||
|
def vocab_size(self):
|
||||||
|
return self.tokenizer.n_vocab
|
||||||
|
|
||||||
|
def _convert_id_to_token(self, index: int) -> Union[bytes, str]:
|
||||||
|
"""Converts an id to a token, special tokens included"""
|
||||||
|
if index in self.decoder:
|
||||||
|
return self.decoder[index]
|
||||||
|
raise ValueError("unknown ids")
|
||||||
|
|
||||||
|
def _convert_token_to_id(self, token: Union[bytes, str]) -> int:
|
||||||
|
"""Converts a token to an id using the vocab, special tokens included"""
|
||||||
|
if token in self.special_tokens:
|
||||||
|
return self.special_tokens[token]
|
||||||
|
if token in self.mergeable_ranks:
|
||||||
|
return self.mergeable_ranks[token]
|
||||||
|
raise ValueError("unknown token")
|
||||||
|
|
||||||
|
def _tokenize(self, text: str, **kwargs):
|
||||||
|
"""
|
||||||
|
Converts a string in a sequence of tokens (string), using the tokenizer. Split in words for word-based
|
||||||
|
vocabulary or sub-words for sub-word-based vocabularies (BPE/SentencePieces/WordPieces).
|
||||||
|
|
||||||
|
Do NOT take care of added tokens.
|
||||||
|
"""
|
||||||
|
raise NotImplementedError
|
||||||
|
|
||||||
|
def _decode(
|
||||||
|
self,
|
||||||
|
token_ids: Union[int, List[int]],
|
||||||
|
skip_special_tokens: bool = False,
|
||||||
|
errors: str = None,
|
||||||
|
**kwargs,
|
||||||
|
) -> str:
|
||||||
|
if isinstance(token_ids, int):
|
||||||
|
token_ids = [token_ids]
|
||||||
|
if skip_special_tokens:
|
||||||
|
token_ids = [i for i in token_ids if i < self.eod_id]
|
||||||
|
return self.tokenizer.decode(token_ids, errors=errors or self.errors)
|
||||||
18
tokenizer_config.json
Normal file
18
tokenizer_config.json
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
{
|
||||||
|
"added_tokens_decoder": {},
|
||||||
|
"additional_special_tokens": null,
|
||||||
|
"auto_map": {
|
||||||
|
"AutoTokenizer": [
|
||||||
|
"tokenization_qwen.QWenTokenizer",
|
||||||
|
null
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"backend": "custom",
|
||||||
|
"bos_token": "<|extra_203|>",
|
||||||
|
"eos_token": "<|im_end|>",
|
||||||
|
"is_local": false,
|
||||||
|
"model_max_length": 8192,
|
||||||
|
"pad_token": "<|endoftext|>",
|
||||||
|
"tokenizer_class": "QWenTokenizer",
|
||||||
|
"unk_token": "<|endoftext|>"
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user