|
| 1 | +import sys |
| 2 | + |
| 3 | +with open("src/maxtext/layers/attention_mla.py", "r") as f: |
| 4 | + code = f.read() |
| 5 | + |
| 6 | +target1 = """ # Aggregate head-wise logits: logits @ weights |
| 7 | + # [b, t, h, d] @ [b, s, d] -> [b, t, s, h] |
| 8 | + logits = jnp.einsum("bthd, bsd -> btsh", q, k, precision=self.config.matmul_precision) |
| 9 | + logits = jax.nn.relu(logits) |
| 10 | + # [b, t, s, h] @ [b, t, h] -> [b, t, s] |
| 11 | + indexer_score = jnp.einsum("btsh, bth -> bts", logits, weights, precision=self.config.matmul_precision)""" |
| 12 | + |
| 13 | +replace1 = """ # Compute Index Scores safely by chunking the 'heads' dimension to prevent OOM |
| 14 | + # The naive evaluation materializes [b, t, s, h] which explodes HBM. |
| 15 | + # We use jax.lax.scan to compute the score iteratively over head chunks. |
| 16 | + b, t, h, d = q.shape |
| 17 | + # Control the HBM footprint of QK tensor: [batch, q_len, s_len, heads] or [batch, heads, q_len, s_len] |
| 18 | + # If set to 0, it falls back to native materialization. |
| 19 | + head_chunk_size = getattr(self.config, "qk_head_chunk_size", 0) |
| 20 | + if head_chunk_size > 0: |
| 21 | + if head_chunk_size > h or h % head_chunk_size != 0: |
| 22 | + raise ValueError( |
| 23 | + f"qk_head_chunk_size ({head_chunk_size}) must be <= number of heads ({h}) " |
| 24 | + f"and divide it evenly." |
| 25 | + ) |
| 26 | + num_chunks = h // head_chunk_size |
| 27 | + # q: [b, t, h, d] -> [h, b, t, d] -> [num_chunks, head_chunk_size, b, t, d] |
| 28 | + q_h = q.transpose(2, 0, 1, 3).reshape(num_chunks, head_chunk_size, b, t, d) |
| 29 | + # weights: [b, t, h] -> [h, b, t] -> [num_chunks, head_chunk_size, b, t] |
| 30 | + w_h = weights.transpose(2, 0, 1).reshape(num_chunks, head_chunk_size, b, t) |
| 31 | +
|
| 32 | + def scan_body_indexer(carry, xs): |
| 33 | + q_c = xs["q"] # [h_chunk, b, t, d] |
| 34 | + w_c = xs["w"] # [h_chunk, b, t] |
| 35 | +
|
| 36 | + # Transpose back for einsum: |
| 37 | + q_c = q_c.transpose(1, 2, 0, 3) # [b, t, h_chunk, d] |
| 38 | + w_c = w_c.transpose(1, 2, 0) # [b, t, h_chunk] |
| 39 | +
|
| 40 | + logits = jnp.einsum("bthd, bsd -> btsh", q_c, k, precision=self.config.matmul_precision) |
| 41 | + logits = jax.nn.relu(logits) |
| 42 | +
|
| 43 | + # Upcast the chunk to fp32 directly inside the block so we precisely match MXU |
| 44 | + # accumulator numerical stability without bfloat16 degradation over the loop boundary |
| 45 | + score_chunk = jnp.einsum( |
| 46 | + "btsh, bth -> bts", |
| 47 | + logits, |
| 48 | + w_c, |
| 49 | + precision=self.config.matmul_precision, |
| 50 | + ) |
| 51 | + return carry + score_chunk.astype(jnp.float32), None |
| 52 | +
|
| 53 | + init_score = jnp.zeros((b, t, k.shape[1]), dtype=jnp.float32) |
| 54 | + indexer_score, _ = jax.lax.scan(jax.checkpoint(scan_body_indexer), init_score, {"q": q_h, "w": w_h}) |
| 55 | + indexer_score = indexer_score.astype(q.dtype) |
| 56 | +
|
| 57 | + else: |
| 58 | + # Aggregate head-wise logits: logits @ weights natively |
| 59 | + logits = jnp.einsum("bthd, bsd -> btsh", q, k, precision=self.config.matmul_precision) |
| 60 | + logits = jax.nn.relu(logits) |
| 61 | + indexer_score = jnp.einsum("btsh, bth -> bts", logits, weights, precision=self.config.matmul_precision)""" |
| 62 | + |
| 63 | +target2 = """ # Compute attention scores: [b, t, h, d] @ [b, s, h, d] -> [b, h, t, s] |
| 64 | + attention_scores = jnp.einsum("bthd, bshd -> bhts", query, key, precision=self.config.matmul_precision) |
| 65 | +
|
| 66 | + if sparse_loss: |
| 67 | + # indexer_mask is already pre-filtered with the attention_mask if any |
| 68 | + attention_scores = attention_scores + indexer_mask[:, None, :, :] |
| 69 | + indexer_score = indexer_score + indexer_mask |
| 70 | + elif attention_mask is not None: |
| 71 | + # indexer_score already applies attention_mask; updating attention_scores only |
| 72 | + attention_scores = attention_scores + attention_mask[:, None, :, :] |
| 73 | +
|
| 74 | + # Use float32 for softmax numerical stability. |
| 75 | + attention_probs = jax.nn.softmax(attention_scores.astype(jnp.float32), axis=-1) |
| 76 | + indexer_probs = jax.nn.softmax(indexer_score.astype(jnp.float32), axis=-1) |
| 77 | +
|
| 78 | + # Aggregate heads: [b, h, t, s] -> [b, t, s] |
| 79 | + attention_probs = jnp.sum(attention_probs, axis=1) |
| 80 | + # Force materialization and prevent fusion across this point to reuse the intermediate tensor |
| 81 | + attention_probs = jax.lax.optimization_barrier(attention_probs)""" |
| 82 | + |
| 83 | +replace2 = """ # Ensure indexer_score updates identically in all branches |
| 84 | + if sparse_loss: |
| 85 | + indexer_score = indexer_score + indexer_mask |
| 86 | + indexer_probs = jax.nn.softmax(indexer_score.astype(jnp.float32), axis=-1) |
| 87 | +
|
| 88 | + batch, q_len, heads, dim = query.shape |
| 89 | +
|
| 90 | + # Chunk across the 'heads' dimension manually using jax.lax.scan |
| 91 | + # Control the HBM footprint of QK tensor: [batch, q_len, s_len, heads] |
| 92 | + # If set to 0, it falls back to native implementation. |
| 93 | + head_chunk_size = getattr(self.config, "qk_head_chunk_size", 0) |
| 94 | + if head_chunk_size > 0: |
| 95 | + if head_chunk_size > heads or heads % head_chunk_size != 0: |
| 96 | + raise ValueError( |
| 97 | + f"qk_head_chunk_size ({head_chunk_size}) must be <= number of heads ({heads}) " |
| 98 | + f"and divide it evenly." |
| 99 | + ) |
| 100 | + num_chunks = heads // head_chunk_size |
| 101 | +
|
| 102 | + # Transpose and reshape to put chunk dimension first for jax.lax.scan |
| 103 | + # query: [b, t, h, d] -> [h, b, t, d] -> [num_chunks, head_chunk_size, b, t, d] |
| 104 | + q_h = query.transpose(2, 0, 1, 3).reshape(num_chunks, head_chunk_size, batch, q_len, dim) |
| 105 | + k_h = key.transpose(2, 0, 1, 3).reshape(num_chunks, head_chunk_size, batch, key.shape[1], dim) |
| 106 | +
|
| 107 | + def scan_body_heads(carry, xs): |
| 108 | + q_c = xs["q"] # [h_chunk, b, t, d] |
| 109 | + k_c = xs["k"] # [h_chunk, b, s, d] |
| 110 | +
|
| 111 | + # Transpose back: [h_chunk, b, t, d] -> [b, t, h_chunk, d] |
| 112 | + q_c = q_c.transpose(1, 2, 0, 3) |
| 113 | + k_c = k_c.transpose(1, 2, 0, 3) |
| 114 | +
|
| 115 | + attn_chunk = jnp.einsum( |
| 116 | + "bthd, bshd -> bhts", |
| 117 | + q_c, |
| 118 | + k_c, |
| 119 | + precision=self.config.matmul_precision, |
| 120 | + ) |
| 121 | +
|
| 122 | + if sparse_loss: |
| 123 | + attn_chunk = attn_chunk + indexer_mask[:, None, :, :] |
| 124 | + elif attention_mask is not None: |
| 125 | + attn_chunk = attn_chunk + attention_mask[:, None, :, :] |
| 126 | +
|
| 127 | + probs_chunk = jax.nn.softmax(attn_chunk.astype(jnp.float32), axis=-1) |
| 128 | + probs_chunk_sum = jnp.sum(probs_chunk, axis=1) # [b, t, s] |
| 129 | +
|
| 130 | + return carry + probs_chunk_sum, None |
| 131 | +
|
| 132 | + init_probs = jnp.zeros((batch, q_len, key.shape[1]), dtype=jnp.float32) |
| 133 | + attention_probs, _ = jax.lax.scan(jax.checkpoint(scan_body_heads), init_probs, {"q": q_h, "k": k_h}) |
| 134 | +
|
| 135 | + else: |
| 136 | + # Natively evaluate if chunking is disabled or head sizing does not allow clean chunks |
| 137 | + attention_scores = jnp.einsum( |
| 138 | + "bthd, bshd -> bhts", |
| 139 | + query, |
| 140 | + key, |
| 141 | + precision=self.config.matmul_precision, |
| 142 | + ) |
| 143 | + if sparse_loss: |
| 144 | + attention_scores = attention_scores + indexer_mask[:, None, :, :] |
| 145 | + elif attention_mask is not None: |
| 146 | + attention_scores = attention_scores + attention_mask[:, None, :, :] |
| 147 | + attention_probs = jnp.sum(jax.nn.softmax(attention_scores.astype(jnp.float32), axis=-1), axis=1) |
| 148 | + attention_probs = jax.lax.optimization_barrier(attention_probs)""" |
| 149 | + |
| 150 | +if target1 not in code: |
| 151 | + print("Could not find target1") |
| 152 | + sys.exit(1) |
| 153 | +if target2 not in code: |
| 154 | + print("Could not find target2") |
| 155 | + sys.exit(1) |
| 156 | + |
| 157 | +code = code.replace(target1, replace1) |
| 158 | +code = code.replace(target2, replace2) |
| 159 | + |
| 160 | +with open("src/maxtext/layers/attention_mla.py", "w") as f: |
| 161 | + f.write(code) |
| 162 | + |
| 163 | +print("Patch fully completed.") |
0 commit comments