初始化项目,由ModelHub XC社区提供模型
Model: BAAI/Aquila-135M-Instruct 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
|
||||||
117
README.md
Normal file
117
README.md
Normal file
@@ -0,0 +1,117 @@
|
|||||||
|
---
|
||||||
|
license: apache-2.0
|
||||||
|
language:
|
||||||
|
- en
|
||||||
|
- zh
|
||||||
|
library_name: transformers
|
||||||
|
datasets:
|
||||||
|
- BAAI/Infinity-Instruct
|
||||||
|
- BAAI/CCI3-HQ
|
||||||
|
- mlfoundations/dclm-baseline-1.0
|
||||||
|
- HuggingFaceFW/fineweb-edu
|
||||||
|
- HuggingFaceTB/smollm-corpus
|
||||||
|
pipeline_tag: text-generation
|
||||||
|
extra_gated_prompt: "You agree to not use the dataset to conduct experiments that cause harm to human subjects."
|
||||||
|
extra_gated_fields:
|
||||||
|
Company/Organization: text
|
||||||
|
Country: country
|
||||||
|
---
|
||||||
|
|
||||||
|
# Introduction
|
||||||
|
|
||||||
|
The **Aquila-135M** model is a small bilingual(Chinese and English) language model, which is trained using a two-phrase paradigm: pre-training and annealing.
|
||||||
|
This model used 1.66TB bilingual tokens in Chinese and English during pre-training phrase and 100B tokens during annealing training phrase.
|
||||||
|
In annealing stage, we selected 100B tokens of high-quality bilingual data and finally got our model.
|
||||||
|
|
||||||
|
The **Aquila-135M-Instuct** model is finetuned using [Infinity Instruct](https://huggingface.co/datasets/BAAI/Infinity-Instruct).
|
||||||
|
|
||||||
|
The entire training process was conducted using [FlagGems](https://github.com/FlagOpen/FlagGems) based on Triton and parallel training framework named [FlagScale](https://github.com/FlagOpen/FlagScale).
|
||||||
|
|
||||||
|
Also, we have open-sourced all [intermediate checkpoints](https://huggingface.co/BAAI/Aquila-135M-Intermediate).
|
||||||
|
|
||||||
|
# News
|
||||||
|
- `2024/12/24`: We have released Aquila-135M and Aquila-135M-Instruct.
|
||||||
|
- `2024/12/24`: We have released all datasets and intermediate checkpoints during training. Please feel free to use these models for analysis and experimentation.
|
||||||
|
|
||||||
|
# Datasets
|
||||||
|
|
||||||
|
We have open-sourced all [bilingual datasets](https://huggingface.co/datasets/BAAI/Aquila-135M-Datasets) during both pre-training and annealing phrases.
|
||||||
|
Datasets composition and mix proportions are shown in the figure below.
|
||||||
|
<img src="./datasets.jpeg" alt="datasets composition" width="800" height="600">
|
||||||
|
|
||||||
|
# Evaluation
|
||||||
|
|
||||||
|
We followed the same evaluation setting of SmolLM models and evaluated models using the [lighteval](https://github.com/huggingface/lighteval) tool.
|
||||||
|
|
||||||
|
The parameter count excludes the embedding part and Aquila-135M and SmolLM2-135M share an identical model structure. Aquila-135M achieves comparable performance on English benchmarks, while Aquila-135M demonstrates significantly better results on Chinese benchmarks.
|
||||||
|
|
||||||
|
Among small models with a total parameter count below and around 400M, Aquila-135M maintains a leading position in processing capabilities while significantly enhancing Chinese language proficiency.
|
||||||
|
|
||||||
|
| Metrics (0-shot) | Aquila-135M (Trition) | Aquila-135M (CUDA) | SmolLM-135M | SmolLM2-135M | gpt2-medium-360M | TinyMistral-248M | TinyMistral-248M-2.5 | OpenELM-270M | Wide-Sheared-LLaMA-290M | opt-350m | MobileLLM-350M | pythia-410m | SmolLM-360M | SmolLM2-360M |
|
||||||
|
|---------------------------|-----------------------|--------------------|-------------|---------------|------------------|------------------|----------------------|--------------|--------------------------|----------|----------------|-------------|-------------|--------------|
|
||||||
|
| **HellaSwag** | 41.19 | 41.12 | 41.15 | 42.10 | 37.08 | 27.06 | 26.80 | 45.74 | 24.94 | 36.08 | 26.28 | 39.22 | 51.73 | 54.66 |
|
||||||
|
| **ARC (Average)** | 44.76 | 44.15 | 42.34 | 43.93 | 34.34 | 29.71 | 27.63 | 35.74 | 26.20 | 31.91 | 27.72 | 35.14 | 49.95 | 53.24 |
|
||||||
|
| **PIQA** | 66.38 | 67.52 | 68.28 | 68.44 | 66.38 | 57.40 | 53.92 | 69.75 | 50.60 | 64.36 | 50.27 | 67.19 | 71.55 | 71.98 |
|
||||||
|
| **MMLU (cloze)** | 31.07 | 30.67 | 30.26 | 31.58 | 27.75 | 25.82 | 25.59 | 27.89 | 24.75 | 26.58 | 24.86 | 28.88 | 34.32 | 36.09 |
|
||||||
|
| **CommonsenseQA** | 32.10 | 31.70 | 32.02 | 32.92 | 31.70 | 24.57 | 21.46 | 35.71 | 16.54 | 32.10 | 17.53 | 31.45 | 36.61 | 38.74 |
|
||||||
|
| **TriviaQA** | 6.65 | 7.02 | 4.24 | 4.03 | 2.36 | 0.50 | 0.08 | 1.34 | 0.00 | 1.38 | 0.00 | 2.06 | 9.19 | 16.92 |
|
||||||
|
| **Winograde** | 51.07 | 51.70 | 51.22 | 50.99 | 49.49 | 49.25 | 49.01 | 52.41 | 49.72 | 51.54 | 49.41 | 49.96 | 53.12 | 52.49 |
|
||||||
|
| **OpenBookQA** | 34.40 | 34.40 | 33.80 | 34.60 | 31.40 | 29.40 | 27.40 | 30.60 | 26.00 | 27.80 | 24.80 | 28.40 | 37.20 | 37.00 |
|
||||||
|
| **GSM8K (5-shot)** | 2.12 | 2.12 | 1.00 | 1.52 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 0.00 | 2.81 |
|
||||||
|
| **SIQA** | 41.81 | 42.32 | 41.15 | 41.45 | 41.30 | 41.86 | 39.71 | 42.73 | 39.76 | 42.37 | 37.10 | 42.02 | 43.45 | 41.61 |
|
||||||
|
| **CEval** | 29.22 | 29.82 | 28.28 | 26.41 | 25.40 | 25.38 | 26.89 | 26.69 | 26.37 | 26.67 | 25.68 | 27.97 | 27.66 | 28.51 |
|
||||||
|
| **CMMLU** | 29.48 | 29.63 | 26.01 | 26.66 | 27.20 | 26.67 | 25.57 | 26.25 | 26.33 | 26.93 | 25.61 | 26.91 | 27.06 | 27.39 |
|
||||||
|
| **Average-English** | 35.16 | 35.27 | 34.55 | 35.16 | 32.18 | 28.56 | 27.16 | 34.19 | 25.85 | 31.41 | 25.80 | 32.43 | 38.71 | 40.55 |
|
||||||
|
| **Average-Chinese** | 29.35 | 29.73 | 27.15 | 26.54 | 26.30 | 26.03 | 26.23 | 26.47 | 26.35 | 26.80 | 25.65 | 27.44 | 27.36 | 27.95 |
|
||||||
|
| **Average** | 32.25 | 32.50 | 30.85 | 30.85 | 29.24 | 27.29 | 26.70 | 30.33 | 26.10 | 29.11 | 25.72 | 29.94 | 33.04 | 34.25 |
|
||||||
|
|
||||||
|
For comparison models, evaluations were conducted in a local environment, so the scores may differ slightly from those reported in papers.
|
||||||
|
|
||||||
|
# How to use
|
||||||
|
|
||||||
|
## Instruct Model
|
||||||
|
```python
|
||||||
|
from transformers import AutoModelForCausalLM, AutoTokenizer
|
||||||
|
checkpoint = "BAAI/Aquila-135M-Instruct"
|
||||||
|
|
||||||
|
device = "cuda" # for GPU usage or "cpu" for CPU usage
|
||||||
|
tokenizer = AutoTokenizer.from_pretrained(checkpoint, trust_remote_code=True)
|
||||||
|
# for multiple GPUs install accelerate and do `model = AutoModelForCausalLM.from_pretrained(checkpoint, device_map="auto")`
|
||||||
|
model = AutoModelForCausalLM.from_pretrained(checkpoint).to(device)
|
||||||
|
|
||||||
|
messages = [{"role": "user", "content": "什么是引力?"}]
|
||||||
|
input_text=tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
||||||
|
print(input_text)
|
||||||
|
inputs = tokenizer.encode(input_text, return_tensors="pt").to(device)
|
||||||
|
outputs = model.generate(inputs, max_new_tokens=500)
|
||||||
|
print(tokenizer.decode(outputs[0]))
|
||||||
|
## 引力是宇宙中的一个基本力,由多个物体相互作用而产生的。它由能量和质量组成,与引力定律密切相关。
|
||||||
|
|
||||||
|
messages = [{"role": "user", "content": "What is gravity?"}]
|
||||||
|
input_text=tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
||||||
|
print(input_text)
|
||||||
|
inputs = tokenizer.encode(input_text, return_tensors="pt").to(device)
|
||||||
|
outputs = model.generate(inputs, max_new_tokens=500)
|
||||||
|
print(tokenizer.decode(outputs[0]))
|
||||||
|
## Gravity is the force that keeps us on Earth as we orbit it. It pulls objects towards each other with a strength that depends on how far apart they are from each other, and how strong the gravitational pull is. The stronger the object's mass, the greater its gravitational pull.
|
||||||
|
```
|
||||||
|
|
||||||
|
# Future Plan
|
||||||
|
|
||||||
|
* We plan to further optimize the composition and proportions of the dataset.
|
||||||
|
* We plan to further explore the application of small-scale models in specific scenarios.
|
||||||
|
|
||||||
|
|
||||||
|
## **Citation**
|
||||||
|
If you find this useful, please cite the following work
|
||||||
|
```
|
||||||
|
@misc{aquila-135m,
|
||||||
|
title={Aquila-135M: A Bilingual Small Language Model in Chinese and English},
|
||||||
|
author={BAAI},
|
||||||
|
year={},
|
||||||
|
eprint={},
|
||||||
|
archivePrefix={arXiv},
|
||||||
|
primaryClass={cs.CL},
|
||||||
|
url={},
|
||||||
|
}
|
||||||
|
```
|
||||||
27
config.json
Normal file
27
config.json
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
{
|
||||||
|
"architectures": [
|
||||||
|
"MistralForCausalLM"
|
||||||
|
],
|
||||||
|
"attention_bias": false,
|
||||||
|
"attention_dropout": 0.0,
|
||||||
|
"bos_token_id": 151849,
|
||||||
|
"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,
|
||||||
|
"rms_norm_eps": 1e-05,
|
||||||
|
"rope_theta": 10000,
|
||||||
|
"sliding_window": 8192,
|
||||||
|
"tie_word_embeddings": true,
|
||||||
|
"torch_dtype": "bfloat16",
|
||||||
|
"transformers_version": "4.44.2",
|
||||||
|
"use_cache": true,
|
||||||
|
"vocab_size": 151851
|
||||||
|
}
|
||||||
1
configuration.json
Normal file
1
configuration.json
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"framework": "pytorch", "task": "text-generation", "allow_remote": true}
|
||||||
BIN
datasets.jpeg
Normal file
BIN
datasets.jpeg
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 434 KiB |
10
generation_config.json
Normal file
10
generation_config.json
Normal file
@@ -0,0 +1,10 @@
|
|||||||
|
{
|
||||||
|
"bos_token_id": 151849,
|
||||||
|
"do_sample": true,
|
||||||
|
"eos_token_id": 151645,
|
||||||
|
"pad_token_id": 151643,
|
||||||
|
"repetition_penalty": 1.05,
|
||||||
|
"temperature": 0.7,
|
||||||
|
"top_p": 0.8,
|
||||||
|
"top_k": 20
|
||||||
|
}
|
||||||
3
model.safetensors
Normal file
3
model.safetensors
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
version https://git-lfs.github.com/spec/v1
|
||||||
|
oid sha256:50ae2e43b75967aae9a01d7611e00bb0ea425990ec415a85cd4531dbdacc03cf
|
||||||
|
size 562302352
|
||||||
151643
qwen.tiktoken
Normal file
151643
qwen.tiktoken
Normal file
File diff suppressed because it is too large
Load Diff
416
qwen_generation_utils.py
Normal file
416
qwen_generation_utils.py
Normal file
@@ -0,0 +1,416 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
"""Generation support."""
|
||||||
|
|
||||||
|
from typing import Tuple, List, Union, Iterable
|
||||||
|
|
||||||
|
import numpy as np
|
||||||
|
import torch
|
||||||
|
import torch.nn.functional as F
|
||||||
|
from transformers import PreTrainedTokenizer
|
||||||
|
from transformers import logging
|
||||||
|
from transformers.generation import LogitsProcessor
|
||||||
|
|
||||||
|
logger = logging.get_logger(__name__)
|
||||||
|
|
||||||
|
# Types.
|
||||||
|
HistoryType = List[Tuple[str, str]]
|
||||||
|
TokensType = List[int]
|
||||||
|
BatchTokensType = List[List[int]]
|
||||||
|
|
||||||
|
|
||||||
|
def pad_batch(batch: BatchTokensType, pad_id: int, seq_length: int) -> BatchTokensType:
|
||||||
|
for tokens in batch:
|
||||||
|
context_length = len(tokens)
|
||||||
|
if context_length < seq_length:
|
||||||
|
tokens.extend([pad_id] * (seq_length - context_length))
|
||||||
|
return batch
|
||||||
|
|
||||||
|
|
||||||
|
def get_ltor_masks_and_position_ids(
|
||||||
|
data,
|
||||||
|
eod_token,
|
||||||
|
reset_position_ids,
|
||||||
|
reset_attention_mask,
|
||||||
|
eod_mask_loss,
|
||||||
|
):
|
||||||
|
"""Build masks and position id for left to right model."""
|
||||||
|
|
||||||
|
# Extract batch size and sequence length.
|
||||||
|
micro_batch_size, seq_length = data.size()
|
||||||
|
|
||||||
|
# Attention mask (lower triangular).
|
||||||
|
if reset_attention_mask:
|
||||||
|
att_mask_batch = micro_batch_size
|
||||||
|
else:
|
||||||
|
att_mask_batch = 1
|
||||||
|
attention_mask = torch.tril(
|
||||||
|
torch.ones((att_mask_batch, seq_length, seq_length), device=data.device)
|
||||||
|
).view(att_mask_batch, 1, seq_length, seq_length)
|
||||||
|
|
||||||
|
# Loss mask.
|
||||||
|
loss_mask = torch.ones(data.size(), dtype=torch.float, device=data.device)
|
||||||
|
if eod_mask_loss:
|
||||||
|
loss_mask[data == eod_token] = 0.0
|
||||||
|
|
||||||
|
# Position ids.
|
||||||
|
position_ids = torch.arange(seq_length, dtype=torch.long, device=data.device)
|
||||||
|
position_ids = position_ids.unsqueeze(0).expand_as(data)
|
||||||
|
# We need to clone as the ids will be modifed based on batch index.
|
||||||
|
if reset_position_ids:
|
||||||
|
position_ids = position_ids.clone()
|
||||||
|
|
||||||
|
if reset_position_ids or reset_attention_mask:
|
||||||
|
# Loop through the batches:
|
||||||
|
for b in range(micro_batch_size):
|
||||||
|
|
||||||
|
# Find indecies where EOD token is.
|
||||||
|
eod_index = position_ids[b, data[b] == eod_token]
|
||||||
|
# Detach indecies from positions if going to modify positions.
|
||||||
|
if reset_position_ids:
|
||||||
|
eod_index = eod_index.clone()
|
||||||
|
|
||||||
|
# Loop through EOD indecies:
|
||||||
|
prev_index = 0
|
||||||
|
for j in range(eod_index.size()[0]):
|
||||||
|
i = eod_index[j]
|
||||||
|
# Mask attention loss.
|
||||||
|
if reset_attention_mask:
|
||||||
|
attention_mask[b, 0, (i + 1) :, : (i + 1)] = 0
|
||||||
|
# Reset positions.
|
||||||
|
if reset_position_ids:
|
||||||
|
position_ids[b, (i + 1) :] -= i + 1 - prev_index
|
||||||
|
prev_index = i + 1
|
||||||
|
|
||||||
|
# Convert attention mask to binary:
|
||||||
|
attention_mask = attention_mask < 0.5
|
||||||
|
|
||||||
|
return attention_mask, loss_mask, position_ids
|
||||||
|
|
||||||
|
|
||||||
|
def get_batch(context_tokens: torch.LongTensor, eod_id: int):
|
||||||
|
"""Generate batch from context tokens."""
|
||||||
|
# Move to GPU.
|
||||||
|
tokens = context_tokens.contiguous().to(context_tokens.device)
|
||||||
|
# Get the attention mask and postition ids.
|
||||||
|
attention_mask, _, position_ids = get_ltor_masks_and_position_ids(
|
||||||
|
tokens,
|
||||||
|
eod_id,
|
||||||
|
reset_position_ids=False,
|
||||||
|
reset_attention_mask=False,
|
||||||
|
eod_mask_loss=False,
|
||||||
|
)
|
||||||
|
return tokens, attention_mask, position_ids
|
||||||
|
|
||||||
|
|
||||||
|
def get_stop_words_ids(chat_format, tokenizer):
|
||||||
|
if chat_format == "raw":
|
||||||
|
stop_words_ids = [tokenizer.encode("Human:"), [tokenizer.eod_id]]
|
||||||
|
elif chat_format == "chatml":
|
||||||
|
stop_words_ids = [[tokenizer.im_end_id], [tokenizer.im_start_id]]
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
||||||
|
return stop_words_ids
|
||||||
|
|
||||||
|
|
||||||
|
def make_context(
|
||||||
|
tokenizer: PreTrainedTokenizer,
|
||||||
|
query: str,
|
||||||
|
history: List[Tuple[str, str]] = None,
|
||||||
|
system: str = "",
|
||||||
|
max_window_size: int = 6144,
|
||||||
|
chat_format: str = "chatml",
|
||||||
|
):
|
||||||
|
if history is None:
|
||||||
|
history = []
|
||||||
|
|
||||||
|
if chat_format == "chatml":
|
||||||
|
im_start, im_end = "<|im_start|>", "<|im_end|>"
|
||||||
|
im_start_tokens = [tokenizer.im_start_id]
|
||||||
|
im_end_tokens = [tokenizer.im_end_id]
|
||||||
|
nl_tokens = tokenizer.encode("\n")
|
||||||
|
|
||||||
|
def _tokenize_str(role, content):
|
||||||
|
return f"{role}\n{content}", tokenizer.encode(
|
||||||
|
role, allowed_special=set()
|
||||||
|
) + nl_tokens + tokenizer.encode(content, allowed_special=set())
|
||||||
|
|
||||||
|
system_text, system_tokens_part = _tokenize_str("system", system)
|
||||||
|
system_tokens = im_start_tokens + system_tokens_part + im_end_tokens
|
||||||
|
|
||||||
|
raw_text = ""
|
||||||
|
context_tokens = []
|
||||||
|
|
||||||
|
for turn_query, turn_response in reversed(history):
|
||||||
|
query_text, query_tokens_part = _tokenize_str("user", turn_query)
|
||||||
|
query_tokens = im_start_tokens + query_tokens_part + im_end_tokens
|
||||||
|
response_text, response_tokens_part = _tokenize_str(
|
||||||
|
"assistant", turn_response
|
||||||
|
)
|
||||||
|
response_tokens = im_start_tokens + response_tokens_part + im_end_tokens
|
||||||
|
|
||||||
|
next_context_tokens = nl_tokens + query_tokens + nl_tokens + response_tokens
|
||||||
|
prev_chat = (
|
||||||
|
f"\n{im_start}{query_text}{im_end}\n{im_start}{response_text}{im_end}"
|
||||||
|
)
|
||||||
|
|
||||||
|
current_context_size = (
|
||||||
|
len(system_tokens) + len(next_context_tokens) + len(context_tokens)
|
||||||
|
)
|
||||||
|
if current_context_size < max_window_size:
|
||||||
|
context_tokens = next_context_tokens + context_tokens
|
||||||
|
raw_text = prev_chat + raw_text
|
||||||
|
else:
|
||||||
|
break
|
||||||
|
|
||||||
|
context_tokens = system_tokens + context_tokens
|
||||||
|
raw_text = f"{im_start}{system_text}{im_end}" + raw_text
|
||||||
|
context_tokens += (
|
||||||
|
nl_tokens
|
||||||
|
+ im_start_tokens
|
||||||
|
+ _tokenize_str("user", query)[1]
|
||||||
|
+ im_end_tokens
|
||||||
|
+ nl_tokens
|
||||||
|
+ im_start_tokens
|
||||||
|
+ tokenizer.encode("assistant")
|
||||||
|
+ nl_tokens
|
||||||
|
)
|
||||||
|
raw_text += f"\n{im_start}user\n{query}{im_end}\n{im_start}assistant\n"
|
||||||
|
|
||||||
|
elif chat_format == "raw":
|
||||||
|
raw_text = query
|
||||||
|
context_tokens = tokenizer.encode(raw_text)
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
||||||
|
|
||||||
|
return raw_text, context_tokens
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_default(
|
||||||
|
tokens: List[int],
|
||||||
|
*,
|
||||||
|
stop_words: List[str],
|
||||||
|
eod_words: List[str],
|
||||||
|
tokenizer: PreTrainedTokenizer,
|
||||||
|
raw_text_len: int,
|
||||||
|
verbose: bool = False,
|
||||||
|
return_end_reason: bool = False,
|
||||||
|
errors: str='replace',
|
||||||
|
):
|
||||||
|
trim_decode_tokens = tokenizer.decode(tokens, errors=errors)[raw_text_len:]
|
||||||
|
if verbose:
|
||||||
|
print("\nRaw Generate: ", trim_decode_tokens)
|
||||||
|
|
||||||
|
end_reason = f"Gen length {len(tokens)}"
|
||||||
|
for stop_word in stop_words:
|
||||||
|
trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
|
||||||
|
for eod_word in eod_words:
|
||||||
|
if eod_word in trim_decode_tokens:
|
||||||
|
end_reason = f"Gen {eod_word!r}"
|
||||||
|
trim_decode_tokens = trim_decode_tokens.split(eod_word)[0]
|
||||||
|
trim_decode_tokens = trim_decode_tokens.strip()
|
||||||
|
if verbose:
|
||||||
|
print("\nEnd Reason:", end_reason)
|
||||||
|
print("\nGenerate: ", trim_decode_tokens)
|
||||||
|
|
||||||
|
if return_end_reason:
|
||||||
|
return trim_decode_tokens, end_reason
|
||||||
|
else:
|
||||||
|
return trim_decode_tokens
|
||||||
|
|
||||||
|
|
||||||
|
def _decode_chatml(
|
||||||
|
tokens: List[int],
|
||||||
|
*,
|
||||||
|
stop_words: List[str],
|
||||||
|
eod_token_ids: List[int],
|
||||||
|
tokenizer: PreTrainedTokenizer,
|
||||||
|
raw_text_len: int,
|
||||||
|
context_length: int,
|
||||||
|
verbose: bool = False,
|
||||||
|
return_end_reason: bool = False,
|
||||||
|
errors: str='replace'
|
||||||
|
):
|
||||||
|
end_reason = f"Gen length {len(tokens)}"
|
||||||
|
eod_token_idx = context_length
|
||||||
|
for eod_token_idx in range(context_length, len(tokens)):
|
||||||
|
if tokens[eod_token_idx] in eod_token_ids:
|
||||||
|
end_reason = f"Gen {tokenizer.decode([tokens[eod_token_idx]])!r}"
|
||||||
|
break
|
||||||
|
|
||||||
|
trim_decode_tokens = tokenizer.decode(tokens[:eod_token_idx], errors=errors)[raw_text_len:]
|
||||||
|
if verbose:
|
||||||
|
print("\nRaw Generate w/o EOD:", tokenizer.decode(tokens, errors=errors)[raw_text_len:])
|
||||||
|
print("\nRaw Generate:", trim_decode_tokens)
|
||||||
|
print("\nEnd Reason:", end_reason)
|
||||||
|
for stop_word in stop_words:
|
||||||
|
trim_decode_tokens = trim_decode_tokens.replace(stop_word, "").strip()
|
||||||
|
trim_decode_tokens = trim_decode_tokens.strip()
|
||||||
|
if verbose:
|
||||||
|
print("\nGenerate:", trim_decode_tokens)
|
||||||
|
|
||||||
|
if return_end_reason:
|
||||||
|
return trim_decode_tokens, end_reason
|
||||||
|
else:
|
||||||
|
return trim_decode_tokens
|
||||||
|
|
||||||
|
|
||||||
|
def decode_tokens(
|
||||||
|
tokens: Union[torch.LongTensor, TokensType],
|
||||||
|
tokenizer: PreTrainedTokenizer,
|
||||||
|
raw_text_len: int,
|
||||||
|
context_length: int,
|
||||||
|
chat_format: str,
|
||||||
|
verbose: bool = False,
|
||||||
|
return_end_reason: bool = False,
|
||||||
|
errors: str="replace",
|
||||||
|
) -> str:
|
||||||
|
if torch.is_tensor(tokens):
|
||||||
|
tokens = tokens.cpu().numpy().tolist()
|
||||||
|
|
||||||
|
if chat_format == "chatml":
|
||||||
|
return _decode_chatml(
|
||||||
|
tokens,
|
||||||
|
stop_words=[],
|
||||||
|
eod_token_ids=[tokenizer.im_start_id, tokenizer.im_end_id],
|
||||||
|
tokenizer=tokenizer,
|
||||||
|
raw_text_len=raw_text_len,
|
||||||
|
context_length=context_length,
|
||||||
|
verbose=verbose,
|
||||||
|
return_end_reason=return_end_reason,
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
|
elif chat_format == "raw":
|
||||||
|
return _decode_default(
|
||||||
|
tokens,
|
||||||
|
stop_words=["<|endoftext|>"],
|
||||||
|
eod_words=["<|endoftext|>"],
|
||||||
|
tokenizer=tokenizer,
|
||||||
|
raw_text_len=raw_text_len,
|
||||||
|
verbose=verbose,
|
||||||
|
return_end_reason=return_end_reason,
|
||||||
|
errors=errors,
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
raise NotImplementedError(f"Unknown chat format {chat_format!r}")
|
||||||
|
|
||||||
|
|
||||||
|
class StopWordsLogitsProcessor(LogitsProcessor):
|
||||||
|
"""
|
||||||
|
:class:`transformers.LogitsProcessor` that enforces that when specified sequences appear, stop geration.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
stop_words_ids (:obj:`List[List[int]]`):
|
||||||
|
List of list of token ids of stop ids. In order to get the tokens of the words
|
||||||
|
that should not appear in the generated text, use :obj:`tokenizer(bad_word,
|
||||||
|
add_prefix_space=True).input_ids`.
|
||||||
|
eos_token_id (:obj:`int`):
|
||||||
|
The id of the `end-of-sequence` token.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, stop_words_ids: Iterable[Iterable[int]], eos_token_id: int):
|
||||||
|
|
||||||
|
if not isinstance(stop_words_ids, List) or len(stop_words_ids) == 0:
|
||||||
|
raise ValueError(
|
||||||
|
f"`stop_words_ids` has to be a non-emtpy list, but is {stop_words_ids}."
|
||||||
|
)
|
||||||
|
if any(not isinstance(bad_word_ids, list) for bad_word_ids in stop_words_ids):
|
||||||
|
raise ValueError(
|
||||||
|
f"`stop_words_ids` has to be a list of lists, but is {stop_words_ids}."
|
||||||
|
)
|
||||||
|
if any(
|
||||||
|
any(
|
||||||
|
(not isinstance(token_id, (int, np.integer)) or token_id < 0)
|
||||||
|
for token_id in stop_word_ids
|
||||||
|
)
|
||||||
|
for stop_word_ids in stop_words_ids
|
||||||
|
):
|
||||||
|
raise ValueError(
|
||||||
|
f"Each list in `stop_words_ids` has to be a list of positive integers, but is {stop_words_ids}."
|
||||||
|
)
|
||||||
|
|
||||||
|
self.stop_words_ids = list(
|
||||||
|
filter(
|
||||||
|
lambda bad_token_seq: bad_token_seq != [eos_token_id], stop_words_ids
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self.eos_token_id = eos_token_id
|
||||||
|
for stop_token_seq in self.stop_words_ids:
|
||||||
|
assert (
|
||||||
|
len(stop_token_seq) > 0
|
||||||
|
), "Stop words token sequences {} cannot have an empty list".format(
|
||||||
|
stop_words_ids
|
||||||
|
)
|
||||||
|
|
||||||
|
def __call__(
|
||||||
|
self, input_ids: torch.LongTensor, scores: torch.FloatTensor
|
||||||
|
) -> torch.FloatTensor:
|
||||||
|
stopped_samples = self._calc_stopped_samples(input_ids)
|
||||||
|
for i, should_stop in enumerate(stopped_samples):
|
||||||
|
if should_stop:
|
||||||
|
scores[i, self.eos_token_id] = float(2**15)
|
||||||
|
return scores
|
||||||
|
|
||||||
|
def _tokens_match(self, prev_tokens: torch.LongTensor, tokens: List[int]) -> bool:
|
||||||
|
if len(tokens) == 0:
|
||||||
|
# if bad word tokens is just one token always ban it
|
||||||
|
return True
|
||||||
|
elif len(tokens) > len(prev_tokens):
|
||||||
|
# if bad word tokens are longer then prev input_ids they can't be equal
|
||||||
|
return False
|
||||||
|
elif prev_tokens[-len(tokens) :].tolist() == tokens:
|
||||||
|
# if tokens match
|
||||||
|
return True
|
||||||
|
else:
|
||||||
|
return False
|
||||||
|
|
||||||
|
def _calc_stopped_samples(self, prev_input_ids: Iterable[int]) -> Iterable[int]:
|
||||||
|
stopped_samples = []
|
||||||
|
for prev_input_ids_slice in prev_input_ids:
|
||||||
|
match = False
|
||||||
|
for stop_token_seq in self.stop_words_ids:
|
||||||
|
if self._tokens_match(prev_input_ids_slice, stop_token_seq):
|
||||||
|
# if tokens do not match continue
|
||||||
|
match = True
|
||||||
|
break
|
||||||
|
stopped_samples.append(match)
|
||||||
|
|
||||||
|
return stopped_samples
|
||||||
|
|
||||||
|
|
||||||
|
def top_k_logits(logits, top_k=0, top_p=0.0, filter_value=-float("Inf")):
|
||||||
|
"""This function has been mostly taken from huggingface conversational
|
||||||
|
ai code at
|
||||||
|
https://medium.com/huggingface/how-to-build-a-state-of-the-art-
|
||||||
|
conversational-ai-with-transfer-learning-2d818ac26313"""
|
||||||
|
|
||||||
|
if top_k > 0:
|
||||||
|
# Remove all tokens with a probability less than the
|
||||||
|
# last token of the top-k
|
||||||
|
indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]
|
||||||
|
logits[indices_to_remove] = filter_value
|
||||||
|
|
||||||
|
if top_p > 0.0:
|
||||||
|
# Cconvert to 1D
|
||||||
|
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
|
||||||
|
cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
|
||||||
|
|
||||||
|
# Remove tokens with cumulative probability above the threshold
|
||||||
|
sorted_indices_to_remove = cumulative_probs > top_p
|
||||||
|
# Shift the indices to the right to keep also the first token
|
||||||
|
# above the threshold
|
||||||
|
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
|
||||||
|
sorted_indices_to_remove[..., 0] = 0
|
||||||
|
for i in range(sorted_indices.size(0)):
|
||||||
|
indices_to_remove = sorted_indices[i][sorted_indices_to_remove[i]]
|
||||||
|
logits[i][indices_to_remove] = filter_value
|
||||||
|
|
||||||
|
return logits
|
||||||
|
|
||||||
|
|
||||||
|
def switch(val1, val2, boolean):
|
||||||
|
boolean = boolean.type_as(val1)
|
||||||
|
return (1 - boolean) * val1 + boolean * val2
|
||||||
6
special_tokens_map.json
Normal file
6
special_tokens_map.json
Normal file
@@ -0,0 +1,6 @@
|
|||||||
|
{
|
||||||
|
"bos_token": "<|extra_203|>",
|
||||||
|
"eos_token": "<|im_end|>",
|
||||||
|
"unk_token": "<|endoftext|>",
|
||||||
|
"pad_token": "<|endoftext|>"
|
||||||
|
}
|
||||||
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)
|
||||||
11
tokenizer_config.json
Normal file
11
tokenizer_config.json
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
{
|
||||||
|
"model_max_length": 8192,
|
||||||
|
"tokenizer_class": "QWenTokenizer",
|
||||||
|
"auto_map": {
|
||||||
|
"AutoTokenizer": [
|
||||||
|
"tokenization_qwen.QWenTokenizer",
|
||||||
|
null
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"chat_template": "{% for message in messages %}{% if loop.first and messages[0]['role'] != 'system' %}{{ '<|im_start|>system\nYou are a helpful assistant<|im_end|>\n' }}{% endif %}{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant\n' }}{% endif %}"
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user