Spaces:
Runtime error
Runtime error
xiaowang7777
commited on
Commit
•
33ea1fe
1
Parent(s):
5dbb4ff
fush
Browse files- app.py +16 -1
- models/configuration_moss.py +123 -0
- models/custom_autotune.py +167 -0
- models/modeling_moss.py +738 -0
- models/quantization.py +397 -0
- models/tokenization_moss.py +380 -0
app.py
CHANGED
@@ -1,13 +1,28 @@
|
|
1 |
import gradio as gr
|
2 |
from transformers import pipeline
|
3 |
import torch
|
|
|
|
|
|
|
|
|
4 |
|
5 |
nstruct_pipeline_3b = pipeline(model="fnlp/moss-moon-003-sft-int4", torch_dtype=torch.float, trust_remote_code=True,
|
6 |
device_map="auto")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
|
8 |
|
9 |
def generate(query, temperature, top_p, top_k, max_new_tokens):
|
10 |
-
return
|
11 |
|
12 |
|
13 |
with gr.Blocks() as demo:
|
|
|
1 |
import gradio as gr
|
2 |
from transformers import pipeline
|
3 |
import torch
|
4 |
+
from models.modeling_moss import MossForCausalLM
|
5 |
+
from models.tokenization_moss import MossTokenizer
|
6 |
+
from models.configuration_moss import MossConfig
|
7 |
+
from accelerate import init_empty_weights, load_checkpoint_and_dispatch
|
8 |
|
9 |
nstruct_pipeline_3b = pipeline(model="fnlp/moss-moon-003-sft-int4", torch_dtype=torch.float, trust_remote_code=True,
|
10 |
device_map="auto")
|
11 |
+
model_path = "fnlp/moss-moon-003-sft-int4"
|
12 |
+
|
13 |
+
config = MossConfig.from_pretrained(model_path)
|
14 |
+
tokenizer = MossTokenizer.from_pretrained(model_path)
|
15 |
+
|
16 |
+
with init_empty_weights():
|
17 |
+
raw_model = MossForCausalLM._from_config(config, torch_dtype=torch.float)
|
18 |
+
raw_model.tie_weights()
|
19 |
+
model = load_checkpoint_and_dispatch(
|
20 |
+
raw_model, model_path, device_map="auto", no_split_module_classes=["MossBlock"], dtype=torch.float
|
21 |
+
)
|
22 |
|
23 |
|
24 |
def generate(query, temperature, top_p, top_k, max_new_tokens):
|
25 |
+
return model.generate(query, temperature, top_p, top_k, max_new_tokens)
|
26 |
|
27 |
|
28 |
with gr.Blocks() as demo:
|
models/configuration_moss.py
ADDED
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" Moss model configuration"""
|
2 |
+
|
3 |
+
from transformers.utils import logging
|
4 |
+
from transformers.configuration_utils import PretrainedConfig
|
5 |
+
|
6 |
+
|
7 |
+
logger = logging.get_logger(__name__)
|
8 |
+
|
9 |
+
|
10 |
+
class MossConfig(PretrainedConfig):
|
11 |
+
r"""
|
12 |
+
This is the configuration class to store the configuration of a [`MossModel`]. It is used to instantiate a
|
13 |
+
Moss model according to the specified arguments, defining the model architecture. Instantiating a configuration
|
14 |
+
with the defaults will yield a similar configuration to that of the Moss
|
15 |
+
[fnlp/moss-moon-003-base](https://huggingface.co/fnlp/moss-moon-003-base) architecture. Configuration objects
|
16 |
+
inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from
|
17 |
+
[`PretrainedConfig`] for more information.
|
18 |
+
|
19 |
+
Args:
|
20 |
+
vocab_size (`int`, *optional*, defaults to 107008):
|
21 |
+
Vocabulary size of the Moss model. Defines the number of different tokens that can be represented by the
|
22 |
+
`inputs_ids` passed when calling [`MossModel`].
|
23 |
+
n_positions (`int`, *optional*, defaults to 2048):
|
24 |
+
The maximum sequence length that this model might ever be used with. Typically set this to something large
|
25 |
+
just in case (e.g., 512 or 1024 or 2048).
|
26 |
+
n_embd (`int`, *optional*, defaults to 4096):
|
27 |
+
Dimensionality of the embeddings and hidden states.
|
28 |
+
n_layer (`int`, *optional*, defaults to 28):
|
29 |
+
Number of hidden layers in the Transformer encoder.
|
30 |
+
n_head (`int`, *optional*, defaults to 16):
|
31 |
+
Number of attention heads for each attention layer in the Transformer encoder.
|
32 |
+
rotary_dim (`int`, *optional*, defaults to 64):
|
33 |
+
Number of dimensions in the embedding that Rotary Position Embedding is applied to.
|
34 |
+
n_inner (`int`, *optional*, defaults to None):
|
35 |
+
Dimensionality of the inner feed-forward layers. `None` will set it to 4 times n_embd
|
36 |
+
activation_function (`str`, *optional*, defaults to `"gelu_new"`):
|
37 |
+
Activation function, to be selected in the list `["relu", "silu", "gelu", "tanh", "gelu_new"]`.
|
38 |
+
resid_pdrop (`float`, *optional*, defaults to 0.1):
|
39 |
+
The dropout probability for all fully connected layers in the embeddings, encoder, and pooler.
|
40 |
+
embd_pdrop (`int`, *optional*, defaults to 0.1):
|
41 |
+
The dropout ratio for the embeddings.
|
42 |
+
attn_pdrop (`float`, *optional*, defaults to 0.1):
|
43 |
+
The dropout ratio for the attention.
|
44 |
+
layer_norm_epsilon (`float`, *optional*, defaults to 1e-5):
|
45 |
+
The epsilon to use in the layer normalization layers.
|
46 |
+
initializer_range (`float`, *optional*, defaults to 0.02):
|
47 |
+
The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
|
48 |
+
use_cache (`bool`, *optional*, defaults to `True`):
|
49 |
+
Whether or not the model should return the last key/values attentions (not used by all models).
|
50 |
+
|
51 |
+
Example:
|
52 |
+
|
53 |
+
```python
|
54 |
+
>>> from modeling_moss import MossModel
|
55 |
+
>>> from configuration_moss import MossConfig
|
56 |
+
|
57 |
+
>>> # Initializing a moss-moon-003-base configuration
|
58 |
+
>>> configuration = MossConfig()
|
59 |
+
|
60 |
+
>>> # Initializing a model (with random weights) from the configuration
|
61 |
+
>>> model = MossModel(configuration)
|
62 |
+
|
63 |
+
>>> # Accessing the model configuration
|
64 |
+
>>> configuration = model.config
|
65 |
+
```"""
|
66 |
+
|
67 |
+
model_type = "moss"
|
68 |
+
attribute_map = {
|
69 |
+
"max_position_embeddings": "n_positions",
|
70 |
+
"hidden_size": "n_embd",
|
71 |
+
"num_attention_heads": "n_head",
|
72 |
+
"num_hidden_layers": "n_layer",
|
73 |
+
}
|
74 |
+
|
75 |
+
def __init__(
|
76 |
+
self,
|
77 |
+
vocab_size=107008,
|
78 |
+
n_positions=2048,
|
79 |
+
n_ctx=2048,
|
80 |
+
n_embd=4096,
|
81 |
+
n_layer=28,
|
82 |
+
n_head=16,
|
83 |
+
rotary_dim=64,
|
84 |
+
n_inner=None,
|
85 |
+
activation_function="gelu_new",
|
86 |
+
resid_pdrop=0.0,
|
87 |
+
embd_pdrop=0.0,
|
88 |
+
attn_pdrop=0.0,
|
89 |
+
layer_norm_epsilon=1e-5,
|
90 |
+
initializer_range=0.02,
|
91 |
+
use_cache=True,
|
92 |
+
bos_token_id=106028,
|
93 |
+
eos_token_id=106068,
|
94 |
+
tie_word_embeddings=False,
|
95 |
+
wbits=32,
|
96 |
+
groupsize=128,
|
97 |
+
**kwargs,
|
98 |
+
):
|
99 |
+
self.vocab_size = vocab_size
|
100 |
+
self.n_ctx = n_ctx
|
101 |
+
self.n_positions = n_positions
|
102 |
+
self.n_embd = n_embd
|
103 |
+
self.n_layer = n_layer
|
104 |
+
self.n_head = n_head
|
105 |
+
self.n_inner = n_inner
|
106 |
+
self.rotary_dim = rotary_dim
|
107 |
+
self.activation_function = activation_function
|
108 |
+
self.resid_pdrop = resid_pdrop
|
109 |
+
self.embd_pdrop = embd_pdrop
|
110 |
+
self.attn_pdrop = attn_pdrop
|
111 |
+
self.layer_norm_epsilon = layer_norm_epsilon
|
112 |
+
self.initializer_range = initializer_range
|
113 |
+
self.use_cache = use_cache
|
114 |
+
self.wbits = wbits
|
115 |
+
self.groupsize = groupsize
|
116 |
+
|
117 |
+
self.bos_token_id = bos_token_id
|
118 |
+
self.eos_token_id = eos_token_id
|
119 |
+
|
120 |
+
super().__init__(
|
121 |
+
bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs
|
122 |
+
)
|
123 |
+
|
models/custom_autotune.py
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#https://github.com/fpgaminer/GPTQ-triton
|
2 |
+
"""
|
3 |
+
Mostly the same as the autotuner in Triton, but with a few changes like using 40 runs instead of 100.
|
4 |
+
"""
|
5 |
+
|
6 |
+
import builtins
|
7 |
+
import math
|
8 |
+
import time
|
9 |
+
from typing import Dict
|
10 |
+
|
11 |
+
import triton
|
12 |
+
|
13 |
+
|
14 |
+
class Autotuner(triton.KernelInterface):
|
15 |
+
def __init__(self, fn, arg_names, configs, key, reset_to_zero, prune_configs_by: Dict = None, nearest_power_of_two: bool = False):
|
16 |
+
'''
|
17 |
+
:param prune_configs_by: a dict of functions that are used to prune configs, fields:
|
18 |
+
'perf_model': performance model used to predicate running time with different configs, returns running time
|
19 |
+
'top_k': number of configs to bench
|
20 |
+
'prune_num_stages_by'(optional): a function used to prune num_stages. It take configs:List[Config] as its input, and returns pruned configs.
|
21 |
+
'nearest_power_of_two'(optional): whether to round key arguments to the nearest power of two when caching tuning results
|
22 |
+
'''
|
23 |
+
if not configs:
|
24 |
+
self.configs = [triton.Config({}, num_warps=4, num_stages=2)]
|
25 |
+
else:
|
26 |
+
self.configs = configs
|
27 |
+
self.key_idx = [arg_names.index(k) for k in key]
|
28 |
+
self.nearest_power_of_two = nearest_power_of_two
|
29 |
+
self.cache = {}
|
30 |
+
# hook to reset all required tensor to zeros before relaunching a kernel
|
31 |
+
self.hook = lambda args: 0
|
32 |
+
if reset_to_zero is not None:
|
33 |
+
self.reset_idx = [arg_names.index(k) for k in reset_to_zero]
|
34 |
+
|
35 |
+
def _hook(args):
|
36 |
+
for i in self.reset_idx:
|
37 |
+
args[i].zero_()
|
38 |
+
self.hook = _hook
|
39 |
+
self.arg_names = arg_names
|
40 |
+
# prune configs
|
41 |
+
if prune_configs_by:
|
42 |
+
perf_model, top_k = prune_configs_by['perf_model'], prune_configs_by['top_k']
|
43 |
+
if 'early_config_prune' in prune_configs_by:
|
44 |
+
early_config_prune = prune_configs_by['early_config_prune']
|
45 |
+
else:
|
46 |
+
perf_model, top_k, early_config_prune = None, None, None
|
47 |
+
self.perf_model, self.configs_top_k = perf_model, top_k
|
48 |
+
self.early_config_prune = early_config_prune
|
49 |
+
self.fn = fn
|
50 |
+
|
51 |
+
def _bench(self, *args, config, **meta):
|
52 |
+
# check for conflicts, i.e. meta-parameters both provided
|
53 |
+
# as kwargs and by the autotuner
|
54 |
+
conflicts = meta.keys() & config.kwargs.keys()
|
55 |
+
if conflicts:
|
56 |
+
raise ValueError(
|
57 |
+
f"Conflicting meta-parameters: {', '.join(conflicts)}."
|
58 |
+
" Make sure that you don't re-define auto-tuned symbols."
|
59 |
+
)
|
60 |
+
# augment meta-parameters with tunable ones
|
61 |
+
current = dict(meta, **config.kwargs)
|
62 |
+
|
63 |
+
def kernel_call():
|
64 |
+
if config.pre_hook:
|
65 |
+
config.pre_hook(self.nargs)
|
66 |
+
self.hook(args)
|
67 |
+
self.fn.run(*args, num_warps=config.num_warps, num_stages=config.num_stages, **current)
|
68 |
+
try:
|
69 |
+
# In testings using only 40 reps seems to be close enough and it appears to be what PyTorch uses
|
70 |
+
# PyTorch also sets fast_flush to True, but I didn't see any speedup so I'll leave the default
|
71 |
+
return triton.testing.do_bench(kernel_call, rep=40)
|
72 |
+
except triton.compiler.OutOfResources:
|
73 |
+
return float('inf')
|
74 |
+
|
75 |
+
def run(self, *args, **kwargs):
|
76 |
+
self.nargs = dict(zip(self.arg_names, args))
|
77 |
+
if len(self.configs) > 1:
|
78 |
+
key = tuple(args[i] for i in self.key_idx)
|
79 |
+
|
80 |
+
# This reduces the amount of autotuning by rounding the keys to the nearest power of two
|
81 |
+
# In my testing this gives decent results, and greatly reduces the amount of tuning required
|
82 |
+
if self.nearest_power_of_two:
|
83 |
+
key = tuple([2 ** int(math.log2(x) + 0.5) for x in key])
|
84 |
+
|
85 |
+
if key not in self.cache:
|
86 |
+
# prune configs
|
87 |
+
pruned_configs = self.prune_configs(kwargs)
|
88 |
+
bench_start = time.time()
|
89 |
+
timings = {config: self._bench(*args, config=config, **kwargs)
|
90 |
+
for config in pruned_configs}
|
91 |
+
bench_end = time.time()
|
92 |
+
self.bench_time = bench_end - bench_start
|
93 |
+
self.cache[key] = builtins.min(timings, key=timings.get)
|
94 |
+
self.hook(args)
|
95 |
+
self.configs_timings = timings
|
96 |
+
config = self.cache[key]
|
97 |
+
else:
|
98 |
+
config = self.configs[0]
|
99 |
+
self.best_config = config
|
100 |
+
if config.pre_hook is not None:
|
101 |
+
config.pre_hook(self.nargs)
|
102 |
+
return self.fn.run(*args, num_warps=config.num_warps, num_stages=config.num_stages, **kwargs, **config.kwargs)
|
103 |
+
|
104 |
+
def prune_configs(self, kwargs):
|
105 |
+
pruned_configs = self.configs
|
106 |
+
if self.early_config_prune:
|
107 |
+
pruned_configs = self.early_config_prune(self.configs, self.nargs)
|
108 |
+
if self.perf_model:
|
109 |
+
top_k = self.configs_top_k
|
110 |
+
if isinstance(top_k, float) and top_k <= 1.0:
|
111 |
+
top_k = int(len(self.configs) * top_k)
|
112 |
+
if len(pruned_configs) > top_k:
|
113 |
+
est_timing = {
|
114 |
+
config: self.perf_model(**self.nargs, **kwargs, **config.kwargs, num_stages=config.num_stages,
|
115 |
+
num_warps=config.num_warps)
|
116 |
+
for config in pruned_configs
|
117 |
+
}
|
118 |
+
pruned_configs = sorted(est_timing.keys(), key=lambda x: est_timing[x])[:top_k]
|
119 |
+
return pruned_configs
|
120 |
+
|
121 |
+
def warmup(self, *args, **kwargs):
|
122 |
+
self.nargs = dict(zip(self.arg_names, args))
|
123 |
+
for config in self.prune_configs(kwargs):
|
124 |
+
self.fn.warmup(
|
125 |
+
*args,
|
126 |
+
num_warps=config.num_warps,
|
127 |
+
num_stages=config.num_stages,
|
128 |
+
**kwargs,
|
129 |
+
**config.kwargs,
|
130 |
+
)
|
131 |
+
self.nargs = None
|
132 |
+
|
133 |
+
|
134 |
+
def autotune(configs, key, prune_configs_by=None, reset_to_zero=None, nearest_power_of_two=False):
|
135 |
+
"""
|
136 |
+
Decorator for auto-tuning a :code:`triton.jit`'d function.
|
137 |
+
.. highlight:: python
|
138 |
+
.. code-block:: python
|
139 |
+
@triton.autotune(configs=[
|
140 |
+
triton.Config(meta={'BLOCK_SIZE': 128}, num_warps=4),
|
141 |
+
triton.Config(meta={'BLOCK_SIZE': 1024}, num_warps=8),
|
142 |
+
],
|
143 |
+
key=['x_size'] # the two above configs will be evaluated anytime
|
144 |
+
# the value of x_size changes
|
145 |
+
)
|
146 |
+
@triton.jit
|
147 |
+
def kernel(x_ptr, x_size, **META):
|
148 |
+
BLOCK_SIZE = META['BLOCK_SIZE']
|
149 |
+
:note: When all the configurations are evaluated, the kernel will run multiple time.
|
150 |
+
This means that whatever value the kernel updates will be updated multiple times.
|
151 |
+
To avoid this undesired behavior, you can use the `reset_to_zero` argument, which
|
152 |
+
reset the value of the provided tensor to `zero` before running any configuration.
|
153 |
+
:param configs: a list of :code:`triton.Config` objects
|
154 |
+
:type configs: list[triton.Config]
|
155 |
+
:param key: a list of argument names whose change in value will trigger the evaluation of all provided configs.
|
156 |
+
:type key: list[str]
|
157 |
+
:param prune_configs_by: a dict of functions that are used to prune configs, fields:
|
158 |
+
'perf_model': performance model used to predicate running time with different configs, returns running time
|
159 |
+
'top_k': number of configs to bench
|
160 |
+
'early_config_prune'(optional): a function used to do early prune (eg, num_stages). It take configs:List[Config] as its input, and returns pruned configs.
|
161 |
+
:param reset_to_zero: a list of argument names whose value will be reset to zero before evaluating any configs.
|
162 |
+
:type reset_to_zero: list[str]
|
163 |
+
"""
|
164 |
+
def decorator(fn):
|
165 |
+
return Autotuner(fn, fn.arg_names, configs, key, reset_to_zero, prune_configs_by, nearest_power_of_two)
|
166 |
+
|
167 |
+
return decorator
|
models/modeling_moss.py
ADDED
@@ -0,0 +1,738 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
""" PyTorch Moss model."""
|
2 |
+
|
3 |
+
from typing import Optional, Tuple, Union
|
4 |
+
|
5 |
+
import torch
|
6 |
+
import torch.utils.checkpoint
|
7 |
+
from torch import nn
|
8 |
+
from torch.nn import CrossEntropyLoss
|
9 |
+
import transformers
|
10 |
+
from transformers.activations import ACT2FN
|
11 |
+
from transformers.modeling_utils import PreTrainedModel
|
12 |
+
from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
|
13 |
+
from transformers.utils import (
|
14 |
+
add_code_sample_docstrings,
|
15 |
+
add_start_docstrings,
|
16 |
+
add_start_docstrings_to_model_forward,
|
17 |
+
logging
|
18 |
+
)
|
19 |
+
|
20 |
+
from .configuration_moss import MossConfig
|
21 |
+
|
22 |
+
logger = logging.get_logger(__name__)
|
23 |
+
|
24 |
+
_CHECKPOINT_FOR_DOC = "fnlp/moss-moon-003-base"
|
25 |
+
_CONFIG_FOR_DOC = "MossConfig"
|
26 |
+
|
27 |
+
|
28 |
+
MOSS_PRETRAINED_MODEL_ARCHIVE_LIST = [
|
29 |
+
"fnlp/moss-moon-003-base",
|
30 |
+
"fnlp/moss-moon-003-sft",
|
31 |
+
"fnlp/moss-moon-003-sft-plugin",
|
32 |
+
"fnlp/moss-moon-003-sft-int4",
|
33 |
+
"fnlp/moss-moon-003-sft-plugin-int4",
|
34 |
+
"fnlp/moss-moon-003-sft-int8",
|
35 |
+
"fnlp/moss-moon-003-sft-plugin-int8",
|
36 |
+
]
|
37 |
+
|
38 |
+
|
39 |
+
# Copied from transformers.models.gptj.modeling_gptj.create_sinusoidal_positions
|
40 |
+
def create_sinusoidal_positions(num_pos: int, dim: int) -> torch.Tensor:
|
41 |
+
inv_freq = 1.0 / (10000 ** (torch.arange(0, dim, 2) / dim))
|
42 |
+
sinusoid_inp = torch.einsum("i , j -> i j", torch.arange(num_pos, dtype=torch.float), inv_freq).float()
|
43 |
+
return torch.cat((torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)), dim=1)
|
44 |
+
|
45 |
+
|
46 |
+
# Copied from transformers.models.gptj.modeling_gptj.rotate_every_two
|
47 |
+
def rotate_every_two(x: torch.Tensor) -> torch.Tensor:
|
48 |
+
x1 = x[:, :, :, ::2]
|
49 |
+
x2 = x[:, :, :, 1::2]
|
50 |
+
x = torch.stack((-x2, x1), dim=-1)
|
51 |
+
return x.flatten(-2) # in einsum notation: rearrange(x, '... d j -> ... (d j)')
|
52 |
+
|
53 |
+
|
54 |
+
# Copied from transformers.models.gptj.modeling_gptj.apply_rotary_pos_emb
|
55 |
+
def apply_rotary_pos_emb(tensor: torch.Tensor, sin: torch.Tensor, cos: torch.Tensor) -> torch.Tensor:
|
56 |
+
sin = torch.repeat_interleave(sin[:, :, None, :], 2, 3)
|
57 |
+
cos = torch.repeat_interleave(cos[:, :, None, :], 2, 3)
|
58 |
+
return (tensor * cos) + (rotate_every_two(tensor) * sin)
|
59 |
+
|
60 |
+
|
61 |
+
class MossAttention(nn.Module):
|
62 |
+
def __init__(self, config):
|
63 |
+
super().__init__()
|
64 |
+
|
65 |
+
max_positions = config.max_position_embeddings
|
66 |
+
self.register_buffer(
|
67 |
+
"causal_mask",
|
68 |
+
torch.tril(torch.ones((max_positions, max_positions), dtype=torch.bool)).view(
|
69 |
+
1, 1, max_positions, max_positions
|
70 |
+
),
|
71 |
+
)
|
72 |
+
|
73 |
+
self.attn_dropout = nn.Dropout(config.attn_pdrop)
|
74 |
+
self.resid_dropout = nn.Dropout(config.resid_pdrop)
|
75 |
+
|
76 |
+
self.embed_dim = config.hidden_size
|
77 |
+
self.num_attention_heads = config.num_attention_heads
|
78 |
+
self.head_dim = self.embed_dim // self.num_attention_heads
|
79 |
+
if self.head_dim * self.num_attention_heads != self.embed_dim:
|
80 |
+
raise ValueError(
|
81 |
+
f"embed_dim must be divisible by num_attention_heads (got `embed_dim`: {self.embed_dim} and"
|
82 |
+
f" `num_attention_heads`: {self.num_attention_heads})."
|
83 |
+
)
|
84 |
+
self.scale_attn = torch.sqrt(torch.tensor(self.head_dim, dtype=torch.float32)).to(torch.get_default_dtype())
|
85 |
+
self.qkv_proj = nn.Linear(self.embed_dim, self.embed_dim * 3, bias=False)
|
86 |
+
|
87 |
+
self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
|
88 |
+
self.rotary_dim = config.rotary_dim
|
89 |
+
pos_embd_dim = self.rotary_dim or self.embed_dim
|
90 |
+
self.embed_positions = create_sinusoidal_positions(max_positions, pos_embd_dim)
|
91 |
+
|
92 |
+
def _split_heads(self, x, n_head, dim_head, mp_num):
|
93 |
+
reshaped = x.reshape(x.shape[:-1] + (n_head // mp_num, dim_head))
|
94 |
+
reshaped = reshaped.reshape(x.shape[:-2] + (-1,) + reshaped.shape[-1:])
|
95 |
+
return reshaped
|
96 |
+
|
97 |
+
def _merge_heads(self, tensor, num_attention_heads, attn_head_size):
|
98 |
+
"""
|
99 |
+
Merges attn_head_size dim and num_attn_heads dim into n_ctx
|
100 |
+
"""
|
101 |
+
if len(tensor.shape) == 5:
|
102 |
+
tensor = tensor.permute(0, 1, 3, 2, 4).contiguous()
|
103 |
+
elif len(tensor.shape) == 4:
|
104 |
+
tensor = tensor.permute(0, 2, 1, 3).contiguous()
|
105 |
+
else:
|
106 |
+
raise ValueError(f"Input tensor rank should be one of [4, 5], but is: {len(tensor.shape)}")
|
107 |
+
new_shape = tensor.size()[:-2] + (num_attention_heads * attn_head_size,)
|
108 |
+
return tensor.view(new_shape)
|
109 |
+
|
110 |
+
def _attn(
|
111 |
+
self,
|
112 |
+
query,
|
113 |
+
key,
|
114 |
+
value,
|
115 |
+
attention_mask=None,
|
116 |
+
head_mask=None,
|
117 |
+
):
|
118 |
+
# compute causal mask from causal mask buffer
|
119 |
+
query_length, key_length = query.size(-2), key.size(-2)
|
120 |
+
causal_mask = self.causal_mask[:, :, key_length - query_length : key_length, :key_length]
|
121 |
+
|
122 |
+
# Keep the attention weights computation in fp32 to avoid overflow issues
|
123 |
+
query = query.to(torch.float32)
|
124 |
+
key = key.to(torch.float32)
|
125 |
+
|
126 |
+
attn_weights = torch.matmul(query, key.transpose(-1, -2))
|
127 |
+
|
128 |
+
attn_weights = attn_weights / self.scale_attn
|
129 |
+
mask_value = torch.finfo(attn_weights.dtype).min
|
130 |
+
# Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
|
131 |
+
# Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
|
132 |
+
mask_value = torch.tensor(mask_value, dtype=attn_weights.dtype).to(attn_weights.device)
|
133 |
+
attn_weights = torch.where(causal_mask, attn_weights, mask_value)
|
134 |
+
|
135 |
+
if attention_mask is not None:
|
136 |
+
# Apply the attention mask
|
137 |
+
attn_weights = attn_weights + attention_mask
|
138 |
+
|
139 |
+
attn_weights = nn.Softmax(dim=-1)(attn_weights)
|
140 |
+
attn_weights = attn_weights.to(value.dtype)
|
141 |
+
attn_weights = self.attn_dropout(attn_weights)
|
142 |
+
|
143 |
+
# Mask heads if we want to
|
144 |
+
if head_mask is not None:
|
145 |
+
attn_weights = attn_weights * head_mask
|
146 |
+
|
147 |
+
attn_output = torch.matmul(attn_weights, value)
|
148 |
+
|
149 |
+
return attn_output, attn_weights
|
150 |
+
|
151 |
+
def forward(
|
152 |
+
self,
|
153 |
+
hidden_states: Optional[torch.FloatTensor],
|
154 |
+
layer_past: Optional[Tuple[torch.Tensor]] = None,
|
155 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
156 |
+
position_ids: Optional[torch.LongTensor] = None,
|
157 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
158 |
+
use_cache: Optional[bool] = False,
|
159 |
+
output_attentions: Optional[bool] = False,
|
160 |
+
) -> Union[
|
161 |
+
Tuple[torch.Tensor, Tuple[torch.Tensor]],
|
162 |
+
Optional[Tuple[torch.Tensor, Tuple[torch.Tensor], Tuple[torch.Tensor, ...]]],
|
163 |
+
]:
|
164 |
+
qkv = self.qkv_proj(hidden_states)
|
165 |
+
# TODO(enijkamp): factor out number of logical TPU-v4 cores or make forward pass agnostic
|
166 |
+
mp_num = 4
|
167 |
+
qkv_split = qkv.reshape(qkv.shape[:-1] + (mp_num, -1))
|
168 |
+
|
169 |
+
local_dim = self.head_dim * self.num_attention_heads // mp_num
|
170 |
+
query, value, key = torch.split(qkv_split, local_dim, dim=-1)
|
171 |
+
query = self._split_heads(query, self.num_attention_heads, self.head_dim, mp_num=mp_num)
|
172 |
+
key = self._split_heads(key, self.num_attention_heads, self.head_dim, mp_num=mp_num)
|
173 |
+
|
174 |
+
value = self._split_heads(value, self.num_attention_heads, self.head_dim, mp_num=mp_num)
|
175 |
+
value = value.permute(0, 2, 1, 3)
|
176 |
+
|
177 |
+
embed_positions = self.embed_positions
|
178 |
+
if embed_positions.device != position_ids.device:
|
179 |
+
embed_positions = embed_positions.to(position_ids.device)
|
180 |
+
self.embed_positions = embed_positions
|
181 |
+
|
182 |
+
sincos = embed_positions[position_ids]
|
183 |
+
sin, cos = torch.split(sincos, sincos.shape[-1] // 2, dim=-1)
|
184 |
+
|
185 |
+
if self.rotary_dim is not None:
|
186 |
+
k_rot = key[:, :, :, : self.rotary_dim]
|
187 |
+
k_pass = key[:, :, :, self.rotary_dim :]
|
188 |
+
|
189 |
+
q_rot = query[:, :, :, : self.rotary_dim]
|
190 |
+
q_pass = query[:, :, :, self.rotary_dim :]
|
191 |
+
|
192 |
+
k_rot = apply_rotary_pos_emb(k_rot, sin, cos)
|
193 |
+
q_rot = apply_rotary_pos_emb(q_rot, sin, cos)
|
194 |
+
|
195 |
+
key = torch.cat([k_rot, k_pass], dim=-1)
|
196 |
+
query = torch.cat([q_rot, q_pass], dim=-1)
|
197 |
+
else:
|
198 |
+
key = apply_rotary_pos_emb(key, sin, cos)
|
199 |
+
query = apply_rotary_pos_emb(query, sin, cos)
|
200 |
+
|
201 |
+
key = key.permute(0, 2, 1, 3)
|
202 |
+
query = query.permute(0, 2, 1, 3)
|
203 |
+
|
204 |
+
if layer_past is not None:
|
205 |
+
past_key = layer_past[0]
|
206 |
+
past_value = layer_past[1]
|
207 |
+
key = torch.cat((past_key, key), dim=-2)
|
208 |
+
value = torch.cat((past_value, value), dim=-2)
|
209 |
+
|
210 |
+
if use_cache is True:
|
211 |
+
present = (key, value)
|
212 |
+
else:
|
213 |
+
present = None
|
214 |
+
|
215 |
+
# compute self-attention: V x Softmax(QK^T)
|
216 |
+
attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
|
217 |
+
|
218 |
+
attn_output = self._merge_heads(attn_output, self.num_attention_heads, self.head_dim)
|
219 |
+
attn_output = self.out_proj(attn_output)
|
220 |
+
attn_output = self.resid_dropout(attn_output)
|
221 |
+
|
222 |
+
outputs = (attn_output, present)
|
223 |
+
if output_attentions:
|
224 |
+
outputs += (attn_weights,)
|
225 |
+
|
226 |
+
return outputs # a, present, (attentions)
|
227 |
+
|
228 |
+
|
229 |
+
# Copied from transformers.models.gptj.modeling_gptj.GPTJMLP with GPTJ->Moss
|
230 |
+
class MossMLP(nn.Module):
|
231 |
+
def __init__(self, intermediate_size, config): # in MLP: intermediate_size= 4 * embed_dim
|
232 |
+
super().__init__()
|
233 |
+
embed_dim = config.n_embd
|
234 |
+
|
235 |
+
self.fc_in = nn.Linear(embed_dim, intermediate_size)
|
236 |
+
self.fc_out = nn.Linear(intermediate_size, embed_dim)
|
237 |
+
|
238 |
+
self.act = ACT2FN[config.activation_function]
|
239 |
+
self.dropout = nn.Dropout(config.resid_pdrop)
|
240 |
+
|
241 |
+
def forward(self, hidden_states: Optional[torch.FloatTensor]) -> torch.FloatTensor:
|
242 |
+
hidden_states = self.fc_in(hidden_states)
|
243 |
+
hidden_states = self.act(hidden_states)
|
244 |
+
hidden_states = self.fc_out(hidden_states)
|
245 |
+
hidden_states = self.dropout(hidden_states)
|
246 |
+
return hidden_states
|
247 |
+
|
248 |
+
|
249 |
+
# Copied from transformers.models.gptj.modeling_gptj.GPTJBlock with GPTJ->Moss
|
250 |
+
class MossBlock(nn.Module):
|
251 |
+
def __init__(self, config):
|
252 |
+
super().__init__()
|
253 |
+
inner_dim = config.n_inner if config.n_inner is not None else 4 * config.n_embd
|
254 |
+
self.ln_1 = nn.LayerNorm(config.n_embd, eps=config.layer_norm_epsilon)
|
255 |
+
self.attn = MossAttention(config)
|
256 |
+
self.mlp = MossMLP(inner_dim, config)
|
257 |
+
|
258 |
+
def forward(
|
259 |
+
self,
|
260 |
+
hidden_states: Optional[torch.FloatTensor],
|
261 |
+
layer_past: Optional[Tuple[torch.Tensor]] = None,
|
262 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
263 |
+
position_ids: Optional[torch.LongTensor] = None,
|
264 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
265 |
+
use_cache: Optional[bool] = False,
|
266 |
+
output_attentions: Optional[bool] = False,
|
267 |
+
) -> Union[Tuple[torch.Tensor], Optional[Tuple[torch.Tensor, Tuple[torch.FloatTensor, ...]]]]:
|
268 |
+
residual = hidden_states
|
269 |
+
hidden_states = self.ln_1(hidden_states)
|
270 |
+
attn_outputs = self.attn(
|
271 |
+
hidden_states=hidden_states,
|
272 |
+
layer_past=layer_past,
|
273 |
+
attention_mask=attention_mask,
|
274 |
+
position_ids=position_ids,
|
275 |
+
head_mask=head_mask,
|
276 |
+
use_cache=use_cache,
|
277 |
+
output_attentions=output_attentions,
|
278 |
+
)
|
279 |
+
attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
|
280 |
+
outputs = attn_outputs[1:]
|
281 |
+
|
282 |
+
feed_forward_hidden_states = self.mlp(hidden_states)
|
283 |
+
hidden_states = attn_output + feed_forward_hidden_states + residual
|
284 |
+
|
285 |
+
if use_cache:
|
286 |
+
outputs = (hidden_states,) + outputs
|
287 |
+
else:
|
288 |
+
outputs = (hidden_states,) + outputs[1:]
|
289 |
+
|
290 |
+
return outputs # hidden_states, present, (attentions)
|
291 |
+
|
292 |
+
|
293 |
+
class MossPreTrainedModel(PreTrainedModel):
|
294 |
+
"""
|
295 |
+
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
|
296 |
+
models.
|
297 |
+
"""
|
298 |
+
|
299 |
+
config_class = MossConfig
|
300 |
+
base_model_prefix = "transformer"
|
301 |
+
supports_gradient_checkpointing = True
|
302 |
+
_no_split_modules = ["MossBlock"]
|
303 |
+
|
304 |
+
def __init__(self, *inputs, **kwargs):
|
305 |
+
super().__init__(*inputs, **kwargs)
|
306 |
+
|
307 |
+
def _init_weights(self, module):
|
308 |
+
"""Initialize the weights."""
|
309 |
+
if isinstance(module, (nn.Linear,)):
|
310 |
+
# Slightly different from Mesh Transformer JAX which uses truncated_normal for initialization
|
311 |
+
# cf https://github.com/pytorch/pytorch/pull/5617
|
312 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
313 |
+
if module.bias is not None:
|
314 |
+
module.bias.data.zero_()
|
315 |
+
elif isinstance(module, nn.Embedding):
|
316 |
+
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
|
317 |
+
if module.padding_idx is not None:
|
318 |
+
module.weight.data[module.padding_idx].zero_()
|
319 |
+
elif isinstance(module, nn.LayerNorm):
|
320 |
+
module.bias.data.zero_()
|
321 |
+
module.weight.data.fill_(1.0)
|
322 |
+
|
323 |
+
def _set_gradient_checkpointing(self, module, value=False):
|
324 |
+
if isinstance(module, MossModel):
|
325 |
+
module.gradient_checkpointing = value
|
326 |
+
|
327 |
+
|
328 |
+
MOSS_START_DOCSTRING = r"""
|
329 |
+
This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
|
330 |
+
it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
|
331 |
+
behavior.
|
332 |
+
|
333 |
+
Parameters:
|
334 |
+
config ([`MossConfig`]): Model configuration class with all the parameters of the model.
|
335 |
+
Initializing with a config file does not load the weights associated with the model, only the
|
336 |
+
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
|
337 |
+
"""
|
338 |
+
|
339 |
+
MOSS_INPUTS_DOCSTRING = r"""
|
340 |
+
Args:
|
341 |
+
input_ids (`torch.LongTensor` of shape `({0})`):
|
342 |
+
Indices of input sequence tokens in the vocabulary.
|
343 |
+
|
344 |
+
Indices can be obtained using [`AutoProcenizer`]. See [`PreTrainedTokenizer.encode`] and
|
345 |
+
[`PreTrainedTokenizer.__call__`] for details.
|
346 |
+
|
347 |
+
[What are input IDs?](../glossary#input-ids)
|
348 |
+
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
|
349 |
+
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
|
350 |
+
|
351 |
+
- 1 for tokens that are **not masked**,
|
352 |
+
- 0 for tokens that are **masked**.
|
353 |
+
|
354 |
+
[What are attention masks?](../glossary#attention-mask)
|
355 |
+
token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
356 |
+
Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,
|
357 |
+
1]`:
|
358 |
+
|
359 |
+
- 0 corresponds to a *sentence A* token,
|
360 |
+
- 1 corresponds to a *sentence B* token.
|
361 |
+
|
362 |
+
[What are token type IDs?](../glossary#token-type-ids)
|
363 |
+
position_ids (`torch.LongTensor` of shape `({0})`, *optional*):
|
364 |
+
Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
|
365 |
+
config.n_positions - 1]`.
|
366 |
+
|
367 |
+
[What are position IDs?](../glossary#position-ids)
|
368 |
+
head_mask (`torch.FloatTensor` of shape `(num_attention_heads,)` or `(n_layer, num_attention_heads)`, *optional*):
|
369 |
+
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
|
370 |
+
|
371 |
+
- 1 indicates the head is **not masked**,
|
372 |
+
- 0 indicates the head is **masked**.
|
373 |
+
|
374 |
+
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_dim)`, *optional*):
|
375 |
+
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
|
376 |
+
is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
|
377 |
+
model's internal embedding lookup matrix.
|
378 |
+
output_attentions (`bool`, *optional*):
|
379 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
|
380 |
+
tensors for more detail.
|
381 |
+
output_hidden_states (`bool`, *optional*):
|
382 |
+
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
|
383 |
+
more detail.
|
384 |
+
return_dict (`bool`, *optional*):
|
385 |
+
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
|
386 |
+
"""
|
387 |
+
|
388 |
+
|
389 |
+
@add_start_docstrings(
|
390 |
+
"The bare Moss Model transformer outputting raw hidden-states without any specific head on top.",
|
391 |
+
MOSS_START_DOCSTRING,
|
392 |
+
)
|
393 |
+
class MossModel(MossPreTrainedModel):
|
394 |
+
def __init__(self, config):
|
395 |
+
super().__init__(config)
|
396 |
+
|
397 |
+
self.embed_dim = config.n_embd
|
398 |
+
self.vocab_size = config.vocab_size
|
399 |
+
self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
|
400 |
+
self.drop = nn.Dropout(config.embd_pdrop)
|
401 |
+
self.h = nn.ModuleList([MossBlock(config) for _ in range(config.n_layer)])
|
402 |
+
self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
|
403 |
+
self.rotary_dim = min(config.rotary_dim, config.n_ctx // config.num_attention_heads)
|
404 |
+
|
405 |
+
self.gradient_checkpointing = False
|
406 |
+
|
407 |
+
# Initialize weights and apply final processing
|
408 |
+
self.post_init()
|
409 |
+
|
410 |
+
def get_input_embeddings(self):
|
411 |
+
return self.wte
|
412 |
+
|
413 |
+
def set_input_embeddings(self, new_embeddings):
|
414 |
+
self.wte = new_embeddings
|
415 |
+
|
416 |
+
@add_start_docstrings_to_model_forward(MOSS_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
417 |
+
@add_code_sample_docstrings(
|
418 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
419 |
+
output_type=BaseModelOutputWithPast,
|
420 |
+
config_class=_CONFIG_FOR_DOC,
|
421 |
+
)
|
422 |
+
def forward(
|
423 |
+
self,
|
424 |
+
input_ids: Optional[torch.LongTensor] = None,
|
425 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
426 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
427 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
428 |
+
position_ids: Optional[torch.LongTensor] = None,
|
429 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
430 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
431 |
+
use_cache: Optional[bool] = None,
|
432 |
+
output_attentions: Optional[bool] = None,
|
433 |
+
output_hidden_states: Optional[bool] = None,
|
434 |
+
return_dict: Optional[bool] = None,
|
435 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
436 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
437 |
+
output_hidden_states = (
|
438 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
439 |
+
)
|
440 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
441 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
442 |
+
|
443 |
+
if input_ids is not None and inputs_embeds is not None:
|
444 |
+
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
|
445 |
+
elif input_ids is not None:
|
446 |
+
input_shape = input_ids.size()
|
447 |
+
input_ids = input_ids.view(-1, input_shape[-1])
|
448 |
+
batch_size = input_ids.shape[0]
|
449 |
+
elif inputs_embeds is not None:
|
450 |
+
input_shape = inputs_embeds.size()[:-1]
|
451 |
+
batch_size = inputs_embeds.shape[0]
|
452 |
+
else:
|
453 |
+
raise ValueError("You have to specify either input_ids or inputs_embeds")
|
454 |
+
|
455 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
456 |
+
|
457 |
+
if token_type_ids is not None:
|
458 |
+
token_type_ids = token_type_ids.view(-1, input_shape[-1])
|
459 |
+
|
460 |
+
if position_ids is not None:
|
461 |
+
position_ids = position_ids.view(-1, input_shape[-1]).long()
|
462 |
+
|
463 |
+
if past_key_values is None:
|
464 |
+
past_length = 0
|
465 |
+
past_key_values = tuple([None] * len(self.h))
|
466 |
+
else:
|
467 |
+
past_length = past_key_values[0][0].size(-2)
|
468 |
+
|
469 |
+
if position_ids is None:
|
470 |
+
position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
|
471 |
+
position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
|
472 |
+
|
473 |
+
# Attention mask.
|
474 |
+
if attention_mask is not None:
|
475 |
+
if batch_size <= 0:
|
476 |
+
raise ValueError("batch_size has to be defined and > 0")
|
477 |
+
attention_mask = attention_mask.view(batch_size, -1)
|
478 |
+
# We create a 3D attention mask from a 2D tensor mask.
|
479 |
+
# Sizes are [batch_size, 1, 1, to_seq_length]
|
480 |
+
# So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
|
481 |
+
# this attention mask is more simple than the triangular masking of causal attention
|
482 |
+
# used in OpenAI GPT, we just need to prepare the broadcast dimension here.
|
483 |
+
attention_mask = attention_mask[:, None, None, :]
|
484 |
+
|
485 |
+
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
|
486 |
+
# masked positions, this operation will create a tensor which is 0.0 for
|
487 |
+
# positions we want to attend and the dtype's smallest value for masked positions.
|
488 |
+
# Since we are adding it to the raw scores before the softmax, this is
|
489 |
+
# effectively the same as removing these entirely.
|
490 |
+
attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
|
491 |
+
attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
|
492 |
+
|
493 |
+
# Prepare head mask if needed
|
494 |
+
# 1.0 in head_mask indicate we keep the head
|
495 |
+
# attention_probs has shape bsz x num_attention_heads x N x N
|
496 |
+
# head_mask has shape n_layer x batch x num_attention_heads x N x N
|
497 |
+
head_mask = self.get_head_mask(head_mask, self.config.n_layer)
|
498 |
+
|
499 |
+
if inputs_embeds is None:
|
500 |
+
inputs_embeds = self.wte(input_ids)
|
501 |
+
|
502 |
+
hidden_states = inputs_embeds
|
503 |
+
|
504 |
+
if token_type_ids is not None:
|
505 |
+
token_type_embeds = self.wte(token_type_ids)
|
506 |
+
hidden_states = hidden_states + token_type_embeds
|
507 |
+
|
508 |
+
hidden_states = self.drop(hidden_states)
|
509 |
+
|
510 |
+
output_shape = input_shape + (hidden_states.size(-1),)
|
511 |
+
|
512 |
+
if self.gradient_checkpointing and self.training:
|
513 |
+
if use_cache:
|
514 |
+
logger.warning_once(
|
515 |
+
"`use_cache=True` is incompatible with `config.gradient_checkpointing=True`. Setting "
|
516 |
+
"`use_cache=False`..."
|
517 |
+
)
|
518 |
+
use_cache = False
|
519 |
+
|
520 |
+
presents = () if use_cache else None
|
521 |
+
all_self_attentions = () if output_attentions else None
|
522 |
+
all_hidden_states = () if output_hidden_states else None
|
523 |
+
for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
|
524 |
+
if output_hidden_states:
|
525 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
526 |
+
|
527 |
+
if self.gradient_checkpointing and self.training:
|
528 |
+
|
529 |
+
def create_custom_forward(module):
|
530 |
+
def custom_forward(*inputs):
|
531 |
+
# None for past_key_value
|
532 |
+
return module(*inputs, use_cache, output_attentions)
|
533 |
+
|
534 |
+
return custom_forward
|
535 |
+
|
536 |
+
outputs = torch.utils.checkpoint.checkpoint(
|
537 |
+
create_custom_forward(block),
|
538 |
+
hidden_states,
|
539 |
+
None,
|
540 |
+
attention_mask,
|
541 |
+
position_ids,
|
542 |
+
head_mask[i],
|
543 |
+
)
|
544 |
+
else:
|
545 |
+
outputs = block(
|
546 |
+
hidden_states=hidden_states,
|
547 |
+
layer_past=layer_past,
|
548 |
+
attention_mask=attention_mask,
|
549 |
+
position_ids=position_ids,
|
550 |
+
head_mask=head_mask[i],
|
551 |
+
use_cache=use_cache,
|
552 |
+
output_attentions=output_attentions,
|
553 |
+
)
|
554 |
+
|
555 |
+
hidden_states = outputs[0]
|
556 |
+
if use_cache is True:
|
557 |
+
presents = presents + (outputs[1],)
|
558 |
+
|
559 |
+
if output_attentions:
|
560 |
+
all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
|
561 |
+
|
562 |
+
hidden_states = self.ln_f(hidden_states)
|
563 |
+
|
564 |
+
hidden_states = hidden_states.view(output_shape)
|
565 |
+
# Add last hidden state
|
566 |
+
if output_hidden_states:
|
567 |
+
all_hidden_states = all_hidden_states + (hidden_states,)
|
568 |
+
|
569 |
+
if not return_dict:
|
570 |
+
return tuple(v for v in [hidden_states, presents, all_hidden_states, all_self_attentions] if v is not None)
|
571 |
+
|
572 |
+
return BaseModelOutputWithPast(
|
573 |
+
last_hidden_state=hidden_states,
|
574 |
+
past_key_values=presents,
|
575 |
+
hidden_states=all_hidden_states,
|
576 |
+
attentions=all_self_attentions,
|
577 |
+
)
|
578 |
+
|
579 |
+
|
580 |
+
@add_start_docstrings(
|
581 |
+
"""
|
582 |
+
The Moss Model transformer with a language modeling head on top.
|
583 |
+
""",
|
584 |
+
MOSS_START_DOCSTRING,
|
585 |
+
)
|
586 |
+
class MossForCausalLM(MossPreTrainedModel):
|
587 |
+
_keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.causal_mask"]
|
588 |
+
|
589 |
+
def __init__(self, config):
|
590 |
+
super().__init__(config)
|
591 |
+
if not hasattr(config, 'wbits'):
|
592 |
+
config.wbits = 32
|
593 |
+
config.groupsize = 128
|
594 |
+
|
595 |
+
if config.wbits not in [4, 8, 32]:
|
596 |
+
logger.warning(f'Specify `wbits` with 4, 8 or 32 to load the model. ')
|
597 |
+
if config.wbits in [4, 8]:
|
598 |
+
def noop(*args, **kwargs):
|
599 |
+
pass
|
600 |
+
torch.nn.init.kaiming_uniform_ = noop
|
601 |
+
torch.nn.init.uniform_ = noop
|
602 |
+
torch.nn.init.normal_ = noop
|
603 |
+
|
604 |
+
torch.set_default_dtype(torch.half)
|
605 |
+
transformers.modeling_utils._init_weights = False
|
606 |
+
torch.set_default_dtype(torch.half)
|
607 |
+
self.transformer = MossModel(config)
|
608 |
+
self.lm_head = nn.Linear(config.n_embd, config.vocab_size)
|
609 |
+
if config.wbits in [4, 8]:
|
610 |
+
torch.set_default_dtype(torch.float)
|
611 |
+
transformers.modeling_utils._init_weights = True
|
612 |
+
self.quantize(config.wbits, config.groupsize)
|
613 |
+
# Initialize weights and apply final processing
|
614 |
+
self.post_init()
|
615 |
+
|
616 |
+
def get_output_embeddings(self):
|
617 |
+
return self.lm_head
|
618 |
+
|
619 |
+
def set_output_embeddings(self, new_embeddings):
|
620 |
+
self.lm_head = new_embeddings
|
621 |
+
|
622 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, **kwargs):
|
623 |
+
token_type_ids = kwargs.get("token_type_ids", None)
|
624 |
+
# only last token for inputs_ids if past is defined in kwargs
|
625 |
+
if past_key_values:
|
626 |
+
input_ids = input_ids[:, -1].unsqueeze(-1)
|
627 |
+
if token_type_ids is not None:
|
628 |
+
token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
|
629 |
+
|
630 |
+
attention_mask = kwargs.get("attention_mask", None)
|
631 |
+
position_ids = kwargs.get("position_ids", None)
|
632 |
+
|
633 |
+
if attention_mask is not None and position_ids is None:
|
634 |
+
# create position_ids on the fly for batch generation
|
635 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
636 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
637 |
+
if past_key_values:
|
638 |
+
position_ids = position_ids[:, -1].unsqueeze(-1)
|
639 |
+
|
640 |
+
return {
|
641 |
+
"input_ids": input_ids,
|
642 |
+
"past_key_values": past_key_values,
|
643 |
+
"use_cache": kwargs.get("use_cache"),
|
644 |
+
"position_ids": position_ids,
|
645 |
+
"attention_mask": attention_mask,
|
646 |
+
"token_type_ids": token_type_ids,
|
647 |
+
}
|
648 |
+
|
649 |
+
@add_start_docstrings_to_model_forward(MOSS_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
|
650 |
+
@add_code_sample_docstrings(
|
651 |
+
checkpoint=_CHECKPOINT_FOR_DOC,
|
652 |
+
output_type=CausalLMOutputWithPast,
|
653 |
+
config_class=_CONFIG_FOR_DOC,
|
654 |
+
)
|
655 |
+
def forward(
|
656 |
+
self,
|
657 |
+
input_ids: Optional[torch.LongTensor] = None,
|
658 |
+
past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None,
|
659 |
+
attention_mask: Optional[torch.FloatTensor] = None,
|
660 |
+
token_type_ids: Optional[torch.LongTensor] = None,
|
661 |
+
position_ids: Optional[torch.LongTensor] = None,
|
662 |
+
head_mask: Optional[torch.FloatTensor] = None,
|
663 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
664 |
+
labels: Optional[torch.LongTensor] = None,
|
665 |
+
use_cache: Optional[bool] = None,
|
666 |
+
output_attentions: Optional[bool] = None,
|
667 |
+
output_hidden_states: Optional[bool] = None,
|
668 |
+
return_dict: Optional[bool] = None,
|
669 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
670 |
+
r"""
|
671 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
672 |
+
Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
|
673 |
+
`labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
|
674 |
+
are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
|
675 |
+
"""
|
676 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
677 |
+
|
678 |
+
transformer_outputs = self.transformer(
|
679 |
+
input_ids,
|
680 |
+
past_key_values=past_key_values,
|
681 |
+
attention_mask=attention_mask,
|
682 |
+
token_type_ids=token_type_ids,
|
683 |
+
position_ids=position_ids,
|
684 |
+
head_mask=head_mask,
|
685 |
+
inputs_embeds=inputs_embeds,
|
686 |
+
use_cache=use_cache,
|
687 |
+
output_attentions=output_attentions,
|
688 |
+
output_hidden_states=output_hidden_states,
|
689 |
+
return_dict=return_dict,
|
690 |
+
)
|
691 |
+
hidden_states = transformer_outputs[0]
|
692 |
+
|
693 |
+
# make sure sampling in fp16 works correctly and
|
694 |
+
# compute loss in fp32 to match with mesh-tf version
|
695 |
+
# https://github.com/EleutherAI/gpt-neo/blob/89ce74164da2fb16179106f54e2269b5da8db333/models/gpt2/gpt2.py#L179
|
696 |
+
lm_logits = self.lm_head(hidden_states).to(torch.float32)
|
697 |
+
|
698 |
+
loss = None
|
699 |
+
if labels is not None:
|
700 |
+
# Shift so that tokens < n predict n
|
701 |
+
shift_logits = lm_logits[..., :-1, :].contiguous()
|
702 |
+
shift_labels = labels[..., 1:].contiguous()
|
703 |
+
# Flatten the tokens
|
704 |
+
loss_fct = CrossEntropyLoss()
|
705 |
+
loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
|
706 |
+
|
707 |
+
loss = loss.to(hidden_states.dtype)
|
708 |
+
|
709 |
+
if not return_dict:
|
710 |
+
output = (lm_logits,) + transformer_outputs[1:]
|
711 |
+
return ((loss,) + output) if loss is not None else output
|
712 |
+
|
713 |
+
return CausalLMOutputWithPast(
|
714 |
+
loss=loss,
|
715 |
+
logits=lm_logits,
|
716 |
+
past_key_values=transformer_outputs.past_key_values,
|
717 |
+
hidden_states=transformer_outputs.hidden_states,
|
718 |
+
attentions=transformer_outputs.attentions,
|
719 |
+
)
|
720 |
+
|
721 |
+
@staticmethod
|
722 |
+
def _reorder_cache(
|
723 |
+
past_key_values: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor
|
724 |
+
) -> Tuple[Tuple[torch.Tensor]]:
|
725 |
+
"""
|
726 |
+
This function is used to re-order the `past_key_values` cache if [`~PretrainedModel.beam_search`] or
|
727 |
+
[`~PretrainedModel.beam_sample`] is called. This is required to match `past_key_values` with the correct
|
728 |
+
beam_idx at every generation step.
|
729 |
+
"""
|
730 |
+
return tuple(
|
731 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
|
732 |
+
for layer_past in past_key_values
|
733 |
+
)
|
734 |
+
|
735 |
+
def quantize(self, wbits, groupsize):
|
736 |
+
from .quantization import quantize_with_gptq
|
737 |
+
return quantize_with_gptq(self, wbits, groupsize)
|
738 |
+
|
models/quantization.py
ADDED
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import numpy as np
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
from torch.cuda.amp import custom_bwd, custom_fwd
|
5 |
+
import math
|
6 |
+
|
7 |
+
|
8 |
+
def find_layers(module, layers=[nn.Conv2d, nn.Linear], name=''):
|
9 |
+
if type(module) in layers:
|
10 |
+
return {name: module}
|
11 |
+
res = {}
|
12 |
+
for name1, child in module.named_children():
|
13 |
+
res.update(find_layers(
|
14 |
+
child, layers=layers, name=name + '.' + name1 if name != '' else name1
|
15 |
+
))
|
16 |
+
return res
|
17 |
+
|
18 |
+
|
19 |
+
try:
|
20 |
+
import triton
|
21 |
+
import triton.language as tl
|
22 |
+
from .custom_autotune import *
|
23 |
+
except:
|
24 |
+
print('triton not installed. Run `pip install triton` to load quantized version of MOSS.')
|
25 |
+
|
26 |
+
# code based https://github.com/fpgaminer/GPTQ-triton
|
27 |
+
@autotune(
|
28 |
+
configs=[
|
29 |
+
triton.Config({'BLOCK_SIZE_M': 256, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
|
30 |
+
num_stages=4, num_warps=4),
|
31 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 256, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
|
32 |
+
num_stages=4, num_warps=4),
|
33 |
+
triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
|
34 |
+
num_stages=4, num_warps=4),
|
35 |
+
triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
|
36 |
+
num_stages=4, num_warps=4),
|
37 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 128, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
|
38 |
+
num_stages=4, num_warps=4),
|
39 |
+
triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_N': 32, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8},
|
40 |
+
num_stages=4, num_warps=4),
|
41 |
+
# These provided a benefit on a 3090
|
42 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
|
43 |
+
num_warps=4),
|
44 |
+
triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
|
45 |
+
num_warps=4),
|
46 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 32, 'BLOCK_SIZE_K': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
|
47 |
+
num_warps=4),
|
48 |
+
triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
|
49 |
+
num_warps=4),
|
50 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
|
51 |
+
num_warps=4),
|
52 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_N': 32, 'BLOCK_SIZE_K': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
|
53 |
+
num_warps=4),
|
54 |
+
triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_N': 64, 'BLOCK_SIZE_K': 128, 'GROUP_SIZE_M': 8},
|
55 |
+
num_stages=4, num_warps=4),
|
56 |
+
],
|
57 |
+
key=['M', 'N'],
|
58 |
+
nearest_power_of_two=True,
|
59 |
+
)
|
60 |
+
@triton.jit
|
61 |
+
def matmul_248_kernel(a_ptr, b_ptr, c_ptr,
|
62 |
+
scales_ptr, zeros_ptr, g_ptr,
|
63 |
+
M, N, K, bits, maxq,
|
64 |
+
stride_am, stride_ak,
|
65 |
+
stride_bk, stride_bn,
|
66 |
+
stride_cm, stride_cn,
|
67 |
+
stride_scales, stride_zeros,
|
68 |
+
BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
|
69 |
+
GROUP_SIZE_M: tl.constexpr):
|
70 |
+
"""
|
71 |
+
Compute the matrix multiplication C = A x B.
|
72 |
+
A is of shape (M, K) float16
|
73 |
+
B is of shape (K//8, N) int32
|
74 |
+
C is of shape (M, N) float16
|
75 |
+
scales is of shape (G, N) float16
|
76 |
+
zeros is of shape (G, N) float16
|
77 |
+
g_ptr is of shape (K) int32
|
78 |
+
"""
|
79 |
+
infearure_per_bits = 32 // bits
|
80 |
+
|
81 |
+
pid = tl.program_id(axis=0)
|
82 |
+
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
83 |
+
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
84 |
+
num_pid_k = tl.cdiv(K, BLOCK_SIZE_K)
|
85 |
+
num_pid_in_group = GROUP_SIZE_M * num_pid_n
|
86 |
+
group_id = pid // num_pid_in_group
|
87 |
+
first_pid_m = group_id * GROUP_SIZE_M
|
88 |
+
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
|
89 |
+
pid_m = first_pid_m + (pid % group_size_m)
|
90 |
+
pid_n = (pid % num_pid_in_group) // group_size_m
|
91 |
+
|
92 |
+
offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
93 |
+
offs_bn = pid_n * BLOCK_SIZE_N + tl.arange(0, BLOCK_SIZE_N)
|
94 |
+
offs_k = tl.arange(0, BLOCK_SIZE_K)
|
95 |
+
a_ptrs = a_ptr + (offs_am[:, None] * stride_am + offs_k[None, :] * stride_ak) # (BLOCK_SIZE_M, BLOCK_SIZE_K)
|
96 |
+
a_mask = (offs_am[:, None] < M)
|
97 |
+
# b_ptrs is set up such that it repeats elements along the K axis 8 times
|
98 |
+
b_ptrs = b_ptr + ((offs_k[:, None] // infearure_per_bits) * stride_bk + offs_bn[None,
|
99 |
+
:] * stride_bn) # (BLOCK_SIZE_K, BLOCK_SIZE_N)
|
100 |
+
g_ptrs = g_ptr + offs_k
|
101 |
+
# shifter is used to extract the N bits of each element in the 32-bit word from B
|
102 |
+
scales_ptrs = scales_ptr + offs_bn[None, :]
|
103 |
+
zeros_ptrs = zeros_ptr + (offs_bn[None, :] // infearure_per_bits)
|
104 |
+
|
105 |
+
shifter = (offs_k % infearure_per_bits) * bits
|
106 |
+
zeros_shifter = (offs_bn % infearure_per_bits) * bits
|
107 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_N), dtype=tl.float32)
|
108 |
+
|
109 |
+
for k in range(0, num_pid_k):
|
110 |
+
g_idx = tl.load(g_ptrs)
|
111 |
+
|
112 |
+
# Fetch scales and zeros; these are per-outfeature and thus reused in the inner loop
|
113 |
+
scales = tl.load(scales_ptrs + g_idx[:, None] * stride_scales) # (BLOCK_SIZE_K, BLOCK_SIZE_N,)
|
114 |
+
zeros = tl.load(zeros_ptrs + g_idx[:, None] * stride_zeros) # (BLOCK_SIZE_K, BLOCK_SIZE_N,)
|
115 |
+
|
116 |
+
zeros = (zeros >> zeros_shifter[None, :]) & maxq
|
117 |
+
zeros = (zeros + 1)
|
118 |
+
|
119 |
+
a = tl.load(a_ptrs, mask=a_mask, other=0.) # (BLOCK_SIZE_M, BLOCK_SIZE_K)
|
120 |
+
b = tl.load(b_ptrs) # (BLOCK_SIZE_K, BLOCK_SIZE_N), but repeated
|
121 |
+
|
122 |
+
# Now we need to unpack b (which is N-bit values) into 32-bit values
|
123 |
+
b = (b >> shifter[:, None]) & maxq # Extract the N-bit values
|
124 |
+
b = (b - zeros) * scales # Scale and shift
|
125 |
+
|
126 |
+
accumulator += tl.dot(a, b)
|
127 |
+
a_ptrs += BLOCK_SIZE_K
|
128 |
+
b_ptrs += (BLOCK_SIZE_K // infearure_per_bits) * stride_bk
|
129 |
+
g_ptrs += BLOCK_SIZE_K
|
130 |
+
|
131 |
+
c = accumulator.to(tl.float16)
|
132 |
+
c_ptrs = c_ptr + stride_cm * offs_am[:, None] + stride_cn * offs_bn[None, :]
|
133 |
+
c_mask = (offs_am[:, None] < M) & (offs_bn[None, :] < N)
|
134 |
+
tl.store(c_ptrs, accumulator, mask=c_mask)
|
135 |
+
|
136 |
+
|
137 |
+
# code based https://github.com/fpgaminer/GPTQ-triton
|
138 |
+
@autotune(
|
139 |
+
configs=[
|
140 |
+
triton.Config({'BLOCK_SIZE_M': 256, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
|
141 |
+
num_stages=4, num_warps=4),
|
142 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 256, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
|
143 |
+
num_stages=4, num_warps=4),
|
144 |
+
triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_K': 128, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
|
145 |
+
num_stages=4, num_warps=4),
|
146 |
+
triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
|
147 |
+
num_stages=4, num_warps=4),
|
148 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 128, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
|
149 |
+
num_stages=4, num_warps=4),
|
150 |
+
triton.Config({'BLOCK_SIZE_M': 128, 'BLOCK_SIZE_K': 32, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8},
|
151 |
+
num_stages=4, num_warps=4),
|
152 |
+
# These provided a benefit on a 3090
|
153 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
|
154 |
+
num_warps=4),
|
155 |
+
triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
|
156 |
+
num_warps=4),
|
157 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 32, 'BLOCK_SIZE_N': 32, 'GROUP_SIZE_M': 8}, num_stages=4,
|
158 |
+
num_warps=4),
|
159 |
+
triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
|
160 |
+
num_warps=4),
|
161 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
|
162 |
+
num_warps=4),
|
163 |
+
triton.Config({'BLOCK_SIZE_M': 64, 'BLOCK_SIZE_K': 32, 'BLOCK_SIZE_N': 64, 'GROUP_SIZE_M': 8}, num_stages=4,
|
164 |
+
num_warps=4),
|
165 |
+
triton.Config({'BLOCK_SIZE_M': 32, 'BLOCK_SIZE_K': 64, 'BLOCK_SIZE_N': 128, 'GROUP_SIZE_M': 8},
|
166 |
+
num_stages=4, num_warps=4),
|
167 |
+
],
|
168 |
+
key=['M', 'K'],
|
169 |
+
nearest_power_of_two=True,
|
170 |
+
)
|
171 |
+
@triton.jit
|
172 |
+
def trans_matmul_248_kernel(a_ptr, b_ptr, c_ptr,
|
173 |
+
scales_ptr, zeros_ptr, g_ptr,
|
174 |
+
M, N, K, bits, maxq,
|
175 |
+
stride_am, stride_ak,
|
176 |
+
stride_bk, stride_bn,
|
177 |
+
stride_cm, stride_cn,
|
178 |
+
stride_scales, stride_zeros,
|
179 |
+
BLOCK_SIZE_M: tl.constexpr, BLOCK_SIZE_N: tl.constexpr, BLOCK_SIZE_K: tl.constexpr,
|
180 |
+
GROUP_SIZE_M: tl.constexpr):
|
181 |
+
"""
|
182 |
+
Compute the matrix multiplication C = A x B.
|
183 |
+
A is of shape (M, N) float16
|
184 |
+
B is of shape (K//8, N) int32
|
185 |
+
C is of shape (M, K) float16
|
186 |
+
scales is of shape (G, N) float16
|
187 |
+
zeros is of shape (G, N) float16
|
188 |
+
g_ptr is of shape (K) int32
|
189 |
+
"""
|
190 |
+
infearure_per_bits = 32 // bits
|
191 |
+
|
192 |
+
pid = tl.program_id(axis=0)
|
193 |
+
num_pid_m = tl.cdiv(M, BLOCK_SIZE_M)
|
194 |
+
num_pid_k = tl.cdiv(K, BLOCK_SIZE_K)
|
195 |
+
num_pid_n = tl.cdiv(N, BLOCK_SIZE_N)
|
196 |
+
num_pid_in_group = GROUP_SIZE_M * num_pid_k
|
197 |
+
group_id = pid // num_pid_in_group
|
198 |
+
first_pid_m = group_id * GROUP_SIZE_M
|
199 |
+
group_size_m = min(num_pid_m - first_pid_m, GROUP_SIZE_M)
|
200 |
+
pid_m = first_pid_m + (pid % group_size_m)
|
201 |
+
pid_k = (pid % num_pid_in_group) // group_size_m
|
202 |
+
|
203 |
+
offs_am = pid_m * BLOCK_SIZE_M + tl.arange(0, BLOCK_SIZE_M)
|
204 |
+
offs_bk = pid_k * BLOCK_SIZE_K + tl.arange(0, BLOCK_SIZE_K)
|
205 |
+
offs_n = tl.arange(0, BLOCK_SIZE_N)
|
206 |
+
a_ptrs = a_ptr + (offs_am[:, None] * stride_am + offs_n[None, :] * stride_ak) # (BLOCK_SIZE_M, BLOCK_SIZE_N)
|
207 |
+
a_mask = (offs_am[:, None] < M)
|
208 |
+
# b_ptrs is set up such that it repeats elements along the K axis 8 times
|
209 |
+
b_ptrs = b_ptr + ((offs_bk[:, None] // infearure_per_bits) * stride_bk + offs_n[None,
|
210 |
+
:] * stride_bn) # (BLOCK_SIZE_K, BLOCK_SIZE_N)
|
211 |
+
g_ptrs = g_ptr + offs_bk
|
212 |
+
g_idx = tl.load(g_ptrs)
|
213 |
+
|
214 |
+
# shifter is used to extract the N bits of each element in the 32-bit word from B
|
215 |
+
scales_ptrs = scales_ptr + offs_n[None, :] + g_idx[:, None] * stride_scales
|
216 |
+
zeros_ptrs = zeros_ptr + (offs_n[None, :] // infearure_per_bits) + g_idx[:, None] * stride_zeros
|
217 |
+
|
218 |
+
shifter = (offs_bk % infearure_per_bits) * bits
|
219 |
+
zeros_shifter = (offs_n % infearure_per_bits) * bits
|
220 |
+
accumulator = tl.zeros((BLOCK_SIZE_M, BLOCK_SIZE_K), dtype=tl.float32)
|
221 |
+
|
222 |
+
for k in range(0, num_pid_n):
|
223 |
+
# Fetch scales and zeros; these are per-outfeature and thus reused in the inner loop
|
224 |
+
scales = tl.load(scales_ptrs) # (BLOCK_SIZE_K, BLOCK_SIZE_N,)
|
225 |
+
zeros = tl.load(zeros_ptrs) # (BLOCK_SIZE_K, BLOCK_SIZE_N,)
|
226 |
+
|
227 |
+
zeros = (zeros >> zeros_shifter[None, :]) & maxq
|
228 |
+
zeros = (zeros + 1)
|
229 |
+
|
230 |
+
a = tl.load(a_ptrs, mask=a_mask, other=0.) # (BLOCK_SIZE_M, BLOCK_SIZE_N)
|
231 |
+
b = tl.load(b_ptrs) # (BLOCK_SIZE_K, BLOCK_SIZE_N), but repeated
|
232 |
+
|
233 |
+
# Now we need to unpack b (which is N-bit values) into 32-bit values
|
234 |
+
b = (b >> shifter[:, None]) & maxq # Extract the N-bit values
|
235 |
+
b = (b - zeros) * scales # Scale and shift
|
236 |
+
b = tl.trans(b)
|
237 |
+
|
238 |
+
accumulator += tl.dot(a, b)
|
239 |
+
a_ptrs += BLOCK_SIZE_N
|
240 |
+
b_ptrs += BLOCK_SIZE_N
|
241 |
+
scales_ptrs += BLOCK_SIZE_N
|
242 |
+
zeros_ptrs += (BLOCK_SIZE_N // infearure_per_bits)
|
243 |
+
|
244 |
+
c = accumulator.to(tl.float16)
|
245 |
+
c_ptrs = c_ptr + stride_cm * offs_am[:, None] + stride_cn * offs_bk[None, :]
|
246 |
+
c_mask = (offs_am[:, None] < M) & (offs_bk[None, :] < K)
|
247 |
+
tl.store(c_ptrs, accumulator, mask=c_mask)
|
248 |
+
|
249 |
+
|
250 |
+
def matmul248(input, qweight, scales, qzeros, g_idx, bits, maxq):
|
251 |
+
output = torch.empty((input.shape[0], qweight.shape[1]), device='cuda', dtype=torch.float16)
|
252 |
+
grid = lambda META: (
|
253 |
+
triton.cdiv(input.shape[0], META['BLOCK_SIZE_M']) * triton.cdiv(qweight.shape[1], META['BLOCK_SIZE_N']),)
|
254 |
+
matmul_248_kernel[grid](input, qweight, output,
|
255 |
+
scales, qzeros, g_idx,
|
256 |
+
input.shape[0], qweight.shape[1], input.shape[1], bits, maxq,
|
257 |
+
input.stride(0), input.stride(1),
|
258 |
+
qweight.stride(0), qweight.stride(1),
|
259 |
+
output.stride(0), output.stride(1),
|
260 |
+
scales.stride(0), qzeros.stride(0))
|
261 |
+
return output
|
262 |
+
|
263 |
+
|
264 |
+
def transpose_matmul248(input, qweight, scales, qzeros, g_idx, bits, maxq):
|
265 |
+
output_dim = (qweight.shape[0] * 32) // bits
|
266 |
+
output = torch.empty((input.shape[0], output_dim), device='cuda', dtype=torch.float16)
|
267 |
+
grid = lambda META: (
|
268 |
+
triton.cdiv(input.shape[0], META['BLOCK_SIZE_M']) * triton.cdiv(output_dim, META['BLOCK_SIZE_K']),)
|
269 |
+
transpose_matmul_248_kernel[grid](input, qweight, output,
|
270 |
+
scales, qzeros, g_idx,
|
271 |
+
input.shape[0], qweight.shape[1], output_dim, bits, maxq,
|
272 |
+
input.stride(0), input.stride(1),
|
273 |
+
qweight.stride(0), qweight.stride(1),
|
274 |
+
output.stride(0), output.stride(1),
|
275 |
+
scales.stride(0), qzeros.stride(0))
|
276 |
+
return output
|
277 |
+
|
278 |
+
|
279 |
+
class QuantLinearFunction(torch.autograd.Function):
|
280 |
+
@staticmethod
|
281 |
+
@custom_fwd(cast_inputs=torch.float16)
|
282 |
+
def forward(ctx, input, qweight, scales, qzeros, g_idx, bits, maxq):
|
283 |
+
output = matmul248(input, qweight, scales, qzeros, g_idx, bits, maxq)
|
284 |
+
ctx.save_for_backward(qweight, scales, qzeros, g_idx)
|
285 |
+
ctx.bits, ctx.maxq = bits, maxq
|
286 |
+
return output
|
287 |
+
|
288 |
+
@staticmethod
|
289 |
+
@custom_bwd
|
290 |
+
def backward(ctx, grad_output):
|
291 |
+
qweight, scales, qzeros, g_idx = ctx.saved_tensors
|
292 |
+
bits, maxq = ctx.bits, ctx.maxq
|
293 |
+
grad_input = None
|
294 |
+
|
295 |
+
if ctx.needs_input_grad[0]:
|
296 |
+
grad_input = transpose_matmul248(grad_output, qweight, scales, qzeros, g_idx, bits, maxq)
|
297 |
+
return grad_input, None, None, None, None, None, None
|
298 |
+
|
299 |
+
class QuantLinear(nn.Module):
|
300 |
+
def __init__(self, bits, groupsize, infeatures, outfeatures, bias):
|
301 |
+
super().__init__()
|
302 |
+
if bits not in [2, 4, 8]:
|
303 |
+
raise NotImplementedError("Only 2,4,8 bits are supported.")
|
304 |
+
self.infeatures = infeatures
|
305 |
+
self.outfeatures = outfeatures
|
306 |
+
self.bits = bits
|
307 |
+
self.maxq = 2 ** self.bits - 1
|
308 |
+
self.groupsize = groupsize if groupsize != -1 else infeatures
|
309 |
+
|
310 |
+
self.register_buffer('qweight', torch.zeros((infeatures // 32 * self.bits, outfeatures), dtype=torch.int32))
|
311 |
+
self.register_buffer('qzeros', torch.zeros((math.ceil(infeatures / self.groupsize), outfeatures // 32 * self.bits), dtype=torch.int32))
|
312 |
+
self.register_buffer('scales', torch.zeros((math.ceil(infeatures / self.groupsize), outfeatures), dtype=torch.float16))
|
313 |
+
self.register_buffer('g_idx', torch.tensor([i // self.groupsize for i in range(infeatures)], dtype=torch.int32))
|
314 |
+
if bias:
|
315 |
+
self.register_buffer('bias', torch.zeros((outfeatures), dtype=torch.float16))
|
316 |
+
else:
|
317 |
+
self.bias = None
|
318 |
+
|
319 |
+
def pack(self, linear, scales, zeros, g_idx=None):
|
320 |
+
self.g_idx = g_idx.clone() if g_idx is not None else self.g_idx
|
321 |
+
|
322 |
+
scales = scales.t().contiguous()
|
323 |
+
zeros = zeros.t().contiguous()
|
324 |
+
scale_zeros = zeros * scales
|
325 |
+
self.scales = scales.clone().half()
|
326 |
+
if linear.bias is not None:
|
327 |
+
self.bias = linear.bias.clone().half()
|
328 |
+
|
329 |
+
intweight = []
|
330 |
+
for idx in range(self.infeatures):
|
331 |
+
intweight.append(torch.round(
|
332 |
+
(linear.weight.data[:, idx] + scale_zeros[self.g_idx[idx]]) / self.scales[self.g_idx[idx]]).to(
|
333 |
+
torch.int)[:, None])
|
334 |
+
intweight = torch.cat(intweight, dim=1)
|
335 |
+
intweight = intweight.t().contiguous()
|
336 |
+
intweight = intweight.numpy().astype(np.uint32)
|
337 |
+
qweight = np.zeros((intweight.shape[0] // 32 * self.bits, intweight.shape[1]), dtype=np.uint32)
|
338 |
+
i = 0
|
339 |
+
row = 0
|
340 |
+
while row < qweight.shape[0]:
|
341 |
+
if self.bits in [2, 4, 8]:
|
342 |
+
for j in range(i, i + (32 // self.bits)):
|
343 |
+
qweight[row] |= intweight[j] << (self.bits * (j - i))
|
344 |
+
i += 32 // self.bits
|
345 |
+
row += 1
|
346 |
+
else:
|
347 |
+
raise NotImplementedError("Only 2,4,8 bits are supported.")
|
348 |
+
|
349 |
+
qweight = qweight.astype(np.int32)
|
350 |
+
self.qweight = torch.from_numpy(qweight)
|
351 |
+
|
352 |
+
zeros -= 1
|
353 |
+
zeros = zeros.numpy().astype(np.uint32)
|
354 |
+
qzeros = np.zeros((zeros.shape[0], zeros.shape[1] // 32 * self.bits), dtype=np.uint32)
|
355 |
+
i = 0
|
356 |
+
col = 0
|
357 |
+
while col < qzeros.shape[1]:
|
358 |
+
if self.bits in [2, 4, 8]:
|
359 |
+
for j in range(i, i + (32 // self.bits)):
|
360 |
+
qzeros[:, col] |= zeros[:, j] << (self.bits * (j - i))
|
361 |
+
i += 32 // self.bits
|
362 |
+
col += 1
|
363 |
+
else:
|
364 |
+
raise NotImplementedError("Only 2,4,8 bits are supported.")
|
365 |
+
|
366 |
+
qzeros = qzeros.astype(np.int32)
|
367 |
+
self.qzeros = torch.from_numpy(qzeros)
|
368 |
+
|
369 |
+
def forward(self, x):
|
370 |
+
out_shape = x.shape[:-1] + (self.outfeatures,)
|
371 |
+
out = QuantLinearFunction.apply(x.reshape(-1, x.shape[-1]), self.qweight, self.scales,
|
372 |
+
self.qzeros, self.g_idx, self.bits, self.maxq)
|
373 |
+
out = out + self.bias if self.bias is not None else out
|
374 |
+
return out.reshape(out_shape)
|
375 |
+
|
376 |
+
def make_quant(module, names, bits, groupsize, name=''):
|
377 |
+
if isinstance(module, QuantLinear):
|
378 |
+
return
|
379 |
+
for attr in dir(module):
|
380 |
+
tmp = getattr(module, attr)
|
381 |
+
name1 = name + '.' + attr if name != '' else attr
|
382 |
+
if name1 in names:
|
383 |
+
delattr(module, attr)
|
384 |
+
setattr(module, attr, QuantLinear(bits, groupsize, tmp.in_features, tmp.out_features, tmp.bias is not None))
|
385 |
+
for name1, child in module.named_children():
|
386 |
+
make_quant(child, names, bits, groupsize, name + '.' + name1 if name != '' else name1)
|
387 |
+
|
388 |
+
|
389 |
+
def quantize_with_gptq(model, wbits, groupsize):
|
390 |
+
model = model.eval()
|
391 |
+
layers = find_layers(model)
|
392 |
+
for name in ['lm_head']:
|
393 |
+
if name in layers:
|
394 |
+
del layers[name]
|
395 |
+
make_quant(model, layers, wbits, groupsize)
|
396 |
+
# model.load_state_dict(torch.load(checkpoint))
|
397 |
+
return model
|
models/tokenization_moss.py
ADDED
@@ -0,0 +1,380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Tokenization classes for Moss"""
|
2 |
+
|
3 |
+
import json
|
4 |
+
import os
|
5 |
+
import numpy as np
|
6 |
+
import regex as re
|
7 |
+
|
8 |
+
from functools import lru_cache
|
9 |
+
from typing import TYPE_CHECKING, List, Optional, Tuple, Union
|
10 |
+
|
11 |
+
from transformers.utils import is_tf_available, is_torch_available, logging
|
12 |
+
from transformers.tokenization_utils import AddedToken, PreTrainedTokenizer
|
13 |
+
|
14 |
+
|
15 |
+
if TYPE_CHECKING:
|
16 |
+
if is_torch_available():
|
17 |
+
import torch
|
18 |
+
if is_tf_available():
|
19 |
+
import tensorflow as tf
|
20 |
+
|
21 |
+
|
22 |
+
logger = logging.get_logger(__name__)
|
23 |
+
|
24 |
+
VOCAB_FILES_NAMES = {
|
25 |
+
"vocab_file": "vocab.json",
|
26 |
+
"merges_file": "merges.txt",
|
27 |
+
}
|
28 |
+
|
29 |
+
PRETRAINED_VOCAB_FILES_MAP = {
|
30 |
+
"vocab_file": {
|
31 |
+
"fnlp/moss-moon-003-base": "https://huggingface.co/fnlp/moss-moon-003-base/resolve/main/vocab.json",
|
32 |
+
"fnlp/moss-moon-003-sft": "https://huggingface.co/fnlp/moss-moon-003-sft/resolve/main/vocab.json",
|
33 |
+
"fnlp/moss-moon-003-sft-plugin": "https://huggingface.co/fnlp/moss-moon-003-sft-plugin/resolve/main/vocab.json",
|
34 |
+
"fnlp/moss-moon-003-sft-int8": "https://huggingface.co/fnlp/moss-moon-003-sft-int8/resolve/main/vocab.json",
|
35 |
+
"fnlp/moss-moon-003-sft-plugin-int8": "https://huggingface.co/fnlp/moss-moon-003-sft-plugin-int8/resolve/main/vocab.json",
|
36 |
+
"fnlp/moss-moon-003-sft-int4": "https://huggingface.co/fnlp/moss-moon-003-sft-int4/resolve/main/vocab.json",
|
37 |
+
"fnlp/moss-moon-003-sft-plugin-int4": "https://huggingface.co/fnlp/moss-moon-003-sft-plugin-int4/resolve/main/vocab.json",
|
38 |
+
},
|
39 |
+
"merges_file": {
|
40 |
+
"fnlp/moss-moon-003-base": "https://huggingface.co/fnlp/moss-moon-003-base/resolve/main/merges.txt",
|
41 |
+
"fnlp/moss-moon-003-sft": "https://huggingface.co/fnlp/moss-moon-003-sft/resolve/main/merges.txt",
|
42 |
+
"fnlp/moss-moon-003-sft-plugin": "https://huggingface.co/fnlp/moss-moon-003-sft-plugin/resolve/main/merges.txt",
|
43 |
+
"fnlp/moss-moon-003-sft-int8": "https://huggingface.co/fnlp/moss-moon-003-sft-int8/resolve/main/merges.txt",
|
44 |
+
"fnlp/moss-moon-003-sft-plugin-int8": "https://huggingface.co/fnlp/moss-moon-003-sft-plugin-int8/resolve/main/merges.txt",
|
45 |
+
"fnlp/moss-moon-003-sft-int4": "https://huggingface.co/fnlp/moss-moon-003-sft-int4/resolve/main/merges.txt",
|
46 |
+
"fnlp/moss-moon-003-sft-plugin-int4": "https://huggingface.co/fnlp/moss-moon-003-sft-plugin-int4/resolve/main/merges.txt",
|
47 |
+
},
|
48 |
+
}
|
49 |
+
|
50 |
+
PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES = {
|
51 |
+
"fnlp/moss-moon-003-base": 2048,
|
52 |
+
"fnlp/moss-moon-003-sft": 2048,
|
53 |
+
"fnlp/moss-moon-003-sft-plugin": 2048,
|
54 |
+
"fnlp/moss-moon-003-sft-int8": 2048,
|
55 |
+
"fnlp/moss-moon-003-sft-plugin-int8": 2048,
|
56 |
+
"fnlp/moss-moon-003-sft-int4": 2048,
|
57 |
+
"fnlp/moss-moon-003-sft-plugin-int4": 2048,
|
58 |
+
}
|
59 |
+
|
60 |
+
|
61 |
+
@lru_cache()
|
62 |
+
def bytes_to_unicode():
|
63 |
+
"""
|
64 |
+
Returns list of utf-8 byte and a mapping to unicode strings. We specifically avoids mapping to whitespace/control
|
65 |
+
characters the bpe code barfs on.
|
66 |
+
|
67 |
+
The reversible bpe codes work on unicode strings. This means you need a large # of unicode characters in your vocab
|
68 |
+
if you want to avoid UNKs. When you're at something like a 10B token dataset you end up needing around 5K for
|
69 |
+
decent coverage. This is a significant percentage of your normal, say, 32K bpe vocab. To avoid that, we want lookup
|
70 |
+
tables between utf-8 bytes and unicode strings.
|
71 |
+
"""
|
72 |
+
bs = (
|
73 |
+
list(range(ord("!"), ord("~") + 1)) + list(range(ord("¡"), ord("¬") + 1)) + list(range(ord("®"), ord("ÿ") + 1))
|
74 |
+
)
|
75 |
+
cs = bs[:]
|
76 |
+
n = 0
|
77 |
+
for b in range(2**8):
|
78 |
+
if b not in bs:
|
79 |
+
bs.append(b)
|
80 |
+
cs.append(2**8 + n)
|
81 |
+
n += 1
|
82 |
+
cs = [chr(n) for n in cs]
|
83 |
+
return dict(zip(bs, cs))
|
84 |
+
|
85 |
+
|
86 |
+
def get_pairs(word):
|
87 |
+
"""
|
88 |
+
Return set of symbol pairs in a word.
|
89 |
+
|
90 |
+
Word is represented as tuple of symbols (symbols being variable-length strings).
|
91 |
+
"""
|
92 |
+
pairs = set()
|
93 |
+
prev_char = word[0]
|
94 |
+
for char in word[1:]:
|
95 |
+
pairs.add((prev_char, char))
|
96 |
+
prev_char = char
|
97 |
+
return pairs
|
98 |
+
|
99 |
+
|
100 |
+
class MossTokenizer(PreTrainedTokenizer):
|
101 |
+
"""
|
102 |
+
Construct a Moss tokenizer. Based on byte-level Byte-Pair-Encoding.
|
103 |
+
|
104 |
+
This tokenizer has been trained to treat spaces like parts of the tokens (a bit like sentencepiece) so a word will
|
105 |
+
be encoded differently whether it is at the beginning of the sentence (without space) or not:
|
106 |
+
|
107 |
+
You can get around that behavior by passing `add_prefix_space=True` when instantiating this tokenizer or when you
|
108 |
+
call it on some text, but since the model was not pretrained this way, it might yield a decrease in performance.
|
109 |
+
|
110 |
+
<Tip>
|
111 |
+
|
112 |
+
When used with `is_split_into_words=True`, this tokenizer will add a space before each word (even the first one).
|
113 |
+
|
114 |
+
</Tip>
|
115 |
+
|
116 |
+
This tokenizer inherits from [`PreTrainedTokenizer`] which contains most of the main methods. Users should refer to
|
117 |
+
this superclass for more information regarding those methods.
|
118 |
+
|
119 |
+
Args:
|
120 |
+
vocab_file (`str`):
|
121 |
+
Path to the vocabulary file.
|
122 |
+
merges_file (`str`):
|
123 |
+
Path to the merges file.
|
124 |
+
errors (`str`, *optional*, defaults to `"replace"`):
|
125 |
+
Paradigm to follow when decoding bytes to UTF-8. See
|
126 |
+
[bytes.decode](https://docs.python.org/3/library/stdtypes.html#bytes.decode) for more information.
|
127 |
+
unk_token (`str`, *optional*, defaults to `<|endoftext|>`):
|
128 |
+
The unknown token. A token that is not in the vocabulary cannot be converted to an ID and is set to be this
|
129 |
+
token instead.
|
130 |
+
bos_token (`str`, *optional*, defaults to `<|endoftext|>`):
|
131 |
+
The beginning of sequence token.
|
132 |
+
eos_token (`str`, *optional*, defaults to `<|endoftext|>`):
|
133 |
+
The end of sequence token.
|
134 |
+
add_prefix_space (`bool`, *optional*, defaults to `False`):
|
135 |
+
Whether or not to add an initial space to the input. This allows to treat the leading word just as any
|
136 |
+
other word. (Moss tokenizer detect beginning of words by the preceding space).
|
137 |
+
"""
|
138 |
+
|
139 |
+
vocab_files_names = VOCAB_FILES_NAMES
|
140 |
+
pretrained_vocab_files_map = PRETRAINED_VOCAB_FILES_MAP
|
141 |
+
max_model_input_sizes = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
|
142 |
+
model_input_names = ["input_ids", "attention_mask"]
|
143 |
+
|
144 |
+
def __init__(
|
145 |
+
self,
|
146 |
+
vocab_file,
|
147 |
+
merges_file,
|
148 |
+
errors="replace",
|
149 |
+
unk_token="<|endoftext|>",
|
150 |
+
bos_token="<|endoftext|>",
|
151 |
+
eos_token="<eom>",
|
152 |
+
pad_token=None,
|
153 |
+
add_prefix_space=False,
|
154 |
+
add_bos_token=False,
|
155 |
+
**kwargs,
|
156 |
+
):
|
157 |
+
bos_token = AddedToken(bos_token, lstrip=False, rstrip=False) if isinstance(bos_token, str) else bos_token
|
158 |
+
eos_token = AddedToken(eos_token, lstrip=False, rstrip=False) if isinstance(eos_token, str) else eos_token
|
159 |
+
unk_token = AddedToken(unk_token, lstrip=False, rstrip=False) if isinstance(unk_token, str) else unk_token
|
160 |
+
pad_token = AddedToken(pad_token, lstrip=False, rstrip=False) if isinstance(pad_token, str) else pad_token
|
161 |
+
super().__init__(
|
162 |
+
errors=errors,
|
163 |
+
unk_token=unk_token,
|
164 |
+
bos_token=bos_token,
|
165 |
+
eos_token=eos_token,
|
166 |
+
pad_token=pad_token,
|
167 |
+
add_prefix_space=add_prefix_space,
|
168 |
+
add_bos_token=add_bos_token,
|
169 |
+
**kwargs,
|
170 |
+
)
|
171 |
+
self.add_bos_token = add_bos_token
|
172 |
+
|
173 |
+
with open(vocab_file, encoding="utf-8") as vocab_handle:
|
174 |
+
self.encoder = json.load(vocab_handle)
|
175 |
+
self.decoder = {v: k for k, v in self.encoder.items()}
|
176 |
+
self.errors = errors # how to handle errors in decoding
|
177 |
+
self.byte_encoder = bytes_to_unicode()
|
178 |
+
self.byte_decoder = {v: k for k, v in self.byte_encoder.items()}
|
179 |
+
with open(merges_file, encoding="utf-8") as merges_handle:
|
180 |
+
bpe_merges = merges_handle.read().split("\n")[1:-1]
|
181 |
+
bpe_merges = [tuple(merge.split()) for merge in bpe_merges]
|
182 |
+
self.bpe_ranks = dict(zip(bpe_merges, range(len(bpe_merges))))
|
183 |
+
self.cache = {}
|
184 |
+
self.add_prefix_space = add_prefix_space
|
185 |
+
|
186 |
+
# Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
|
187 |
+
self.pat = re.compile(r"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+""")
|
188 |
+
|
189 |
+
@property
|
190 |
+
def vocab_size(self):
|
191 |
+
return len(self.encoder)
|
192 |
+
|
193 |
+
def get_vocab(self):
|
194 |
+
return dict(self.encoder, **self.added_tokens_encoder)
|
195 |
+
|
196 |
+
def bpe(self, token):
|
197 |
+
if token in self.cache:
|
198 |
+
return self.cache[token]
|
199 |
+
word = tuple(token)
|
200 |
+
pairs = get_pairs(word)
|
201 |
+
|
202 |
+
if not pairs:
|
203 |
+
return token
|
204 |
+
|
205 |
+
while True:
|
206 |
+
bigram = min(pairs, key=lambda pair: self.bpe_ranks.get(pair, float("inf")))
|
207 |
+
if bigram not in self.bpe_ranks:
|
208 |
+
break
|
209 |
+
first, second = bigram
|
210 |
+
new_word = []
|
211 |
+
i = 0
|
212 |
+
while i < len(word):
|
213 |
+
try:
|
214 |
+
j = word.index(first, i)
|
215 |
+
except ValueError:
|
216 |
+
new_word.extend(word[i:])
|
217 |
+
break
|
218 |
+
else:
|
219 |
+
new_word.extend(word[i:j])
|
220 |
+
i = j
|
221 |
+
|
222 |
+
if word[i] == first and i < len(word) - 1 and word[i + 1] == second:
|
223 |
+
new_word.append(first + second)
|
224 |
+
i += 2
|
225 |
+
else:
|
226 |
+
new_word.append(word[i])
|
227 |
+
i += 1
|
228 |
+
new_word = tuple(new_word)
|
229 |
+
word = new_word
|
230 |
+
if len(word) == 1:
|
231 |
+
break
|
232 |
+
else:
|
233 |
+
pairs = get_pairs(word)
|
234 |
+
word = " ".join(word)
|
235 |
+
self.cache[token] = word
|
236 |
+
return word
|
237 |
+
|
238 |
+
def build_inputs_with_special_tokens(self, token_ids_0, token_ids_1=None):
|
239 |
+
if self.add_bos_token:
|
240 |
+
bos_token_ids = [self.bos_token_id]
|
241 |
+
else:
|
242 |
+
bos_token_ids = []
|
243 |
+
|
244 |
+
output = bos_token_ids + token_ids_0
|
245 |
+
|
246 |
+
if token_ids_1 is None:
|
247 |
+
return output
|
248 |
+
|
249 |
+
return output + bos_token_ids + token_ids_1
|
250 |
+
|
251 |
+
def _tokenize(self, text):
|
252 |
+
"""Tokenize a string."""
|
253 |
+
bpe_tokens = []
|
254 |
+
for token in re.findall(self.pat, text):
|
255 |
+
token = "".join(
|
256 |
+
self.byte_encoder[b] for b in token.encode("utf-8")
|
257 |
+
) # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
|
258 |
+
bpe_tokens.extend(bpe_token for bpe_token in self.bpe(token).split(" "))
|
259 |
+
return bpe_tokens
|
260 |
+
|
261 |
+
def _convert_token_to_id(self, token):
|
262 |
+
"""Converts a token (str) in an id using the vocab."""
|
263 |
+
return self.encoder.get(token, self.encoder.get(self.unk_token))
|
264 |
+
|
265 |
+
def _convert_id_to_token(self, index):
|
266 |
+
"""Converts an index (integer) in a token (str) using the vocab."""
|
267 |
+
return self.decoder.get(index)
|
268 |
+
|
269 |
+
def convert_tokens_to_string(self, tokens):
|
270 |
+
"""Converts a sequence of tokens (string) in a single string."""
|
271 |
+
text = "".join(tokens)
|
272 |
+
text = bytearray([self.byte_decoder[c] for c in text]).decode("utf-8", errors=self.errors)
|
273 |
+
return text
|
274 |
+
|
275 |
+
def save_vocabulary(self, save_directory: str, filename_prefix: Optional[str] = None) -> Tuple[str]:
|
276 |
+
if not os.path.isdir(save_directory):
|
277 |
+
logger.error(f"Vocabulary path ({save_directory}) should be a directory")
|
278 |
+
return
|
279 |
+
vocab_file = os.path.join(
|
280 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"]
|
281 |
+
)
|
282 |
+
merge_file = os.path.join(
|
283 |
+
save_directory, (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["merges_file"]
|
284 |
+
)
|
285 |
+
|
286 |
+
with open(vocab_file, "w", encoding="utf-8") as f:
|
287 |
+
f.write(json.dumps(self.encoder, indent=2, sort_keys=True, ensure_ascii=False) + "\n")
|
288 |
+
|
289 |
+
index = 0
|
290 |
+
with open(merge_file, "w", encoding="utf-8") as writer:
|
291 |
+
writer.write("#version: 0.2\n")
|
292 |
+
for bpe_tokens, token_index in sorted(self.bpe_ranks.items(), key=lambda kv: kv[1]):
|
293 |
+
if index != token_index:
|
294 |
+
logger.warning(
|
295 |
+
f"Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."
|
296 |
+
" Please check that the tokenizer is not corrupted!"
|
297 |
+
)
|
298 |
+
index = token_index
|
299 |
+
writer.write(" ".join(bpe_tokens) + "\n")
|
300 |
+
index += 1
|
301 |
+
|
302 |
+
return vocab_file, merge_file
|
303 |
+
|
304 |
+
def prepare_for_tokenization(self, text, is_split_into_words=False, **kwargs):
|
305 |
+
add_prefix_space = kwargs.pop("add_prefix_space", self.add_prefix_space)
|
306 |
+
if is_split_into_words or add_prefix_space:
|
307 |
+
text = " " + text
|
308 |
+
return (text, kwargs)
|
309 |
+
|
310 |
+
def decode(
|
311 |
+
self,
|
312 |
+
token_ids: Union[int, List[int], "np.ndarray", "torch.Tensor", "tf.Tensor"],
|
313 |
+
skip_special_tokens: bool = False,
|
314 |
+
clean_up_tokenization_spaces: bool = None,
|
315 |
+
truncate_before_pattern: Optional[List[str]] = None,
|
316 |
+
**kwargs,
|
317 |
+
) -> str:
|
318 |
+
"""
|
319 |
+
Converts a sequence of ids in a string, using the tokenizer and vocabulary with options to remove special
|
320 |
+
tokens and clean up tokenization spaces.
|
321 |
+
|
322 |
+
Similar to doing `self.convert_tokens_to_string(self.convert_ids_to_tokens(token_ids))`.
|
323 |
+
|
324 |
+
Args:
|
325 |
+
token_ids (`Union[int, List[int], np.ndarray, torch.Tensor, tf.Tensor]`):
|
326 |
+
List of tokenized input ids. Can be obtained using the `__call__` method.
|
327 |
+
skip_special_tokens (`bool`, *optional*, defaults to `False`):
|
328 |
+
Whether or not to remove special tokens in the decoding.
|
329 |
+
clean_up_tokenization_spaces (`bool`, *optional*):
|
330 |
+
Whether or not to clean up the tokenization spaces. If `None`, will default to
|
331 |
+
`self.clean_up_tokenization_spaces` (available in the `tokenizer_config`).
|
332 |
+
truncate_before_pattern (`List[str]`, *optional*, defaults to `None`):
|
333 |
+
A list of regular expression strings that will be used to truncate the returned string. This can be
|
334 |
+
used to remove extra pieces of code (e.g. truncate if observing a comment symbol "#" at the beginning
|
335 |
+
of a new line). An example pattern could be `["^#", re.escape("<|endoftext|>"), "^'''", "\n\n\n"]`.
|
336 |
+
kwargs (additional keyword arguments, *optional*):
|
337 |
+
Will be passed to the underlying model specific decode method.
|
338 |
+
|
339 |
+
Returns:
|
340 |
+
`str`: The decoded sentence.
|
341 |
+
"""
|
342 |
+
decoded_text = super()._decode(
|
343 |
+
token_ids=token_ids,
|
344 |
+
skip_special_tokens=skip_special_tokens,
|
345 |
+
clean_up_tokenization_spaces=clean_up_tokenization_spaces,
|
346 |
+
**kwargs,
|
347 |
+
)
|
348 |
+
|
349 |
+
if truncate_before_pattern is not None and len(truncate_before_pattern) > 0:
|
350 |
+
decoded_text = self.truncate(decoded_text, truncate_before_pattern)
|
351 |
+
|
352 |
+
return decoded_text
|
353 |
+
|
354 |
+
def truncate(self, completion, truncate_before_pattern):
|
355 |
+
def find_re(string, pattern, start_pos):
|
356 |
+
m = pattern.search(string, start_pos)
|
357 |
+
return m.start() if m else -1
|
358 |
+
|
359 |
+
terminals = [re.compile(pattern, re.MULTILINE) for pattern in truncate_before_pattern]
|
360 |
+
|
361 |
+
prints = list(re.finditer("^print", completion, re.MULTILINE))
|
362 |
+
|
363 |
+
if len(prints) > 1:
|
364 |
+
completion = completion[: prints[1].start()]
|
365 |
+
|
366 |
+
defs = list(re.finditer("^def", completion, re.MULTILINE))
|
367 |
+
|
368 |
+
if len(defs) > 1:
|
369 |
+
completion = completion[: defs[1].start()]
|
370 |
+
|
371 |
+
start_pos = 0
|
372 |
+
|
373 |
+
terminals_pos = [
|
374 |
+
pos for pos in [find_re(completion, terminal, start_pos) for terminal in terminals] if pos != -1
|
375 |
+
]
|
376 |
+
|
377 |
+
if len(terminals_pos) > 0:
|
378 |
+
return completion[: min(terminals_pos)]
|
379 |
+
else:
|
380 |
+
return completion
|