llama.py 16.4 KB
Newer Older
Tri Dao's avatar
Tri Dao committed
1
2
3
# Copyright (c) 2023, Tri Dao.

import json
4
5
import math
import os
Tri Dao's avatar
Tri Dao committed
6
7
import re
from collections import OrderedDict
8
9
from pathlib import Path
from typing import Union
Tri Dao's avatar
Tri Dao committed
10
11
12

import torch
import torch.nn.functional as F
13
from sentencepiece import SentencePieceProcessor
Tri Dao's avatar
Tri Dao committed
14
15
16
from transformers import GPT2Config, LlamaConfig


17
18
19
20
21
22
23
24
def remap_state_dict_meta_llama(
    state_dict: dict[str, torch.Tensor], config: GPT2Config
) -> dict[str, torch.Tensor]:
    """Convert the state_dict in Meta format to standard GPT format.

    This function modifies state_dict in place.
    """

Tri Dao's avatar
Tri Dao committed
25
    def key_mapping_layers(key):
Tri Dao's avatar
Tri Dao committed
26
27
        return f"transformer.{key}" if not key.startswith("output.") else key

Tri Dao's avatar
Tri Dao committed
28
    state_dict = OrderedDict((key_mapping_layers(k), v) for k, v in state_dict.items())
Kevin Hu's avatar
Kevin Hu committed
29

Tri Dao's avatar
Tri Dao committed
30
31
    # Word embedding
    def key_mapping_emb(key):
Tri Dao's avatar
Tri Dao committed
32
        return re.sub(
Kevin Hu's avatar
Kevin Hu committed
33
34
35
            r"^transformer.tok_embeddings.",
            "transformer.embeddings.word_embeddings.",
            key,
Tri Dao's avatar
Tri Dao committed
36
37
        )

Tri Dao's avatar
Tri Dao committed
38
    state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items())
Tri Dao's avatar
Tri Dao committed
39
    word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight")
Tri Dao's avatar
Tri Dao committed
40
    # It's possible that vocab_size is padded to be a multiple of 8, for example.
Tri Dao's avatar
Tri Dao committed
41
42
43
44
45
    pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1)
    vocab_size = (
        math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple
    )
    state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad(
Tri Dao's avatar
Tri Dao committed
46
47
        word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0])
    )
Tri Dao's avatar
Tri Dao committed
48
49
    if getattr(config, "tie_word_embeddings"):
        state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"]
Tri Dao's avatar
Tri Dao committed
50
    else:
Tri Dao's avatar
Tri Dao committed
51
        output_embeddings = state_dict.pop("output.weight")
Tri Dao's avatar
Tri Dao committed
52
53
        # Need to recompute vocab_size since LLaMa shards the word embeddings and output embeddings
        # differently.
Tri Dao's avatar
Tri Dao committed
54
55
56
57
        vocab_size = (
            math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple)
            * pad_vocab_size_multiple
        )
Tri Dao's avatar
Tri Dao committed
58
        # It's possible that vocab_size is padded to be a multiple of 8, for example.
Tri Dao's avatar
Tri Dao committed
59
        state_dict["lm_head.weight"] = F.pad(
Tri Dao's avatar
Tri Dao committed
60
61
62
63
64
            output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0])
        )

    # LayerNorm
    def key_mapping_ln(key):
Tri Dao's avatar
Tri Dao committed
65
66
        key = re.sub(r"^transformer.norm.", r"transformer.ln_f.", key)
        key = re.sub(
Kevin Hu's avatar
Kevin Hu committed
67
68
69
            r"^transformer.layers.(\d+).attention_norm.",
            r"transformer.layers.\1.norm1.",
            key,
Tri Dao's avatar
Tri Dao committed
70
71
        )
        key = re.sub(r"^transformer.layers.(\d+).ffn_norm.", r"transformer.layers.\1.norm2.", key)
Tri Dao's avatar
Tri Dao committed
72
        return key
Tri Dao's avatar
Tri Dao committed
73

Tri Dao's avatar
Tri Dao committed
74
75
76
77
    state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items())

    # MLP
    for l in range(config.n_layer):
Tri Dao's avatar
Tri Dao committed
78
79
        w1 = state_dict.pop(f"transformer.layers.{l}.feed_forward.w1.weight")
        w3 = state_dict.pop(f"transformer.layers.{l}.feed_forward.w3.weight")
Tri Dao's avatar
Tri Dao committed
80
        # Our ordering is different
Tri Dao's avatar
Tri Dao committed
81
82
        state_dict[f"transformer.layers.{l}.mlp.fc1.weight"] = torch.cat([w3, w1], dim=0)

Tri Dao's avatar
Tri Dao committed
83
    def key_mapping_mlp(key):
Tri Dao's avatar
Tri Dao committed
84
        return re.sub(
Kevin Hu's avatar
Kevin Hu committed
85
86
87
            r"^transformer.layers.(\d+).feed_forward.w2.",
            r"transformer.layers.\1.mlp.fc2.",
            key,
Tri Dao's avatar
Tri Dao committed
88
89
        )

Tri Dao's avatar
Tri Dao committed
90
91
92
93
    state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items())

    # Attention
    for l in range(config.n_layer):
Tri Dao's avatar
Tri Dao committed
94
95
96
97
        Wq = state_dict.pop(f"transformer.layers.{l}.attention.wq.weight")
        Wk = state_dict.pop(f"transformer.layers.{l}.attention.wk.weight")
        Wv = state_dict.pop(f"transformer.layers.{l}.attention.wv.weight")
        state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat([Wq, Wk, Wv], dim=0)
Tri Dao's avatar
Tri Dao committed
98
        # We don't store these
Tri Dao's avatar
Tri Dao committed
99
100
        state_dict.pop(f"transformer.layers.{l}.attention.inner_attention.rope.freqs", None)

Tri Dao's avatar
Tri Dao committed
101
    def key_mapping_attn(key):
Tri Dao's avatar
Tri Dao committed
102
103
104
105
106
107
        return re.sub(
            r"^transformer.layers.(\d+).attention.wo.",
            r"transformer.layers.\1.mixer.out_proj.",
            key,
        )

Tri Dao's avatar
Tri Dao committed
108
109
    state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items())

110
111
    state_dict.pop("transformer.rope.freqs", None)

Tri Dao's avatar
Tri Dao committed
112
113
114
    return state_dict


115
def remap_state_dict_hf_llama(
Kevin Hu's avatar
Kevin Hu committed
116
    state_dict: dict[str, torch.Tensor], config: GPT2Config, multi_query: bool = False
117
118
119
120
121
) -> dict[str, torch.Tensor]:
    """Convert the state_dict in Hugging Face format to standard GPT format.

    This function modifies state_dict in place.
    """
Kevin Hu's avatar
Kevin Hu committed
122

123
124
    # Embedding
    def key_mapping_emb(key):
Tri Dao's avatar
Tri Dao committed
125
        return re.sub(r"^model.embed_tokens.", "transformer.embeddings.word_embeddings.", key)
126
127

    state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items())
Tri Dao's avatar
Tri Dao committed
128
    word_embeddings = state_dict.pop("transformer.embeddings.word_embeddings.weight")
129
    # It's possible that vocab_size is padded to be a multiple of 8, for example.
Tri Dao's avatar
Tri Dao committed
130
131
132
133
134
    pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1)
    vocab_size = (
        math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple
    )
    state_dict["transformer.embeddings.word_embeddings.weight"] = F.pad(
135
136
137
138
        word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0])
    )

    # LM head
Tri Dao's avatar
Tri Dao committed
139
140
    if getattr(config, "tie_word_embeddings"):
        state_dict["lm_head.weight"] = state_dict["transformer.embeddings.word_embeddings.weight"]
141
    else:
Tri Dao's avatar
Tri Dao committed
142
        output_embeddings = state_dict.pop("lm_head.weight")
143
144
        # Need to recompute vocab_size since LLaMa shards the word embeddings and output embeddings
        # differently.
Tri Dao's avatar
Tri Dao committed
145
146
147
148
        vocab_size = (
            math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple)
            * pad_vocab_size_multiple
        )
149
        # It's possible that vocab_size is padded to be a multiple of 8, for example.
Tri Dao's avatar
Tri Dao committed
150
        state_dict["lm_head.weight"] = F.pad(
151
152
153
154
155
156
157
158
            output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0])
        )

    # MLP
    for l in range(config.n_layer):
        # Fusing weights this way based on difference in the following:
        # https://github.com/huggingface/transformers/blob/b42010bb1d3cbf262d27e0a328661885be46dfdb/src/transformers/models/llama/modeling_llama.py#L220
        # https://github.com/Dao-AILab/flash-attention/blob/c60851a8253257eb970e06a022c82517a8033e8c/flash_attn/modules/mlp.py#L115
Tri Dao's avatar
Tri Dao committed
159
160
161
        w1 = state_dict.pop(f"model.layers.{l}.mlp.gate_proj.weight")
        w3 = state_dict.pop(f"model.layers.{l}.mlp.up_proj.weight")
        state_dict[f"transformer.layers.{l}.mlp.fc1.weight"] = torch.cat([w3, w1], dim=0)
162
163

    def key_mapping_mlp(key):
Kevin Hu's avatar
Kevin Hu committed
164
165
166
167
168
        return re.sub(
            r"^model.layers.(\d+).mlp.down_proj.",
            r"transformer.layers.\1.mlp.fc2.",
            key,
        )
169
170
171
172
173

    state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items())

    # LayerNorm
    def key_mapping_ln(key):
Tri Dao's avatar
Tri Dao committed
174
175
        key = re.sub(r"^model.norm.", r"transformer.ln_f.", key)
        key = re.sub(
Kevin Hu's avatar
Kevin Hu committed
176
177
178
179
180
181
182
183
            r"^model.layers.(\d+).input_layernorm.",
            r"transformer.layers.\1.norm1.",
            key,
        )
        key = re.sub(
            r"^model.layers.(\d+).post_attention_layernorm.",
            r"transformer.layers.\1.norm2.",
            key,
Tri Dao's avatar
Tri Dao committed
184
        )
185
186
187
188
        return key

    state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items())

Kevin Hu's avatar
Kevin Hu committed
189
    def inv_permute(w, first_dim=None):
190
191
        # Inverse of permute implemented in:
        # https://github.com/huggingface/transformers/blob/b42010bb1d3cbf262d27e0a328661885be46dfdb/src/transformers/models/llama/convert_llama_weights_to_hf.py#L114
Tri Dao's avatar
Tri Dao committed
192
        return (
Kevin Hu's avatar
Kevin Hu committed
193
            w.reshape(first_dim or config.n_head, 2, -1, config.n_embd)
Tri Dao's avatar
Tri Dao committed
194
            .transpose(1, 2)
Kevin Hu's avatar
Kevin Hu committed
195
            .reshape(-1, config.n_embd)
Tri Dao's avatar
Tri Dao committed
196
        )
197
198
199

    # Attention
    for l in range(config.n_layer):
Tri Dao's avatar
Tri Dao committed
200
201
202
        Wq = state_dict.pop(f"model.layers.{l}.self_attn.q_proj.weight")
        Wk = state_dict.pop(f"model.layers.{l}.self_attn.k_proj.weight")
        Wv = state_dict.pop(f"model.layers.{l}.self_attn.v_proj.weight")
Kevin Hu's avatar
Kevin Hu committed
203

Tri Dao's avatar
Tri Dao committed
204
        state_dict[f"transformer.layers.{l}.mixer.Wqkv.weight"] = torch.cat(
Kevin Hu's avatar
Kevin Hu committed
205
206
            (inv_permute(Wq), inv_permute(Wk, getattr(config, "n_head_kv")), Wv),
            dim=0,
207
208
        )
        # We don't store these
Tri Dao's avatar
Tri Dao committed
209
        state_dict.pop(f"model.layers.{l}.self_attn.rotary_emb.inv_freq", None)
210
211

    def key_mapping_attn(key):
Tri Dao's avatar
Tri Dao committed
212
        return re.sub(
Kevin Hu's avatar
Kevin Hu committed
213
214
215
            r"^model.layers.(\d+).self_attn.o_proj.",
            r"transformer.layers.\1.mixer.out_proj.",
            key,
Tri Dao's avatar
Tri Dao committed
216
        )
217
218
219
220
221

    state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items())
    return state_dict


222
def inv_remap_state_dict_hf_llama(
Kevin Hu's avatar
Kevin Hu committed
223
    state_dict: dict[str, torch.Tensor], config: GPT2Config, multi_query: bool = False
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
) -> dict[str, torch.Tensor]:
    """Convert the state_dict in standard GPT format to Hugging Face format.

    This function is meant to be the inverse of remap_state_dict_hf_llama, up to a
    multiplier pad in the embedding and lm_head. That is if the original embedding
    isn't a multiple of pad_vocab_size_multiple, then
    inv_remap_state_dict_hf_llama(remap_state_dict_hf_llama(state_dict)) != state_dict.

    This function modifies state_dict in place.
    """

    # Embedding
    def key_mapping_emb(key):
        return re.sub(r"^transformer.embeddings.word_embeddings.", "model.embed_tokens.", key)

    state_dict = OrderedDict((key_mapping_emb(k), v) for k, v in state_dict.items())
    word_embeddings = state_dict.pop("model.embed_tokens.weight")
    pad_vocab_size_multiple = getattr(config, "pad_vocab_size_multiple", 1)
    vocab_size = (
        math.ceil(word_embeddings.shape[0] / pad_vocab_size_multiple) * pad_vocab_size_multiple
    )
    state_dict["model.embed_tokens.weight"] = F.pad(
        word_embeddings, (0, 0, 0, vocab_size - word_embeddings.shape[0])
    )

    # LM head
    if getattr(config, "tie_word_embeddings"):
        state_dict["lm_head.weight"] = state_dict["model.embed_tokens.weight"]
    else:
        output_embeddings = state_dict.pop("lm_head.weight")
        vocab_size = (
            math.ceil(output_embeddings.shape[0] / pad_vocab_size_multiple)
            * pad_vocab_size_multiple
        )
        state_dict["lm_head.weight"] = F.pad(
            output_embeddings, (0, 0, 0, vocab_size - output_embeddings.shape[0])
        )

    # MLP
    for l in range(config.n_layer):
        w3, w1 = torch.chunk(
            state_dict.pop(f"transformer.layers.{l}.mlp.fc1.weight"), chunks=2, dim=0
        )
        state_dict[f"model.layers.{l}.mlp.gate_proj.weight"] = w1
        state_dict[f"model.layers.{l}.mlp.up_proj.weight"] = w3

    def key_mapping_mlp(key):
Kevin Hu's avatar
Kevin Hu committed
271
272
273
274
275
        return re.sub(
            r"^transformer.layers.(\d+).mlp.fc2.",
            r"model.layers.\1.mlp.down_proj.",
            key,
        )
276
277
278
279
280
281
282

    state_dict = OrderedDict((key_mapping_mlp(k), v) for k, v in state_dict.items())

    # LayerNorm
    def key_mapping_ln(key):
        key = re.sub(r"^transformer.ln_f.", r"model.norm.", key)
        key = re.sub(
Kevin Hu's avatar
Kevin Hu committed
283
284
285
286
287
288
289
290
            r"^transformer.layers.(\d+).norm1.",
            r"model.layers.\1.input_layernorm.",
            key,
        )
        key = re.sub(
            r"^transformer.layers.(\d+).norm2.",
            r"model.layers.\1.post_attention_layernorm.",
            key,
291
292
293
294
295
        )
        return key

    state_dict = OrderedDict((key_mapping_ln(k), v) for k, v in state_dict.items())

Kevin Hu's avatar
Kevin Hu committed
296
    def permute(w, first_dim=None):
297
        return (
Kevin Hu's avatar
Kevin Hu committed
298
            w.view(first_dim or config.n_head, -1, 2, config.n_embd)
299
            .transpose(1, 2)
Kevin Hu's avatar
Kevin Hu committed
300
            .reshape(-1, config.n_embd)
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
        )

    n_head = config.n_head
    n_head_kv = getattr(config, "n_head_kv", n_head)

    embed_dim = config.hidden_size
    head_dim = embed_dim // n_head

    q_dim = n_head * head_dim
    k_dim = v_dim = n_head_kv * head_dim

    # Attention
    for l in range(config.n_layer):
        Wqkv = state_dict.pop(f"transformer.layers.{l}.mixer.Wqkv.weight")
        Wq = Wqkv[:q_dim]
        Wk = Wqkv[q_dim : q_dim + k_dim]
        Wv = Wqkv[q_dim + k_dim : q_dim + k_dim + v_dim]
        state_dict[f"model.layers.{l}.self_attn.q_proj.weight"] = permute(Wq)
Kevin Hu's avatar
Kevin Hu committed
319
        state_dict[f"model.layers.{l}.self_attn.k_proj.weight"] = permute(Wk, n_head_kv)
320
321
322
323
324
        state_dict[f"model.layers.{l}.self_attn.v_proj.weight"] = Wv
        state_dict.pop(f"transformer.layers.{l}.attention.inner_attention.rope.freqs", None)

    def key_mapping_attn(key):
        return re.sub(
Kevin Hu's avatar
Kevin Hu committed
325
326
327
            r"^transformer.layers.(\d+).mixer.out_proj.",
            r"model.layers.\1.self_attn.o_proj.",
            key,
328
329
330
331
332
333
        )

    state_dict = OrderedDict((key_mapping_attn(k), v) for k, v in state_dict.items())
    return state_dict


Tri Dao's avatar
Tri Dao committed
334
335
336
def config_from_meta_checkpoint(
    checkpoint_path: Union[str, os.PathLike], model_name: str
) -> LlamaConfig:
Tri Dao's avatar
Tri Dao committed
337
    """Load a LlamaConfig from a checkpoint path."""
Tri Dao's avatar
Tri Dao committed
338
    with open(Path(checkpoint_path) / model_name / "params.json") as f:
Tri Dao's avatar
Tri Dao committed
339
        params = json.load(f)
Tri Dao's avatar
Tri Dao committed
340
341
342
343
344
345
    config = LlamaConfig(
        hidden_size=params["dim"],
        intermediate_size=None,
        num_attention_heads=params["n_heads"],
        num_hidden_layers=params["n_layers"],
        rms_norm_eps=params["norm_eps"],
346
        num_key_value_heads=params.get("n_kv_heads", None),
Tri Dao's avatar
Tri Dao committed
347
    )
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
    multiple_of = params.get("multiple_of", 1)
    ffn_dim_multiplier = params.get("ffn_dim_multiplier", None)

    # Compute the hidden dimension of the MLP
    # https://github.com/facebookresearch/llama/blob/1a240688810f8036049e8da36b073f63d2ac552c/llama/model.py#L224
    intermediate_size = 4 * config.hidden_size
    # https://github.com/facebookresearch/llama/blob/1a240688810f8036049e8da36b073f63d2ac552c/llama/model.py#L195-L199
    intermediate_size = int(2 * intermediate_size / 3)
    # custom dim factor multiplier
    if ffn_dim_multiplier is not None:
        intermediate_size = int(ffn_dim_multiplier * intermediate_size)
    intermediate_size = multiple_of * ((intermediate_size + multiple_of - 1) // multiple_of)

    config.intermediate_size = intermediate_size
    if "rope_theta" in params:
        config.rotary_emb_base = params["rope_theta"]
    config.vocab_size = 32000
    # some CodeLLaMa have vocab_size 32000, some 32016
    # Sadly it's not specified in the `params.json` file :(
    tokenizer = Path(checkpoint_path) / model_name / "tokenizer.model"
    if tokenizer.is_file():
        config.vocab_size = SentencePieceProcessor(str(tokenizer)).vocab_size()
Tri Dao's avatar
Tri Dao committed
370
371
372
    return config


Tri Dao's avatar
Tri Dao committed
373
374
375
376
def config_from_hf_checkpoint(
    checkpoint_path: Union[str, os.PathLike], model_name: str
) -> LlamaConfig:
    return LlamaConfig.from_pretrained(Path(checkpoint_path) / f"{model_name}-hf" / "config.json")
377
378
379
380
381
382
383
384
385
386
387


def config_from_checkpoint(
    checkpoint_path: Union[str, os.PathLike], model_name: str, checkpoint_format="meta"
) -> LlamaConfig:
    if checkpoint_format == "meta":
        return config_from_meta_checkpoint(checkpoint_path, model_name)
    else:
        return config_from_hf_checkpoint(checkpoint_path, model_name)


Tri Dao's avatar
Tri Dao committed
388
389
390
def state_dicts_from_checkpoint(
    checkpoint_path: Union[str, os.PathLike], model_name: str
) -> list[dict]:
Tri Dao's avatar
Tri Dao committed
391
    # Need to sort, otherwise we mess up the ordering and the weights are wrong
Tri Dao's avatar
Tri Dao committed
392
393
394
395
    return [
        torch.load(path, map_location="cpu")
        for path in sorted((Path(checkpoint_path) / model_name).glob("consolidated.*.pth"))
    ]
Tri Dao's avatar
Tri Dao committed
396
397
398
399
400
401
402
403
404
405


def llama_config_to_gpt2_config(llama_config: LlamaConfig) -> GPT2Config:
    return GPT2Config(
        vocab_size=llama_config.vocab_size,
        n_positions=0,  # No absolute position embedding
        n_embd=llama_config.hidden_size,
        n_layer=llama_config.num_hidden_layers,
        n_head=llama_config.num_attention_heads,
        n_inner=llama_config.intermediate_size,
Tri Dao's avatar
Tri Dao committed
406
        activation_function="swiglu",  # Hardcode since HF calls it 'silu'
Tri Dao's avatar
Tri Dao committed
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
        # Llama doesn't have dropout, idk if it's because they only release the inference code
        resid_pdrop=0.0,
        embd_pdrop=0.0,
        attn_pdrop=0.0,
        layer_norm_epsilon=llama_config.rms_norm_eps,
        initializer_range=llama_config.initializer_range,
        bos_token_id=llama_config.bos_token_id,
        eos_token_id=llama_config.eos_token_id,
        # These are new arguments not in the original GPT2Config
        pad_token_id=llama_config.pad_token_id,  # Idk if this does anything
        rms_norm=True,
        rotary_emb_fraction=1.0,
        rotary_emb_interleaved=True,
        tie_word_embeddings=False,
        qkv_proj_bias=False,
        out_proj_bias=False,
        mlp_fc1_bias=False,
        mlp_fc2_bias=False,
425
426
        rotary_emb_base=getattr(llama_config, "rotary_emb_base", 10000.0),
        n_head_kv=llama_config.num_key_value_heads,
Tri Dao's avatar
Tri Dao committed
427
    )