Views
No views yet
<|eot_id|>
<|start_header_id|>
<|end_header_id|>embed and lm_head to be the mean of all other tokens.1import argparse
2
3import transformers
4import torch
5
6
7def init_eot_embedding_llama3(model_path, output_dir, special_tokens=["<|eot_id|>", "<|start_header_id|>", "<|end_header_id|>"], mean_cutoff=128000, dtype=torch.bfloat16):
8 tokenizer = transformers.AutoTokenizer.from_pretrained(model_path)
9 model = transformers.AutoModelForCausalLM.from_pretrained(model_path, low_cpu_mem_usage=True, torch_dtype=dtype)
10
11 assert model.model.embed_tokens.weight.shape[0] >= mean_cutoff
12 assert model.lm_head.weight.shape[0] >= mean_cutoff
13
14 with torch.no_grad():
15 for token in special_tokens:
16 token_id = tokenizer.convert_tokens_to_ids(token)
17
18 print (f"Token {token} ID {token_id}")
19
20 model.model.embed_tokens.weight[token_id] = torch.mean(model.model.embed_tokens.weight[:mean_cutoff].to(torch.float32), dim=0).to(dtype)
21 model.lm_head.weight[token_id] = torch.mean(model.lm_head.weight[:mean_cutoff].to(torch.float32), dim=0).to(dtype)
22
23 # Save
24 tokenizer.save_pretrained(output_dir)
25 model.save_pretrained(output_dir)
26
27
28def main():
29 parser = argparse.ArgumentParser()
30 parser.add_argument(
31 "--model-path",
32 help="Location of model, or HuggingFace repo ID",
33 )
34 parser.add_argument(
35 "--output-dir",
36 help="Location to write resulting model and tokenizer",
37 )
38
39 init_eot_embedding_llama3(**vars(parser.parse_args()))
40
41
42if __name__ == "__main__":
43 main()
44