Views
No views yet
pip install safetensors==0.6.0.dev01import os, torch
2from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
3from accelerate import init_empty_weights
4from huggingface_hub import snapshot_download
5from os.path import join as pjoin
6from safetensors import safe_open
7
8@torch.compile(fullgraph=True)
9def matmul_fp4(x, W_q, scales, group_size, fp4_values):
10 def unpack_over_cols(W_q_packed, W_nbits, num_output_cols, dtype):
11 n_rows, n_cols = W_q_packed.shape
12 device = W_q_packed.device
13 shifts = torch.arange(num_output_cols // n_cols, device=device, dtype=W_q_packed.dtype) * W_nbits
14 W_q_unpacked = ((W_q_packed.unsqueeze(-1) >> shifts) & ((1 << W_nbits) - 1)).to(dtype)
15 W_q_unpacked = W_q_unpacked.view(n_rows, num_output_cols)
16 return W_q_unpacked
17
18 N, K = W_q.shape[0], W_q.shape[1] * 2
19 W_q = fp4_values[unpack_over_cols(W_q, W_nbits=4, num_output_cols=K, dtype=torch.int32)]
20 W_r = (W_q.float().view([-1, group_size]) * scales.float()).reshape([N, K]).to(x.dtype).T
21 return torch.matmul(x, W_r)
22
23class AutoModelForCausalLMFP4:
24
25 @classmethod
26 def from_pretrained(
27 cls,
28 save_dir_or_hub,
29 torch_dtype=torch.bfloat16,
30 cache_dir=None,
31 device_map="cuda:0",
32 *args,
33 **kwargs
34 ):
35
36 #Download snapshot
37 if os.path.exists(save_dir_or_hub):
38 save_dir = save_dir_or_hub
39 else:
40 save_dir = snapshot_download(repo_id=save_dir_or_hub, cache_dir=cache_dir)
41
42 #Create model from config
43 config = AutoConfig.from_pretrained(pjoin(save_dir, "config.json"))
44 config.torch_dtype = str(torch_dtype).split('.')[-1]
45 with init_empty_weights():
46 model = AutoModelForCausalLM.from_config(config)
47
48 #Load and patch
49 state_dict = {}
50 with safe_open(pjoin(save_dir, "model.safetensors"), framework="pt", device="cpu") as f:
51 for key in f.keys():
52 tensor = f.get_tensor(key)
53 dtype = torch_dtype if tensor.is_floating_point() else tensor.dtype
54 state_dict[key] = tensor.to(device=device_map, dtype=dtype, non_blocking=True)
55
56 cls.patch_model_for_fp4_inference(model=model, torch_dtype=torch_dtype, device=device_map, state_dict=state_dict)
57
58 return model
59
60 @classmethod
61 def patch_model_for_fp4_inference(cls, model, torch_dtype, device, state_dict):
62
63 model.fp4_values = torch.tensor(
64 [0, 0.5, 1, 1.5, 2, 3, 4, 6, -0, -0.5, -1, -1.5, -2, -3, -4, -6],
65 dtype=torch_dtype,
66 device=device,
67 )
68
69 def patch_linearlayers(model, fct):
70 for name, layer in model.named_children():
71 if isinstance(layer, torch.nn.Linear):
72 setattr(model, name, fct(layer, name))
73 else:
74 patch_linearlayers(layer, fct)
75
76 def patch_enable_fp4(layer, arg):
77 #Load params
78 if('lm_head' in layer.name):
79 return layer
80
81 if(hasattr(layer, 'weight')):
82 del layer.weight
83 for key in ['W_q', 'scales', 'shift', 'post_scale', 'meta']:
84 param_tag, param = layer.name + '.' + key, None
85 if(param_tag in state_dict):
86 param = state_dict[param_tag].tolist() if key in ["meta"] else state_dict[param_tag]
87 setattr(layer, key, param)
88
89 #Set forward pass
90 def forward(self, x):
91 if(hasattr(self, 'weight')):
92 out = torch.matmul(x, self.weight.data.T)
93 else:
94 out = matmul_fp4(x, self.W_q, self.scales, self.meta[-1], model.fp4_values)
95 if(self.post_scale is not None):
96 out *= self.post_scale
97 if(self.shift is not None):
98 out += self.shift
99 if(self.bias is not None):
100 out += self.bias
101 return out
102
103 layer.forward = lambda x: forward(layer, x)
104
105 return layer
106
107 try: #FP4 params will fail here
108 model.load_state_dict(state_dict, assign=True)
109 except:
110 pass
111
112 for name, module in model.named_modules():
113 module.name = name
114 patch_linearlayers(model, patch_enable_fp4)
115 model = model.to(device)1model_id = "mobiuslabsgmbh/Llama-3.1-8B-Instruct_nvfp4_weights_calib_demo"
2model = AutoModelForCausalLMFP4.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map='cuda')
3tokenizer = AutoTokenizer.from_pretrained(model_id)
4
5# Check the trained params
6# print( model.model.layers[-1].self_attn.v_proj.shift)
7# tensor([ 0.0082, 0.0002, 0.0058, ..., -0.0076, -0.0044, -0.0065],
8# device='cuda:0', dtype=torch.bfloat16, requires_grad=True)
9
10# print( model.model.layers[-1].self_attn.v_proj.post_scale)
11# tensor([1., 1., 1., ..., 1., 1., 1.], device='cuda:0', dtype=torch.bfloat16)
12
13outputs = model.generate(
14 tokenizer.apply_chat_template(
15 [{"role": "user", "content": "Solve the following equation: x^2 + 1 = -1"}],
16 tokenize=True,
17 add_generation_prompt=True,
18 return_tensors="pt",
19 ).to(model.device),
20 max_new_tokens=256,
21)
22print(tokenizer.decode(outputs[0]))