Upload folder using huggingface_hub
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- Lordos4x/test/README.mdAdded+59
- Lordos4x/test/adapter_config.jsonAdded+26
- Lordos4x/test/adapter_model.safetensorsAdded+3
- Lordos4x/test/all_results.jsonAdded+7
- Lordos4x/test/checkpoint-100/README.mdAdded+204
- Lordos4x/test/checkpoint-100/adapter_config.jsonAdded+26
- Lordos4x/test/checkpoint-100/adapter_model.safetensorsAdded+3
- Lordos4x/test/checkpoint-100/optimizer.ptAdded+3
- Lordos4x/test/checkpoint-100/qwen.tiktokenAdded
- Lordos4x/test/checkpoint-100/rng_state.pthAdded+3
- Lordos4x/test/checkpoint-100/scheduler.ptAdded+3
- Lordos4x/test/checkpoint-100/special_tokens_map.jsonAdded+4
- Lordos4x/test/checkpoint-100/tokenization_qwen.pyAdded+276
- Lordos4x/test/checkpoint-100/tokenizer_config.jsonAdded+16
- Lordos4x/test/checkpoint-100/trainer_state.jsonAdded+141
- Lordos4x/test/checkpoint-100/training_args.binAdded+3
- Lordos4x/test/checkpoint-200/README.mdAdded+204
- Lordos4x/test/checkpoint-200/adapter_config.jsonAdded+26
- Lordos4x/test/checkpoint-200/adapter_model.safetensorsAdded+3
- Lordos4x/test/checkpoint-200/optimizer.ptAdded+3
- Lordos4x/test/checkpoint-200/qwen.tiktokenAdded
- Lordos4x/test/checkpoint-200/rng_state.pthAdded+3
- Lordos4x/test/checkpoint-200/scheduler.ptAdded+3
- Lordos4x/test/checkpoint-200/special_tokens_map.jsonAdded+4
- Lordos4x/test/checkpoint-200/tokenization_qwen.pyAdded+276
- Lordos4x/test/checkpoint-200/tokenizer_config.jsonAdded+16
- Lordos4x/test/checkpoint-200/trainer_state.jsonAdded+261
- Lordos4x/test/checkpoint-200/training_args.binAdded+3
- Lordos4x/test/checkpoint-300/README.mdAdded+204
- Lordos4x/test/checkpoint-300/adapter_config.jsonAdded+26
- Lordos4x/test/checkpoint-300/adapter_model.safetensorsAdded+3
- Lordos4x/test/checkpoint-300/optimizer.ptAdded+3
- Lordos4x/test/checkpoint-300/qwen.tiktokenAdded
- Lordos4x/test/checkpoint-300/rng_state.pthAdded+3
- Lordos4x/test/checkpoint-300/scheduler.ptAdded+3
- Lordos4x/test/checkpoint-300/special_tokens_map.jsonAdded+4
- Lordos4x/test/checkpoint-300/tokenization_qwen.pyAdded+276
- Lordos4x/test/checkpoint-300/tokenizer_config.jsonAdded+16
- Lordos4x/test/checkpoint-300/trainer_state.jsonAdded+381
- Lordos4x/test/checkpoint-300/training_args.binAdded+3
- Lordos4x/test/checkpoint-400/README.mdAdded+204
- Lordos4x/test/checkpoint-400/adapter_config.jsonAdded+26
- Lordos4x/test/checkpoint-400/adapter_model.safetensorsAdded+3
- Lordos4x/test/checkpoint-400/optimizer.ptAdded+3
- Lordos4x/test/checkpoint-400/qwen.tiktokenAdded
- Lordos4x/test/checkpoint-400/rng_state.pthAdded+3
- Lordos4x/test/checkpoint-400/scheduler.ptAdded+3
- Lordos4x/test/checkpoint-400/special_tokens_map.jsonAdded+4
- Lordos4x/test/checkpoint-400/tokenization_qwen.pyAdded+276
- Lordos4x/test/checkpoint-400/tokenizer_config.jsonAdded+16
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859---license: otherlibrary_name: pefttags:- llama-factory- lora- generated_from_trainerbase_model: /root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chatmodel-index:- name: '2024' results: []---
<!-- This model card has been generated automatically according to the information the Trainer had access to. Youshould probably proofread and complete it, then remove this comment. -->
# 2024
This model is a fine-tuned version of [/root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat](https://huggingface.co//root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat) on the alpaca_gpt4_en dataset.
## Model description
More information needed
## Intended uses & limitations
More information needed
## Training and evaluation data
More information needed
## Training procedure
### Training hyperparameters
The following hyperparameters were used during training:- learning_rate: 5e-05- train_batch_size: 4- eval_batch_size: 8- seed: 42- gradient_accumulation_steps: 4- total_train_batch_size: 16- optimizer: Adam with betas=(0.9,0.999) and epsilon=1e-08- lr_scheduler_type: cosine- num_epochs: 1.0- mixed_precision_training: Native AMP
### Training results
### Framework versions
- PEFT 0.8.2- Transformers 4.37.2- Pytorch 2.1.2- Datasets 2.16.1- Tokenizers 0.15.11234567891011121314151617181920212223242526{ "alpha_pattern": {}, "auto_mapping": null, "base_model_name_or_path": "/root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat", "bias": "none", "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 16, "lora_dropout": 0.1, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "peft_type": "LORA", "r": 8, "rank_pattern": {}, "revision": null, "target_modules": [ "c_attn" ], "task_type": "CAUSAL_LM", "use_rslora": false}123version https://git-lfs.github.com/spec/v1oid sha256:d690fea72ea9dee2d7476c49dd21be737318010206887ec482f06df4062dfeb3size 62976001234567{ "epoch": 1.0, "train_loss": 1.2522715446472168, "train_runtime": 2170.1492, "train_samples_per_second": 4.608, "train_steps_per_second": 0.288}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204---library_name: peftbase_model: /root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat---
# 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. -->
- **Developed by:** [More Information Needed]- **Funded by [optional]:** [More Information Needed]- **Shared by [optional]:** [More Information Needed]- **Model type:** [More Information Needed]- **Language(s) (NLP):** [More Information Needed]- **License:** [More Information Needed]- **Finetuned from model [optional]:** [More Information Needed]
### 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. -->
[More Information Needed]
### 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.
[More Information Needed]
## 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. -->
[More Information Needed]
### 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
- **Training regime:** [More Information Needed] <!--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
[More Information Needed]
#### 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]
### Framework versions
- PEFT 0.8.21234567891011121314151617181920212223242526{ "alpha_pattern": {}, "auto_mapping": null, "base_model_name_or_path": "/root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat", "bias": "none", "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 16, "lora_dropout": 0.1, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "peft_type": "LORA", "r": 8, "rank_pattern": {}, "revision": null, "target_modules": [ "c_attn" ], "task_type": "CAUSAL_LM", "use_rslora": false}123version https://git-lfs.github.com/spec/v1oid sha256:cbf1988e3cde626fb663fd94f605a2057179b4f8843506c89503d3fcee77a5bdsize 6297600123version https://git-lfs.github.com/spec/v1oid sha256:29fb78e4926b30a824db0768e573bf9ce042343a17a48c3f1edf6e48211cc320size 12623610123version https://git-lfs.github.com/spec/v1oid sha256:b3d9312a6f6e154ccb12cc7928ee3ca010f4347c57642af019a8f5ee118df44fsize 14244123version https://git-lfs.github.com/spec/v1oid sha256:a3597d5e084ef95fd637f3f366e4f6165284f8a75385cb930f4b53b546344852size 10641234{ "eos_token": "<|im_end|>", "pad_token": "<|endoftext|>"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276# 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 base64import loggingimport osimport unicodedatafrom typing import Collection, Dict, List, Set, Tuple, Union
import tiktokenfrom 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 impactEXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))# changed to use actual index to avoid misconfiguration with vocabulary expansionSPECIAL_START_ID = 151643SPECIAL_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)12345678910111213141516{ "added_tokens_decoder": {}, "auto_map": { "AutoTokenizer": [ "tokenization_qwen.QWenTokenizer", null ] }, "clean_up_tokenization_spaces": true, "eos_token": "<|im_end|>", "model_max_length": 8192, "pad_token": "<|endoftext|>", "padding_side": "right", "split_special_tokens": false, "tokenizer_class": "QWenTokenizer"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141{ "best_metric": null, "best_model_checkpoint": null, "epoch": 0.16, "eval_steps": 500, "global_step": 100, "is_hyper_param_search": false, "is_local_process_zero": true, "is_world_process_zero": true, "log_history": [ { "epoch": 0.01, "learning_rate": 4.99921047320825e-05, "loss": 1.3272, "step": 5 }, { "epoch": 0.02, "learning_rate": 4.996842391515044e-05, "loss": 1.4074, "step": 10 }, { "epoch": 0.02, "learning_rate": 4.992897250651535e-05, "loss": 1.3206, "step": 15 }, { "epoch": 0.03, "learning_rate": 4.987377542453251e-05, "loss": 1.2691, "step": 20 }, { "epoch": 0.04, "learning_rate": 4.980286753286195e-05, "loss": 1.2404, "step": 25 }, { "epoch": 0.05, "learning_rate": 4.971629361844785e-05, "loss": 1.2842, "step": 30 }, { "epoch": 0.06, "learning_rate": 4.9614108363230135e-05, "loss": 1.2281, "step": 35 }, { "epoch": 0.06, "learning_rate": 4.949637630960617e-05, "loss": 1.2607, "step": 40 }, { "epoch": 0.07, "learning_rate": 4.9363171819664434e-05, "loss": 1.3113, "step": 45 }, { "epoch": 0.08, "learning_rate": 4.9214579028215776e-05, "loss": 1.2577, "step": 50 }, { "epoch": 0.09, "learning_rate": 4.905069178965215e-05, "loss": 1.2397, "step": 55 }, { "epoch": 0.1, "learning_rate": 4.887161361866608e-05, "loss": 1.219, "step": 60 }, { "epoch": 0.1, "learning_rate": 4.867745762486861e-05, "loss": 1.1894, "step": 65 }, { "epoch": 0.11, "learning_rate": 4.846834644134686e-05, "loss": 1.2301, "step": 70 }, { "epoch": 0.12, "learning_rate": 4.8244412147206284e-05, "loss": 1.1576, "step": 75 }, { "epoch": 0.13, "learning_rate": 4.800579618414676e-05, "loss": 1.2253, "step": 80 }, { "epoch": 0.14, "learning_rate": 4.775264926712489e-05, "loss": 1.327, "step": 85 }, { "epoch": 0.14, "learning_rate": 4.7485131289159276e-05, "loss": 1.217, "step": 90 }, { "epoch": 0.15, "learning_rate": 4.720341122033862e-05, "loss": 1.2694, "step": 95 }, { "epoch": 0.16, "learning_rate": 4.690766700109659e-05, "loss": 1.2352, "step": 100 } ], "logging_steps": 5, "max_steps": 625, "num_input_tokens_seen": 0, "num_train_epochs": 1, "save_steps": 100, "total_flos": 4570567105708032.0, "train_batch_size": 4, "trial_name": null, "trial_params": null}123version https://git-lfs.github.com/spec/v1oid sha256:b815e38a230d037df7896cb286b9f709dfeb8104461486a0980a49299c45b3e1size 4920123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204---library_name: peftbase_model: /root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat---
# 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. -->
- **Developed by:** [More Information Needed]- **Funded by [optional]:** [More Information Needed]- **Shared by [optional]:** [More Information Needed]- **Model type:** [More Information Needed]- **Language(s) (NLP):** [More Information Needed]- **License:** [More Information Needed]- **Finetuned from model [optional]:** [More Information Needed]
### 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. -->
[More Information Needed]
### 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.
[More Information Needed]
## 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. -->
[More Information Needed]
### 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
- **Training regime:** [More Information Needed] <!--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
[More Information Needed]
#### 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]
### Framework versions
- PEFT 0.8.21234567891011121314151617181920212223242526{ "alpha_pattern": {}, "auto_mapping": null, "base_model_name_or_path": "/root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat", "bias": "none", "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 16, "lora_dropout": 0.1, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "peft_type": "LORA", "r": 8, "rank_pattern": {}, "revision": null, "target_modules": [ "c_attn" ], "task_type": "CAUSAL_LM", "use_rslora": false}123version https://git-lfs.github.com/spec/v1oid sha256:81bdc655e1367b933e06c1746bf8c41d051352a37af0ebdff2a368a52df1196fsize 6297600123version https://git-lfs.github.com/spec/v1oid sha256:460fb096fc1277a2e20e11880f313e297e8554350bdd642242c217b6a867371csize 12623610123version https://git-lfs.github.com/spec/v1oid sha256:e6203b33d5a2c894c8bee5bc07ff5536e5dfad9be97d6f48788669feb5e7d25fsize 14244123version https://git-lfs.github.com/spec/v1oid sha256:763bcd9b1429996cf4d18e6198a0d2544d7a1ea81e94b1b68d8f369feda61e36size 10641234{ "eos_token": "<|im_end|>", "pad_token": "<|endoftext|>"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276# 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 base64import loggingimport osimport unicodedatafrom typing import Collection, Dict, List, Set, Tuple, Union
import tiktokenfrom 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 impactEXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))# changed to use actual index to avoid misconfiguration with vocabulary expansionSPECIAL_START_ID = 151643SPECIAL_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)12345678910111213141516{ "added_tokens_decoder": {}, "auto_map": { "AutoTokenizer": [ "tokenization_qwen.QWenTokenizer", null ] }, "clean_up_tokenization_spaces": true, "eos_token": "<|im_end|>", "model_max_length": 8192, "pad_token": "<|endoftext|>", "padding_side": "right", "split_special_tokens": false, "tokenizer_class": "QWenTokenizer"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261{ "best_metric": null, "best_model_checkpoint": null, "epoch": 0.32, "eval_steps": 500, "global_step": 200, "is_hyper_param_search": false, "is_local_process_zero": true, "is_world_process_zero": true, "log_history": [ { "epoch": 0.01, "learning_rate": 4.99921047320825e-05, "loss": 1.3272, "step": 5 }, { "epoch": 0.02, "learning_rate": 4.996842391515044e-05, "loss": 1.4074, "step": 10 }, { "epoch": 0.02, "learning_rate": 4.992897250651535e-05, "loss": 1.3206, "step": 15 }, { "epoch": 0.03, "learning_rate": 4.987377542453251e-05, "loss": 1.2691, "step": 20 }, { "epoch": 0.04, "learning_rate": 4.980286753286195e-05, "loss": 1.2404, "step": 25 }, { "epoch": 0.05, "learning_rate": 4.971629361844785e-05, "loss": 1.2842, "step": 30 }, { "epoch": 0.06, "learning_rate": 4.9614108363230135e-05, "loss": 1.2281, "step": 35 }, { "epoch": 0.06, "learning_rate": 4.949637630960617e-05, "loss": 1.2607, "step": 40 }, { "epoch": 0.07, "learning_rate": 4.9363171819664434e-05, "loss": 1.3113, "step": 45 }, { "epoch": 0.08, "learning_rate": 4.9214579028215776e-05, "loss": 1.2577, "step": 50 }, { "epoch": 0.09, "learning_rate": 4.905069178965215e-05, "loss": 1.2397, "step": 55 }, { "epoch": 0.1, "learning_rate": 4.887161361866608e-05, "loss": 1.219, "step": 60 }, { "epoch": 0.1, "learning_rate": 4.867745762486861e-05, "loss": 1.1894, "step": 65 }, { "epoch": 0.11, "learning_rate": 4.846834644134686e-05, "loss": 1.2301, "step": 70 }, { "epoch": 0.12, "learning_rate": 4.8244412147206284e-05, "loss": 1.1576, "step": 75 }, { "epoch": 0.13, "learning_rate": 4.800579618414676e-05, "loss": 1.2253, "step": 80 }, { "epoch": 0.14, "learning_rate": 4.775264926712489e-05, "loss": 1.327, "step": 85 }, { "epoch": 0.14, "learning_rate": 4.7485131289159276e-05, "loss": 1.217, "step": 90 }, { "epoch": 0.15, "learning_rate": 4.720341122033862e-05, "loss": 1.2694, "step": 95 }, { "epoch": 0.16, "learning_rate": 4.690766700109659e-05, "loss": 1.2352, "step": 100 }, { "epoch": 0.17, "learning_rate": 4.659808542982088e-05, "loss": 1.2486, "step": 105 }, { "epoch": 0.18, "learning_rate": 4.6274862044867304e-05, "loss": 1.2909, "step": 110 }, { "epoch": 0.18, "learning_rate": 4.593820100105355e-05, "loss": 1.2775, "step": 115 }, { "epoch": 0.19, "learning_rate": 4.558831494071069e-05, "loss": 1.2828, "step": 120 }, { "epoch": 0.2, "learning_rate": 4.522542485937369e-05, "loss": 1.2764, "step": 125 }, { "epoch": 0.21, "learning_rate": 4.484975996619589e-05, "loss": 1.2725, "step": 130 }, { "epoch": 0.22, "learning_rate": 4.4461557539175594e-05, "loss": 1.1917, "step": 135 }, { "epoch": 0.22, "learning_rate": 4.40610627752862e-05, "loss": 1.2756, "step": 140 }, { "epoch": 0.23, "learning_rate": 4.3648528635604556e-05, "loss": 1.2373, "step": 145 }, { "epoch": 0.24, "learning_rate": 4.3224215685535294e-05, "loss": 1.3337, "step": 150 }, { "epoch": 0.25, "learning_rate": 4.278839193023214e-05, "loss": 1.2876, "step": 155 }, { "epoch": 0.26, "learning_rate": 4.234133264532012e-05, "loss": 1.2702, "step": 160 }, { "epoch": 0.26, "learning_rate": 4.188332020302561e-05, "loss": 1.2058, "step": 165 }, { "epoch": 0.27, "learning_rate": 4.1414643893823914e-05, "loss": 1.2134, "step": 170 }, { "epoch": 0.28, "learning_rate": 4.093559974371725e-05, "loss": 1.2687, "step": 175 }, { "epoch": 0.29, "learning_rate": 4.044649032725836e-05, "loss": 1.1337, "step": 180 }, { "epoch": 0.3, "learning_rate": 3.9947624576437975e-05, "loss": 1.3005, "step": 185 }, { "epoch": 0.3, "learning_rate": 3.943931758555669e-05, "loss": 1.2973, "step": 190 }, { "epoch": 0.31, "learning_rate": 3.8921890412204705e-05, "loss": 1.3638, "step": 195 }, { "epoch": 0.32, "learning_rate": 3.8395669874474915e-05, "loss": 1.263, "step": 200 } ], "logging_steps": 5, "max_steps": 625, "num_input_tokens_seen": 0, "num_train_epochs": 1, "save_steps": 100, "total_flos": 9098322714820608.0, "train_batch_size": 4, "trial_name": null, "trial_params": null}123version https://git-lfs.github.com/spec/v1oid sha256:b815e38a230d037df7896cb286b9f709dfeb8104461486a0980a49299c45b3e1size 4920123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204---library_name: peftbase_model: /root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat---
# 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. -->
- **Developed by:** [More Information Needed]- **Funded by [optional]:** [More Information Needed]- **Shared by [optional]:** [More Information Needed]- **Model type:** [More Information Needed]- **Language(s) (NLP):** [More Information Needed]- **License:** [More Information Needed]- **Finetuned from model [optional]:** [More Information Needed]
### 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. -->
[More Information Needed]
### 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.
[More Information Needed]
## 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. -->
[More Information Needed]
### 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
- **Training regime:** [More Information Needed] <!--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
[More Information Needed]
#### 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]
### Framework versions
- PEFT 0.8.21234567891011121314151617181920212223242526{ "alpha_pattern": {}, "auto_mapping": null, "base_model_name_or_path": "/root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat", "bias": "none", "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 16, "lora_dropout": 0.1, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "peft_type": "LORA", "r": 8, "rank_pattern": {}, "revision": null, "target_modules": [ "c_attn" ], "task_type": "CAUSAL_LM", "use_rslora": false}123version https://git-lfs.github.com/spec/v1oid sha256:7ad5fe313e4dd4909768ab763db2e388eb17afa54b3263c094ea98f5c9646db3size 6297600123version https://git-lfs.github.com/spec/v1oid sha256:0c545eb4966f7df95f64e7ddc73f6475e86c51bf6a2a8de1bf9aaac83f2d2629size 12623610123version https://git-lfs.github.com/spec/v1oid sha256:52c73e1b687d924168a51452ca3f3491dbb0e8c005ec13c1c9e710351c37fb83size 14244123version https://git-lfs.github.com/spec/v1oid sha256:105bb81cd4f3c8e8164730c6d2135902f073f039ec577bf17203fcc57d1e8504size 10641234{ "eos_token": "<|im_end|>", "pad_token": "<|endoftext|>"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276# 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 base64import loggingimport osimport unicodedatafrom typing import Collection, Dict, List, Set, Tuple, Union
import tiktokenfrom 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 impactEXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))# changed to use actual index to avoid misconfiguration with vocabulary expansionSPECIAL_START_ID = 151643SPECIAL_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)12345678910111213141516{ "added_tokens_decoder": {}, "auto_map": { "AutoTokenizer": [ "tokenization_qwen.QWenTokenizer", null ] }, "clean_up_tokenization_spaces": true, "eos_token": "<|im_end|>", "model_max_length": 8192, "pad_token": "<|endoftext|>", "padding_side": "right", "split_special_tokens": false, "tokenizer_class": "QWenTokenizer"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381{ "best_metric": null, "best_model_checkpoint": null, "epoch": 0.48, "eval_steps": 500, "global_step": 300, "is_hyper_param_search": false, "is_local_process_zero": true, "is_world_process_zero": true, "log_history": [ { "epoch": 0.01, "learning_rate": 4.99921047320825e-05, "loss": 1.3272, "step": 5 }, { "epoch": 0.02, "learning_rate": 4.996842391515044e-05, "loss": 1.4074, "step": 10 }, { "epoch": 0.02, "learning_rate": 4.992897250651535e-05, "loss": 1.3206, "step": 15 }, { "epoch": 0.03, "learning_rate": 4.987377542453251e-05, "loss": 1.2691, "step": 20 }, { "epoch": 0.04, "learning_rate": 4.980286753286195e-05, "loss": 1.2404, "step": 25 }, { "epoch": 0.05, "learning_rate": 4.971629361844785e-05, "loss": 1.2842, "step": 30 }, { "epoch": 0.06, "learning_rate": 4.9614108363230135e-05, "loss": 1.2281, "step": 35 }, { "epoch": 0.06, "learning_rate": 4.949637630960617e-05, "loss": 1.2607, "step": 40 }, { "epoch": 0.07, "learning_rate": 4.9363171819664434e-05, "loss": 1.3113, "step": 45 }, { "epoch": 0.08, "learning_rate": 4.9214579028215776e-05, "loss": 1.2577, "step": 50 }, { "epoch": 0.09, "learning_rate": 4.905069178965215e-05, "loss": 1.2397, "step": 55 }, { "epoch": 0.1, "learning_rate": 4.887161361866608e-05, "loss": 1.219, "step": 60 }, { "epoch": 0.1, "learning_rate": 4.867745762486861e-05, "loss": 1.1894, "step": 65 }, { "epoch": 0.11, "learning_rate": 4.846834644134686e-05, "loss": 1.2301, "step": 70 }, { "epoch": 0.12, "learning_rate": 4.8244412147206284e-05, "loss": 1.1576, "step": 75 }, { "epoch": 0.13, "learning_rate": 4.800579618414676e-05, "loss": 1.2253, "step": 80 }, { "epoch": 0.14, "learning_rate": 4.775264926712489e-05, "loss": 1.327, "step": 85 }, { "epoch": 0.14, "learning_rate": 4.7485131289159276e-05, "loss": 1.217, "step": 90 }, { "epoch": 0.15, "learning_rate": 4.720341122033862e-05, "loss": 1.2694, "step": 95 }, { "epoch": 0.16, "learning_rate": 4.690766700109659e-05, "loss": 1.2352, "step": 100 }, { "epoch": 0.17, "learning_rate": 4.659808542982088e-05, "loss": 1.2486, "step": 105 }, { "epoch": 0.18, "learning_rate": 4.6274862044867304e-05, "loss": 1.2909, "step": 110 }, { "epoch": 0.18, "learning_rate": 4.593820100105355e-05, "loss": 1.2775, "step": 115 }, { "epoch": 0.19, "learning_rate": 4.558831494071069e-05, "loss": 1.2828, "step": 120 }, { "epoch": 0.2, "learning_rate": 4.522542485937369e-05, "loss": 1.2764, "step": 125 }, { "epoch": 0.21, "learning_rate": 4.484975996619589e-05, "loss": 1.2725, "step": 130 }, { "epoch": 0.22, "learning_rate": 4.4461557539175594e-05, "loss": 1.1917, "step": 135 }, { "epoch": 0.22, "learning_rate": 4.40610627752862e-05, "loss": 1.2756, "step": 140 }, { "epoch": 0.23, "learning_rate": 4.3648528635604556e-05, "loss": 1.2373, "step": 145 }, { "epoch": 0.24, "learning_rate": 4.3224215685535294e-05, "loss": 1.3337, "step": 150 }, { "epoch": 0.25, "learning_rate": 4.278839193023214e-05, "loss": 1.2876, "step": 155 }, { "epoch": 0.26, "learning_rate": 4.234133264532012e-05, "loss": 1.2702, "step": 160 }, { "epoch": 0.26, "learning_rate": 4.188332020302561e-05, "loss": 1.2058, "step": 165 }, { "epoch": 0.27, "learning_rate": 4.1414643893823914e-05, "loss": 1.2134, "step": 170 }, { "epoch": 0.28, "learning_rate": 4.093559974371725e-05, "loss": 1.2687, "step": 175 }, { "epoch": 0.29, "learning_rate": 4.044649032725836e-05, "loss": 1.1337, "step": 180 }, { "epoch": 0.3, "learning_rate": 3.9947624576437975e-05, "loss": 1.3005, "step": 185 }, { "epoch": 0.3, "learning_rate": 3.943931758555669e-05, "loss": 1.2973, "step": 190 }, { "epoch": 0.31, "learning_rate": 3.8921890412204705e-05, "loss": 1.3638, "step": 195 }, { "epoch": 0.32, "learning_rate": 3.8395669874474915e-05, "loss": 1.263, "step": 200 }, { "epoch": 0.33, "learning_rate": 3.786098834453766e-05, "loss": 1.1872, "step": 205 }, { "epoch": 0.34, "learning_rate": 3.731818353870729e-05, "loss": 1.1829, "step": 210 }, { "epoch": 0.34, "learning_rate": 3.6767598304133324e-05, "loss": 1.1306, "step": 215 }, { "epoch": 0.35, "learning_rate": 3.6209580402250815e-05, "loss": 1.2149, "step": 220 }, { "epoch": 0.36, "learning_rate": 3.564448228912682e-05, "loss": 1.2721, "step": 225 }, { "epoch": 0.37, "learning_rate": 3.507266089284157e-05, "loss": 1.2713, "step": 230 }, { "epoch": 0.38, "learning_rate": 3.4494477388045035e-05, "loss": 1.2435, "step": 235 }, { "epoch": 0.38, "learning_rate": 3.3910296967831266e-05, "loss": 1.2568, "step": 240 }, { "epoch": 0.39, "learning_rate": 3.332048861307467e-05, "loss": 1.2105, "step": 245 }, { "epoch": 0.4, "learning_rate": 3.272542485937369e-05, "loss": 1.1573, "step": 250 }, { "epoch": 0.41, "learning_rate": 3.21254815617494e-05, "loss": 1.3292, "step": 255 }, { "epoch": 0.42, "learning_rate": 3.152103765724743e-05, "loss": 1.2807, "step": 260 }, { "epoch": 0.42, "learning_rate": 3.091247492559312e-05, "loss": 1.2628, "step": 265 }, { "epoch": 0.43, "learning_rate": 3.0300177748051373e-05, "loss": 1.2506, "step": 270 }, { "epoch": 0.44, "learning_rate": 2.9684532864643122e-05, "loss": 1.1508, "step": 275 }, { "epoch": 0.45, "learning_rate": 2.9065929129872094e-05, "loss": 1.3014, "step": 280 }, { "epoch": 0.46, "learning_rate": 2.844475726711595e-05, "loss": 1.2336, "step": 285 }, { "epoch": 0.46, "learning_rate": 2.782140962183704e-05, "loss": 1.1856, "step": 290 }, { "epoch": 0.47, "learning_rate": 2.7196279913768584e-05, "loss": 1.2296, "step": 295 }, { "epoch": 0.48, "learning_rate": 2.656976298823284e-05, "loss": 1.2893, "step": 300 } ], "logging_steps": 5, "max_steps": 625, "num_input_tokens_seen": 0, "num_train_epochs": 1, "save_steps": 100, "total_flos": 1.3782369609449472e+16, "train_batch_size": 4, "trial_name": null, "trial_params": null}123version https://git-lfs.github.com/spec/v1oid sha256:b815e38a230d037df7896cb286b9f709dfeb8104461486a0980a49299c45b3e1size 4920123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204---library_name: peftbase_model: /root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat---
# 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. -->
- **Developed by:** [More Information Needed]- **Funded by [optional]:** [More Information Needed]- **Shared by [optional]:** [More Information Needed]- **Model type:** [More Information Needed]- **Language(s) (NLP):** [More Information Needed]- **License:** [More Information Needed]- **Finetuned from model [optional]:** [More Information Needed]
### 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. -->
[More Information Needed]
### 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.
[More Information Needed]
## 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. -->
[More Information Needed]
### 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
- **Training regime:** [More Information Needed] <!--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
[More Information Needed]
#### 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]
### Framework versions
- PEFT 0.8.21234567891011121314151617181920212223242526{ "alpha_pattern": {}, "auto_mapping": null, "base_model_name_or_path": "/root/.cache/modelscope/hub/qwen/Qwen-1_8B-Chat", "bias": "none", "fan_in_fan_out": false, "inference_mode": true, "init_lora_weights": true, "layers_pattern": null, "layers_to_transform": null, "loftq_config": {}, "lora_alpha": 16, "lora_dropout": 0.1, "megatron_config": null, "megatron_core": "megatron.core", "modules_to_save": null, "peft_type": "LORA", "r": 8, "rank_pattern": {}, "revision": null, "target_modules": [ "c_attn" ], "task_type": "CAUSAL_LM", "use_rslora": false}123version https://git-lfs.github.com/spec/v1oid sha256:ad09bcb90a1253bd0307cc7a4dcd72568ba0b4766d3e8ddee8f51c72f4890e62size 6297600123version https://git-lfs.github.com/spec/v1oid sha256:b9b22a882ecf749f6f4345ef65f978790404b460079abc9bf20ad417851b08adsize 12623610123version https://git-lfs.github.com/spec/v1oid sha256:2db3af0189cc874f7e551dbb10c07b4bab70baba27706969f3e89fbeb8ca2f0bsize 14244123version https://git-lfs.github.com/spec/v1oid sha256:991afdce3921db3bf4a0aca4d23f064b1eaf5bf187ff8675af1e970571a0a8bdsize 10641234{ "eos_token": "<|im_end|>", "pad_token": "<|endoftext|>"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276# 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 base64import loggingimport osimport unicodedatafrom typing import Collection, Dict, List, Set, Tuple, Union
import tiktokenfrom 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 impactEXTRAS = tuple((f"<|extra_{i}|>" for i in range(205)))# changed to use actual index to avoid misconfiguration with vocabulary expansionSPECIAL_START_ID = 151643SPECIAL_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)12345678910111213141516{ "added_tokens_decoder": {}, "auto_map": { "AutoTokenizer": [ "tokenization_qwen.QWenTokenizer", null ] }, "clean_up_tokenization_spaces": true, "eos_token": "<|im_end|>", "model_max_length": 8192, "pad_token": "<|endoftext|>", "padding_side": "right", "split_special_tokens": false, "tokenizer_class": "QWenTokenizer"}Lordos4x/test/README.mdAdded+59
Lordos4x/test/adapter_config.jsonAdded+26
Lordos4x/test/adapter_model.safetensorsAdded+3
Lordos4x/test/all_results.jsonAdded+7
Lordos4x/test/checkpoint-100/README.mdAdded+204
Lordos4x/test/checkpoint-100/adapter_config.jsonAdded+26
Lordos4x/test/checkpoint-100/adapter_model.safetensorsAdded+3
Lordos4x/test/checkpoint-100/optimizer.ptAdded+3
Lordos4x/test/checkpoint-100/qwen.tiktokenAdded
Lordos4x/test/checkpoint-100/rng_state.pthAdded+3
Lordos4x/test/checkpoint-100/scheduler.ptAdded+3
Lordos4x/test/checkpoint-100/special_tokens_map.jsonAdded+4
Lordos4x/test/checkpoint-100/tokenization_qwen.pyAdded+276
Lordos4x/test/checkpoint-100/tokenizer_config.jsonAdded+16
Lordos4x/test/checkpoint-100/trainer_state.jsonAdded+141
Lordos4x/test/checkpoint-100/training_args.binAdded+3
Lordos4x/test/checkpoint-200/README.mdAdded+204
Lordos4x/test/checkpoint-200/adapter_config.jsonAdded+26
Lordos4x/test/checkpoint-200/adapter_model.safetensorsAdded+3
Lordos4x/test/checkpoint-200/optimizer.ptAdded+3
Lordos4x/test/checkpoint-200/qwen.tiktokenAdded
Lordos4x/test/checkpoint-200/rng_state.pthAdded+3
Lordos4x/test/checkpoint-200/scheduler.ptAdded+3
Lordos4x/test/checkpoint-200/special_tokens_map.jsonAdded+4
Lordos4x/test/checkpoint-200/tokenization_qwen.pyAdded+276
Lordos4x/test/checkpoint-200/tokenizer_config.jsonAdded+16
Lordos4x/test/checkpoint-200/trainer_state.jsonAdded+261
Lordos4x/test/checkpoint-200/training_args.binAdded+3
Lordos4x/test/checkpoint-300/README.mdAdded+204
Lordos4x/test/checkpoint-300/adapter_config.jsonAdded+26
Lordos4x/test/checkpoint-300/adapter_model.safetensorsAdded+3
Lordos4x/test/checkpoint-300/optimizer.ptAdded+3
Lordos4x/test/checkpoint-300/qwen.tiktokenAdded
Lordos4x/test/checkpoint-300/rng_state.pthAdded+3
Lordos4x/test/checkpoint-300/scheduler.ptAdded+3
Lordos4x/test/checkpoint-300/special_tokens_map.jsonAdded+4
Lordos4x/test/checkpoint-300/tokenization_qwen.pyAdded+276
Lordos4x/test/checkpoint-300/tokenizer_config.jsonAdded+16
Lordos4x/test/checkpoint-300/trainer_state.jsonAdded+381
Lordos4x/test/checkpoint-300/training_args.binAdded+3
Lordos4x/test/checkpoint-400/README.mdAdded+204
Lordos4x/test/checkpoint-400/adapter_config.jsonAdded+26
Lordos4x/test/checkpoint-400/adapter_model.safetensorsAdded+3
Lordos4x/test/checkpoint-400/optimizer.ptAdded+3
Lordos4x/test/checkpoint-400/qwen.tiktokenAdded
Lordos4x/test/checkpoint-400/rng_state.pthAdded+3
Lordos4x/test/checkpoint-400/scheduler.ptAdded+3
Lordos4x/test/checkpoint-400/special_tokens_map.jsonAdded+4
Lordos4x/test/checkpoint-400/tokenization_qwen.pyAdded+276
Lordos4x/test/checkpoint-400/tokenizer_config.jsonAdded+16