ajsbsd commited on
Commit
fd6e294
·
verified ·
1 Parent(s): 99133af

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -26
app.py CHANGED
@@ -2,7 +2,6 @@ import gradio as gr
2
  import torch
3
  import spaces
4
  import sys
5
- import re
6
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
7
  from threading import Thread
8
  import transformers.modeling_rope_utils as rope_utils
@@ -37,32 +36,55 @@ model = AutoModelForCausalLM.from_pretrained(
37
  attn_implementation="eager",
38
  )
39
 
40
- # 3. Patch the seq_len bug in fa3.py in memory
41
  def patch_fa3_module():
42
- try:
43
- fa3_path = hf_hub_download(repo_id=model_id, filename="fa3.py")
44
- with open(fa3_path, "r", encoding="utf-8") as f:
45
- fa3_source = f.read()
46
-
47
- # The model authors made a typo: query is (bsz, num_heads, q_len, head_dim)
48
- # so q_len is at index 2, not 1!
49
- if "seq_len = query.shape[1]" in fa3_source:
50
- fa3_source = fa3_source.replace("seq_len = query.shape[1]", "seq_len = query.shape[2]")
51
- print("Fixed seq_len bug in fa3 source string.")
52
- else:
53
- fa3_source = re.sub(r'seq_len\s*=\s*query\.shape\[1\]', 'seq_len = query.shape[2]', fa3_source)
54
- print("Attempted regex fix on fa3 source string.")
55
-
56
- # Inject the patched source code directly into the loaded module in sys.modules
57
- for name, module in list(sys.modules.items()):
58
- if 'fa3' in name and 'maple' in name:
59
- print(f"Injecting patched fa3 into {name}")
60
- if not hasattr(module, '__package__') or not module.__package__:
61
- module.__package__ = name.rsplit('.', 1)[0]
62
- exec(compile(fa3_source, fa3_path, 'exec'), vars(module))
63
- print("✅ Injection successful.")
64
- except Exception as e:
65
- print(f"Failed to patch fa3 module: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  patch_fa3_module()
68
 
 
2
  import torch
3
  import spaces
4
  import sys
 
5
  from transformers import AutoModelForCausalLM, AutoTokenizer, TextIteratorStreamer
6
  from threading import Thread
7
  import transformers.modeling_rope_utils as rope_utils
 
36
  attn_implementation="eager",
37
  )
38
 
39
+ # 3. Patch the cu_seq_lens mismatch bug in fa3.py in memory
40
  def patch_fa3_module():
41
+ for name, module in list(sys.modules.items()):
42
+ if 'fa3' in name and 'maple' in name:
43
+ if hasattr(module, '_flash_attention_forward'):
44
+ orig_fa_forward = module._flash_attention_forward
45
+
46
+ def patched_fa_forward(
47
+ query_states,
48
+ key_states,
49
+ value_states,
50
+ attention_mask,
51
+ query_length,
52
+ is_causal,
53
+ dropout=0.0,
54
+ position_ids=None,
55
+ softmax_scale=None,
56
+ sliding_window=None,
57
+ use_top_left_mask=False,
58
+ softcap=None,
59
+ deterministic=None,
60
+ cu_seq_lens_q=None,
61
+ cu_seq_lens_k=None,
62
+ max_length_q=None,
63
+ max_length_k=None,
64
+ target_dtype=None,
65
+ **kwargs,
66
+ ):
67
+ # FIX: Override cu_seq_lens to perfectly match the actual number of tokens in query_states
68
+ if cu_seq_lens_q is not None and query_states is not None:
69
+ # query_states shape at this point is (batch_size, num_heads, q_len, head_dim)
70
+ total_tokens = query_states.shape[0] * query_states.shape[2]
71
+
72
+ cu_seq_lens_q = torch.tensor([0, total_tokens], device=query_states.device, dtype=torch.int32)
73
+ cu_seq_lens_k = torch.tensor([0, total_tokens], device=key_states.device, dtype=torch.int32)
74
+ max_length_q = total_tokens
75
+ max_length_k = total_tokens
76
+
77
+ return orig_fa_forward(
78
+ query_states, key_states, value_states, attention_mask, query_length, is_causal,
79
+ dropout, position_ids, softmax_scale, sliding_window, use_top_left_mask, softcap,
80
+ deterministic, cu_seq_lens_q, cu_seq_lens_k, max_length_q, max_length_k, target_dtype, **kwargs
81
+ )
82
+
83
+ module._flash_attention_forward = patched_fa_forward
84
+ print("✅ Patched _flash_attention_forward to fix cu_seq_lens mismatch.")
85
+ return True
86
+ print("⚠️ Could not find fa3 module to patch.")
87
+ return False
88
 
89
  patch_fa3_module()
90