MCPcopy Create free account
hub / github.com/OpenBitSys/BitDistiller / make_quant_attn

Function make_quant_attn

inference/modules/fused_attn.py:304–370  ·  view source on GitHub ↗

Replace all LlamaAttention modules with QuantLlamaAttention modules, fusing the q, k, v projections.

(model, dev)

Source from the content-addressed store, hash-verified

302
303
304def make_quant_attn(model, dev):
305 """
306 Replace all LlamaAttention modules with QuantLlamaAttention modules, fusing the q, k, v projections.
307 """
308 model = model.cpu()
309 for name, m in model.named_modules():
310 if not m.__class__.__name__ in ["LlamaAttention", "LlamaAttentionFused"]:
311 continue
312
313 q_proj = m.q_proj
314 k_proj = m.k_proj
315 v_proj = m.v_proj
316
317 qweights = torch.cat([q_proj.qweight, k_proj.qweight, v_proj.qweight], dim=0)
318 qzeros = torch.cat([q_proj.qzeros, k_proj.qzeros, v_proj.qzeros], dim=0)
319 scales = torch.cat([q_proj.scales, k_proj.scales, v_proj.scales], dim=0)
320 # g_idx = torch.cat([q_proj.g_idx, k_proj.g_idx, v_proj.g_idx], dim=0)
321 g_idx = None
322 bias = (
323 torch.cat([q_proj.bias, k_proj.bias, v_proj.bias], dim=0)
324 if q_proj.bias is not None
325 else None
326 )
327
328 qkv_layer = WQLinear(
329 q_proj.w_bit,
330 q_proj.group_size,
331 q_proj.in_features,
332 q_proj.out_features + k_proj.out_features + v_proj.out_features,
333 q_proj.bias is not None,
334 q_proj.qweight.device,
335 )
336 qkv_layer.qweight = qweights
337 qkv_layer.qzeros = qzeros
338 qkv_layer.scales = scales
339
340 qkv_layer.bias = bias
341 qkv_layer.split_k_iters = q_proj.split_k_iters
342 # We're dropping the rotary embedding layer m.rotary_emb here. We don't need it in the triton branch.
343
344 if isinstance(m, LlamaAttention):
345 attn = QuantLlamaAttention(
346 m.hidden_size, m.num_heads, qkv_layer, m.o_proj, dev
347 )
348 else:
349 attn = QuantLlamaAttentionFused(
350 m.args.hidden_size,
351 m.args.num_attention_heads,
352 qkv_layer,
353 m.o_proj,
354 dev,
355 m.args,
356 )
357 if "." in name:
358 parent_name = name.rsplit(".", 1)[0]
359 child_name = name[len(parent_name) + 1 :]
360 parent = model.get_submodule(parent_name)
361 else:

Callers

nothing calls this directly

Calls 3

WQLinearClass · 0.90
QuantLlamaAttentionClass · 0.85

Tested by

no test coverage detected