fla-core 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. fla/__init__.py +4 -0
  2. fla/modules/__init__.py +33 -0
  3. fla/modules/activations.py +548 -0
  4. fla/modules/convolution.py +1143 -0
  5. fla/modules/feature_map.py +300 -0
  6. fla/modules/fused_bitlinear.py +632 -0
  7. fla/modules/fused_cross_entropy.py +419 -0
  8. fla/modules/fused_kl_div.py +324 -0
  9. fla/modules/fused_linear_cross_entropy.py +620 -0
  10. fla/modules/fused_norm_gate.py +1253 -0
  11. fla/modules/grpo.py +411 -0
  12. fla/modules/l2norm.py +285 -0
  13. fla/modules/l2warp.py +38 -0
  14. fla/modules/layernorm.py +1433 -0
  15. fla/modules/layernorm_gated.py +528 -0
  16. fla/modules/mlp.py +132 -0
  17. fla/modules/parallel.py +42 -0
  18. fla/modules/rotary.py +500 -0
  19. fla/modules/token_shift.py +543 -0
  20. fla/ops/__init__.py +53 -0
  21. fla/ops/abc/__init__.py +7 -0
  22. fla/ops/abc/chunk.py +1117 -0
  23. fla/ops/abc/naive.py +96 -0
  24. fla/ops/attn/__init__.py +7 -0
  25. fla/ops/attn/decoding.py +182 -0
  26. fla/ops/attn/parallel.py +730 -0
  27. fla/ops/based/__init__.py +9 -0
  28. fla/ops/based/fused_chunk.py +373 -0
  29. fla/ops/based/naive.py +72 -0
  30. fla/ops/based/parallel.py +408 -0
  31. fla/ops/comba/__init__.py +7 -0
  32. fla/ops/comba/chunk.py +342 -0
  33. fla/ops/comba/fused_recurrent.py +332 -0
  34. fla/ops/comba/utils.py +172 -0
  35. fla/ops/comba/wy_fast.py +423 -0
  36. fla/ops/common/__init__.py +1 -0
  37. fla/ops/common/chunk_delta_h.py +527 -0
  38. fla/ops/common/chunk_h.py +384 -0
  39. fla/ops/common/chunk_h_parallel.py +551 -0
  40. fla/ops/common/chunk_h_split.py +596 -0
  41. fla/ops/common/chunk_o.py +681 -0
  42. fla/ops/common/chunk_scaled_dot_kkt.py +305 -0
  43. fla/ops/common/fused_chunk.py +629 -0
  44. fla/ops/common/fused_recurrent.py +567 -0
  45. fla/ops/delta_rule/__init__.py +11 -0
  46. fla/ops/delta_rule/chunk.py +311 -0
  47. fla/ops/delta_rule/fused_chunk.py +6 -0
  48. fla/ops/delta_rule/fused_recurrent.py +535 -0
  49. fla/ops/delta_rule/naive.py +120 -0
  50. fla/ops/delta_rule/parallel.py +403 -0
  51. fla/ops/delta_rule/wy_fast.py +294 -0
  52. fla/ops/forgetting_attn/__init__.py +7 -0
  53. fla/ops/forgetting_attn/parallel.py +64 -0
  54. fla/ops/gated_delta_product/__init__.py +5 -0
  55. fla/ops/gated_delta_product/chunk.py +305 -0
  56. fla/ops/gated_delta_product/chunk_deltaproduct_h.py +502 -0
  57. fla/ops/gated_delta_product/chunk_deltaproduct_o.py +154 -0
  58. fla/ops/gated_delta_product/chunk_ref.py +68 -0
  59. fla/ops/gated_delta_product/naive.py +36 -0
  60. fla/ops/gated_delta_rule/__init__.py +7 -0
  61. fla/ops/gated_delta_rule/chunk.py +340 -0
  62. fla/ops/gated_delta_rule/fused_recurrent.py +351 -0
  63. fla/ops/gated_delta_rule/wy_fast.py +296 -0
  64. fla/ops/generalized_delta_rule/__init__.py +9 -0
  65. fla/ops/generalized_delta_rule/dplr/__init__.py +7 -0
  66. fla/ops/generalized_delta_rule/dplr/chunk.py +362 -0
  67. fla/ops/generalized_delta_rule/dplr/chunk_A_bwd.py +367 -0
  68. fla/ops/generalized_delta_rule/dplr/chunk_A_fwd.py +198 -0
  69. fla/ops/generalized_delta_rule/dplr/chunk_h_bwd.py +175 -0
  70. fla/ops/generalized_delta_rule/dplr/chunk_h_fwd.py +175 -0
  71. fla/ops/generalized_delta_rule/dplr/chunk_o_bwd.py +430 -0
  72. fla/ops/generalized_delta_rule/dplr/chunk_o_fwd.py +125 -0
  73. fla/ops/generalized_delta_rule/dplr/fused_recurrent.py +268 -0
  74. fla/ops/generalized_delta_rule/dplr/naive.py +96 -0
  75. fla/ops/generalized_delta_rule/dplr/wy_fast_bwd.py +164 -0
  76. fla/ops/generalized_delta_rule/dplr/wy_fast_fwd.py +284 -0
  77. fla/ops/generalized_delta_rule/iplr/__init__.py +7 -0
  78. fla/ops/generalized_delta_rule/iplr/chunk.py +492 -0
  79. fla/ops/generalized_delta_rule/iplr/fused_recurrent.py +452 -0
  80. fla/ops/generalized_delta_rule/iplr/naive.py +69 -0
  81. fla/ops/generalized_delta_rule/iplr/wy_fast.py +300 -0
  82. fla/ops/gla/__init__.py +11 -0
  83. fla/ops/gla/chunk.py +1298 -0
  84. fla/ops/gla/fused_chunk.py +642 -0
  85. fla/ops/gla/fused_recurrent.py +111 -0
  86. fla/ops/gla/naive.py +41 -0
  87. fla/ops/gsa/__init__.py +9 -0
  88. fla/ops/gsa/chunk.py +1133 -0
  89. fla/ops/gsa/fused_recurrent.py +536 -0
  90. fla/ops/gsa/naive.py +69 -0
  91. fla/ops/hgrn/__init__.py +9 -0
  92. fla/ops/hgrn/chunk.py +282 -0
  93. fla/ops/hgrn/fused_recurrent.py +308 -0
  94. fla/ops/hgrn/naive.py +63 -0
  95. fla/ops/lightning_attn/__init__.py +9 -0
  96. fla/ops/lightning_attn/chunk.py +84 -0
  97. fla/ops/lightning_attn/fused_recurrent.py +84 -0
  98. fla/ops/linear_attn/__init__.py +11 -0
  99. fla/ops/linear_attn/chunk.py +76 -0
  100. fla/ops/linear_attn/fused_chunk.py +61 -0
  101. fla/ops/linear_attn/fused_recurrent.py +35 -0
  102. fla/ops/linear_attn/naive.py +64 -0
  103. fla/ops/linear_attn/utils.py +10 -0
  104. fla/ops/log_linear_attn/__init__.py +7 -0
  105. fla/ops/log_linear_attn/chunk.py +1904 -0
  106. fla/ops/log_linear_attn/naive.py +50 -0
  107. fla/ops/mesa_net/__init__.py +5 -0
  108. fla/ops/mesa_net/chunk.py +371 -0
  109. fla/ops/mesa_net/chunk_cg_solver_bwd.py +162 -0
  110. fla/ops/mesa_net/chunk_cg_solver_fwd.py +186 -0
  111. fla/ops/mesa_net/chunk_h_fwd.py +170 -0
  112. fla/ops/mesa_net/chunk_h_kk_intra_bwd.py +191 -0
  113. fla/ops/mesa_net/chunk_h_kv_intra_bwd.py +209 -0
  114. fla/ops/mesa_net/chunk_h_kv_intra_bwd_separate.py +300 -0
  115. fla/ops/mesa_net/decoding_one_step.py +175 -0
  116. fla/ops/mesa_net/naive.py +131 -0
  117. fla/ops/nsa/__init__.py +9 -0
  118. fla/ops/nsa/compression.py +536 -0
  119. fla/ops/nsa/naive.py +103 -0
  120. fla/ops/nsa/parallel.py +879 -0
  121. fla/ops/nsa/utils.py +92 -0
  122. fla/ops/path_attn/__init__.py +7 -0
  123. fla/ops/path_attn/cumprod_householder_bwd.py +140 -0
  124. fla/ops/path_attn/cumprod_householder_fwd.py +119 -0
  125. fla/ops/path_attn/intra_chunk_preprocess_bwd.py +140 -0
  126. fla/ops/path_attn/intra_chunk_preprocess_bwd_prepare.py +208 -0
  127. fla/ops/path_attn/intra_chunk_preprocess_fwd.py +168 -0
  128. fla/ops/path_attn/parallel.py +270 -0
  129. fla/ops/path_attn/parallel_path_bwd_inter_dkv.py +189 -0
  130. fla/ops/path_attn/parallel_path_bwd_inter_dqh.py +200 -0
  131. fla/ops/path_attn/parallel_path_bwd_intra.py +172 -0
  132. fla/ops/path_attn/parallel_path_fwd.py +195 -0
  133. fla/ops/path_attn/prepare_k_cache.py +74 -0
  134. fla/ops/path_attn/transform_q.py +108 -0
  135. fla/ops/rebased/__init__.py +7 -0
  136. fla/ops/rebased/naive.py +27 -0
  137. fla/ops/rebased/parallel.py +464 -0
  138. fla/ops/retention/__init__.py +13 -0
  139. fla/ops/retention/chunk.py +77 -0
  140. fla/ops/retention/fused_chunk.py +78 -0
  141. fla/ops/retention/fused_recurrent.py +33 -0
  142. fla/ops/retention/naive.py +15 -0
  143. fla/ops/retention/parallel.py +71 -0
  144. fla/ops/rwkv4/__init__.py +7 -0
  145. fla/ops/rwkv4/fused_recurrent.py +472 -0
  146. fla/ops/rwkv6/__init__.py +9 -0
  147. fla/ops/rwkv6/chunk.py +1300 -0
  148. fla/ops/rwkv6/chunk_naive.py +43 -0
  149. fla/ops/rwkv6/fused_recurrent.py +673 -0
  150. fla/ops/rwkv6/recurrent_naive.py +103 -0
  151. fla/ops/rwkv7/__init__.py +10 -0
  152. fla/ops/rwkv7/channel_mixing.py +323 -0
  153. fla/ops/rwkv7/chunk.py +78 -0
  154. fla/ops/rwkv7/fused_addcmul.py +293 -0
  155. fla/ops/rwkv7/fused_k_update.py +346 -0
  156. fla/ops/rwkv7/fused_recurrent.py +334 -0
  157. fla/ops/rwkv7/gate_output_correction.py +244 -0
  158. fla/ops/simple_gla/__init__.py +13 -0
  159. fla/ops/simple_gla/chunk.py +303 -0
  160. fla/ops/simple_gla/fused_chunk.py +108 -0
  161. fla/ops/simple_gla/fused_recurrent.py +112 -0
  162. fla/ops/simple_gla/naive.py +114 -0
  163. fla/ops/simple_gla/parallel.py +722 -0
  164. fla/ops/titans/__init__.py +7 -0
  165. fla/ops/titans/log_impl.py +153 -0
  166. fla/ops/titans/naive.py +375 -0
  167. fla/ops/ttt/__init__.py +9 -0
  168. fla/ops/ttt/chunk.py +1441 -0
  169. fla/ops/ttt/fused_chunk.py +831 -0
  170. fla/ops/ttt/naive.py +126 -0
  171. fla/ops/utils/__init__.py +58 -0
  172. fla/ops/utils/constant.py +6 -0
  173. fla/ops/utils/cumsum.py +465 -0
  174. fla/ops/utils/index.py +133 -0
  175. fla/ops/utils/logcumsumexp.py +52 -0
  176. fla/ops/utils/logsumexp.py +80 -0
  177. fla/ops/utils/matmul.py +245 -0
  178. fla/ops/utils/op.py +62 -0
  179. fla/ops/utils/pack.py +208 -0
  180. fla/ops/utils/pooling.py +207 -0
  181. fla/ops/utils/softmax.py +106 -0
  182. fla/ops/utils/solve_tril.py +381 -0
  183. fla/utils.py +462 -0
  184. fla_core-0.3.2.dist-info/METADATA +575 -0
  185. fla_core-0.3.2.dist-info/RECORD +188 -0
  186. fla_core-0.3.2.dist-info/WHEEL +5 -0
  187. fla_core-0.3.2.dist-info/licenses/LICENSE +21 -0
  188. fla_core-0.3.2.dist-info/top_level.txt +1 -0
fla/modules/grpo.py ADDED
@@ -0,0 +1,411 @@
1
+ # -*- coding: utf-8 -*-
2
+ # modified from https://github.com/mdy666/mdy_triton/blob/e0a856347bd988e05e0152332bba35f1d33c5b1f/others/grpo/grpo_loss.ipynb
3
+ # XHS ID: blueeeee
4
+
5
+ # https://github.com/huggingface/trl/blob/main/trl/trainer/grpo_trainer.py
6
+ """
7
+ # Get the per-token log probabilities for the completions for the model and the reference model
8
+ def _get_per_token_logps(self, model, input_ids, attention_mask, logits_to_keep):
9
+ # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded
10
+ logits = model(input_ids=input_ids, attention_mask=attention_mask, logits_to_keep=logits_to_keep + 1).logits
11
+ logits = logits[:, :-1, :] # (B, L-1, V), exclude the last logit: it corresponds to the next token pred
12
+
13
+ input_ids = input_ids[:, -logits_to_keep:]
14
+ # For transformers<=4.48, logits_to_keep argument isn't supported, so here we drop logits ourselves.
15
+ # See https://github.com/huggingface/trl/issues/2770
16
+ logits = logits[:, -logits_to_keep:]
17
+ return selective_log_softmax(logits, input_ids) # compute logprobs for the input tokens
18
+
19
+ def compute_loss(self, model, inputs, return_outputs=False, num_items_in_batch=None):
20
+ if return_outputs:
21
+ raise ValueError("The GRPOTrainer does not support returning outputs")
22
+ # Compute the per-token log probabilities for the model
23
+
24
+ prompt_ids, prompt_mask = inputs["prompt_ids"], inputs["prompt_mask"]
25
+ completion_ids, completion_mask = inputs["completion_ids"], inputs["completion_mask"]
26
+ input_ids = torch.cat([prompt_ids, completion_ids], dim=1)
27
+ attention_mask = torch.cat([prompt_mask, completion_mask], dim=1)
28
+ logits_to_keep = completion_ids.size(1) # we only need to compute the logits for the completion tokens
29
+
30
+ per_token_logps = self._get_per_token_logps(model, input_ids, attention_mask, logits_to_keep)
31
+
32
+ # Compute the KL divergence between the model and the reference model
33
+ ref_per_token_logps = inputs["ref_per_token_logps"]
34
+ per_token_kl = torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
35
+
36
+ # x - x.detach() allows for preserving gradients from x
37
+ advantages = inputs["advantages"]
38
+ per_token_loss = torch.exp(per_token_logps - per_token_logps.detach()) * advantages.unsqueeze(1)
39
+ per_token_loss = -(per_token_loss - self.beta * per_token_kl)
40
+ loss = ((per_token_loss * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)).mean()
41
+
42
+ # Log the metrics
43
+ completion_length = self.accelerator.gather_for_metrics(completion_mask.sum(1)).float().mean().item()
44
+ self._metrics["completion_length"].append(completion_length)
45
+
46
+ mean_kl = ((per_token_kl * completion_mask).sum(dim=1) / completion_mask.sum(dim=1)).mean()
47
+ self._metrics["kl"].append(self.accelerator.gather_for_metrics(mean_kl).mean().item())
48
+
49
+ return loss
50
+ """
51
+
52
+
53
+ import torch
54
+ import triton
55
+ import triton.language as tl
56
+
57
+ from fla.ops.utils.op import exp, log
58
+ from fla.utils import input_guard, is_amd
59
+
60
+ NUM_WARPS_AUTOTUNE = [4, 8, 16] if is_amd else [4, 8, 16, 32]
61
+
62
+
63
+ @triton.autotune(
64
+ configs=[
65
+ triton.Config({'BLOCK_SIZE': BLOCK_SIZE}, num_warps=NUM_WARPS, num_stages=NUM_STAGES)
66
+ for BLOCK_SIZE in [1024, 2048, 4096, 8192]
67
+ for NUM_WARPS in NUM_WARPS_AUTOTUNE
68
+ for NUM_STAGES in [1, 2, 4]
69
+ ],
70
+ key=['B', 'N']
71
+ )
72
+ @triton.jit
73
+ def grpo_fwd_kernel(
74
+ logits_ptr,
75
+ ref_logp_ptr,
76
+ input_ids_ptr,
77
+ advantages_ptr,
78
+ completion_mask_ptr,
79
+ loss_ptr,
80
+ lse_ptr,
81
+ beta,
82
+ save_kl: tl.constexpr,
83
+ B,
84
+ M,
85
+ N,
86
+ L,
87
+ start_idx,
88
+ BLOCK_SIZE: tl.constexpr
89
+ ):
90
+ row_idx = tl.program_id(0)
91
+
92
+ off_b = row_idx // L
93
+ N = tl.cast(N, tl.int64)
94
+
95
+ loss_ptr += row_idx
96
+
97
+ completion_mask_ptr += row_idx
98
+ not_skip = tl.load(completion_mask_ptr).to(tl.int1)
99
+ if not_skip == 1:
100
+ ref_logp_ptr += row_idx
101
+ lse_ptr += row_idx
102
+ advantages_ptr += off_b
103
+ logits_ptr += N * (row_idx + off_b)
104
+ input_ids_ptr += row_idx + (off_b+1) * start_idx
105
+ base_cols = tl.arange(0, BLOCK_SIZE)
106
+
107
+ m_i = -float("inf")
108
+ l_i = 0.0
109
+ for start_n in tl.range(0, N, BLOCK_SIZE):
110
+ cols = start_n + base_cols
111
+ mask = cols < N
112
+ logits = tl.load(logits_ptr+cols, mask=mask, other=-float('inf')).to(tl.float32)
113
+ m_ij = tl.max(logits)
114
+ new_m_i = tl.maximum(m_i, m_ij)
115
+ l_i = l_i * exp(m_i - new_m_i) + tl.sum(exp(logits - new_m_i))
116
+ m_i = new_m_i
117
+ lse = log(l_i) + m_i
118
+
119
+ idx = tl.load(input_ids_ptr)
120
+ x = tl.load(logits_ptr+idx).to(tl.float32)
121
+ advantage = tl.load(advantages_ptr).to(tl.float32)
122
+ ref_logp = tl.load(ref_logp_ptr)
123
+ logp = x - lse
124
+ diff = ref_logp - logp
125
+ kl = exp(diff) - diff - 1
126
+ loss = kl * beta - advantage
127
+
128
+ tl.store(loss_ptr, loss.to(loss_ptr.dtype.element_ty))
129
+ tl.store(lse_ptr, lse.to(lse_ptr.dtype.element_ty))
130
+ if save_kl:
131
+ tl.store(loss_ptr+M, kl.to(loss_ptr.dtype.element_ty))
132
+ else:
133
+ # store 0
134
+ tl.store(loss_ptr, 0.0)
135
+ if save_kl:
136
+ tl.store(loss_ptr+M, 0.0)
137
+
138
+
139
+ @triton.autotune(
140
+ configs=[
141
+ triton.Config({}, num_warps=NUM_WARPS, num_stages=NUM_STAGES)
142
+ for NUM_WARPS in [32]
143
+ for NUM_STAGES in [4]
144
+ ],
145
+ key=['B', 'N']
146
+ )
147
+ @triton.jit
148
+ def grpo_bwd_kernel(
149
+ dloss_ptr,
150
+ dlogits_ptr,
151
+ logits_ptr,
152
+ ref_logp_ptr,
153
+ input_ids_ptr,
154
+ advantages_ptr,
155
+ completion_mask_ptr,
156
+ lse_ptr,
157
+ beta,
158
+ B,
159
+ N,
160
+ L,
161
+ start_idx,
162
+ BLOCK_SIZE: tl.constexpr
163
+ ):
164
+
165
+ row_idx = tl.program_id(0) # B*L
166
+ off_b = row_idx // L
167
+
168
+ N = tl.cast(N, tl.int64)
169
+
170
+ dlogits_ptr += N * (row_idx + off_b)
171
+ base_cols = tl.arange(0, BLOCK_SIZE)
172
+ completion_mask_ptr += row_idx
173
+ not_skip = tl.load(completion_mask_ptr).to(tl.int1)
174
+
175
+ if not_skip == 1:
176
+ lse_ptr += row_idx
177
+ dloss_ptr += row_idx
178
+ advantages_ptr += off_b
179
+ ref_logp_ptr += row_idx
180
+ logits_ptr += N * (row_idx + off_b)
181
+ input_ids_ptr += row_idx + (off_b+1) * start_idx
182
+ dloss = tl.load(dloss_ptr).to(tl.float32)
183
+ lse = tl.load(lse_ptr).to(tl.float32)
184
+ idx = tl.load(input_ids_ptr)
185
+ x = tl.load(logits_ptr+idx).to(tl.float32)
186
+ advantage = tl.load(advantages_ptr).to(tl.float32)
187
+ ref_logp = tl.load(ref_logp_ptr)
188
+ # Need for in-place grad.
189
+ tl.debug_barrier()
190
+ logp = x - lse
191
+
192
+ dlogp = (beta * (-1.0 * exp(ref_logp - logp) + 1)
193
+ - advantage) * dloss
194
+
195
+ for start_n in tl.range(0, N, BLOCK_SIZE):
196
+ cols = start_n + base_cols
197
+ mask = cols < N
198
+ logits = tl.load(logits_ptr+cols, mask=mask, other=-float('inf')).to(tl.float32)
199
+ probs = exp(logits - lse)
200
+ dlogits = tl.where(cols == idx, 1-probs, -probs) * dlogp
201
+
202
+ tl.store(dlogits_ptr+cols, dlogits.to(dlogits_ptr.dtype.element_ty), mask=mask)
203
+ else:
204
+ dlogits = tl.zeros((BLOCK_SIZE,), dtype=tl.float32)
205
+ for start_n in tl.range(0, N, BLOCK_SIZE):
206
+ cols = start_n + base_cols
207
+ mask = cols < N
208
+
209
+ tl.store(dlogits_ptr+cols, dlogits.to(dlogits_ptr.dtype.element_ty), mask=mask)
210
+
211
+
212
+ class GrpoLoss(torch.autograd.Function):
213
+
214
+ @input_guard
215
+ @staticmethod
216
+ def forward(ctx, logits, ref_logp, input_ids, advantages, beta, completion_mask, save_kl, inplace=True):
217
+ ctx.input_shape = logits.shape
218
+ B, L_ADD_1, N = ctx.input_shape
219
+ L = L_ADD_1 - 1
220
+ M = B * L
221
+ input_ids_start_index = input_ids.size(1) - L
222
+
223
+ if not save_kl:
224
+ loss = torch.empty(B, L, device=logits.device, dtype=torch.float32)
225
+ else:
226
+ loss = torch.empty(B*2, L, device=logits.device, dtype=torch.float32)
227
+
228
+ lse = torch.empty(B, L, device=logits.device, dtype=torch.float32)
229
+
230
+ if completion_mask is None:
231
+ completion_mask = torch.ones(B, L, device=logits.device, dtype=torch.int32)
232
+ else:
233
+ loss[:B].masked_fill_(completion_mask.logical_not(), 0.0)
234
+
235
+ grpo_fwd_kernel[(M,)](
236
+ logits_ptr=logits,
237
+ ref_logp_ptr=ref_logp,
238
+ input_ids_ptr=input_ids,
239
+ advantages_ptr=advantages,
240
+ completion_mask_ptr=completion_mask,
241
+ loss_ptr=loss,
242
+ lse_ptr=lse,
243
+ beta=beta,
244
+ save_kl=save_kl,
245
+ B=B, M=M, N=N, L=L,
246
+ start_idx=input_ids_start_index,
247
+ )
248
+ ctx.beta = beta
249
+ ctx.save_for_backward(lse, logits, input_ids, advantages, completion_mask)
250
+ ctx.ref_logp = ref_logp
251
+ ctx.inplace = inplace
252
+ return loss
253
+
254
+ @input_guard
255
+ @staticmethod
256
+ def backward(ctx, dloss):
257
+ # The grad of logits comes from two parts, the reward part and the kl part
258
+ lse, logits, input_ids, advantages, completion_mask = ctx.saved_tensors
259
+ inplace = ctx.inplace
260
+ B, L_ADD_1, N = ctx.input_shape
261
+ L = L_ADD_1 - 1
262
+ M = B * L
263
+
264
+ input_ids_start_index = input_ids.size(1) - L
265
+
266
+ # B, L_ADD_1, N
267
+ dlogits = logits if inplace else torch.empty_like(logits)
268
+ BN = min(65536, triton.next_power_of_2(N))
269
+
270
+ grpo_bwd_kernel[(M,)](
271
+ dloss_ptr=dloss,
272
+ dlogits_ptr=dlogits,
273
+ logits_ptr=logits,
274
+ ref_logp_ptr=ctx.ref_logp,
275
+ input_ids_ptr=input_ids,
276
+ advantages_ptr=advantages,
277
+ completion_mask_ptr=completion_mask,
278
+ lse_ptr=lse,
279
+ beta=ctx.beta,
280
+ B=B, N=N, L=L,
281
+ BLOCK_SIZE=BN,
282
+ start_idx=input_ids_start_index,
283
+ )
284
+ # The last token in the completion is not used in the loss computation
285
+ # and therefore its gradient should be set to 0
286
+ dlogits[:, -1, :].fill_(0.0)
287
+ return dlogits.view(*ctx.input_shape), None, None, None, None, None, None, None
288
+
289
+
290
+ def fused_grpo_loss(logits, ref_logp, input_ids, advantages,
291
+ beta=0.1, completion_mask=None, save_kl=False, inplace=False) -> torch.Tensor:
292
+ '''
293
+ compute grpo loss, save memory(no addition usage) and fast speed(6X for A800)
294
+
295
+ Args:
296
+ logtits: Tensor, [B, L+1, vocab_size], the origin output of model, it's not logits[:, :-1]
297
+ ref_logp: Tensor, [B, L], the origin output of model, it's not ref_logits[:, :-1]
298
+ input_ids: Tensor, [B, K+L], it's prompt_completion_id, it contains the prompt ids and output ids
299
+ advantages: Tensor, [B], the advantages of each prompt
300
+ beta: float, the weight of kl loss
301
+ completion_mask: Tensor, loss mask
302
+ save_kl: bool, if true will save kl
303
+
304
+ Retutn:
305
+ loss: Tensor, [B, L], the loss of grpo, it contains the advantage part and kl part
306
+
307
+ NOTE: logits(ref_logits) is computed by these steps
308
+ logits_to_keep = completion_ids.size(1)
309
+
310
+ def get_per_token_logits(model, input_ids, attention_mask, logits_to_keep):
311
+ # We add 1 to `logits_to_keep` because the last logits of the sequence is later excluded
312
+ logits = model(
313
+ input_ids=input_ids, attention_mask=attention_mask, logits_to_keep=logits_to_keep + 1
314
+ ).logits
315
+ return logits
316
+
317
+ logits = get_per_token_logits(model, prompt_completion_ids, attention_mask, logits_to_keep)
318
+ '''
319
+ out = GrpoLoss.apply(logits, ref_logp, input_ids, advantages, beta, completion_mask, save_kl, inplace)
320
+ if not save_kl:
321
+ return out
322
+ else:
323
+ return out.chunk(2, axis=0)
324
+
325
+
326
+ def grpo_loss_torch(logits, ref_logp, input_ids, advantages, beta=0.1, completion_mask=None, save_kl=False):
327
+ def get_log_probs(logits, input_ids):
328
+ per_token_logps = []
329
+ for logits_row, input_ids_row in zip(logits, input_ids[:, -logits.size(1):]):
330
+ log_probs = logits_row.log_softmax(dim=-1)
331
+ token_log_prob = torch.gather(log_probs, dim=1, index=input_ids_row.unsqueeze(1)).squeeze(1)
332
+ per_token_logps.append(token_log_prob)
333
+ return torch.stack(per_token_logps)
334
+
335
+ logits = logits[:, :-1]
336
+ per_token_logps = get_log_probs(logits, input_ids)
337
+ ref_per_token_logps = ref_logp
338
+ per_token_kl = torch.exp(ref_per_token_logps - per_token_logps) - (ref_per_token_logps - per_token_logps) - 1
339
+
340
+ per_token_loss = torch.exp(per_token_logps - per_token_logps.detach()) * advantages.unsqueeze(1)
341
+ per_token_loss = -(per_token_loss - beta * per_token_kl)
342
+ if completion_mask is not None:
343
+ per_token_loss *= completion_mask
344
+ if save_kl:
345
+ per_token_kl *= completion_mask
346
+ return per_token_loss if not save_kl else (per_token_loss, per_token_kl)
347
+
348
+
349
+ @torch.compile(fullgraph=True)
350
+ def grpo_loss_with_old_logps(
351
+ logps: torch.Tensor,
352
+ ref_logps: torch.Tensor,
353
+ old_logps: torch.Tensor,
354
+ pad_mask: torch.Tensor,
355
+ logits_to_keep: int,
356
+ rewards: torch.Tensor,
357
+ beta: float = 0.2,
358
+ epsilon: float = 0.2
359
+ ):
360
+ """
361
+ Compute the GRPO (Group Relative Policy Optimization) loss.
362
+
363
+ Args:
364
+ logps (torch.Tensor): [Batch, Token_length] Log probabilities of the current policy.
365
+ ref_logps (torch.Tensor):[Batch, Token_length] Log probabilities of the reference policy.
366
+ old_logps (torch.Tensor): [Batch, Token_length] Log probabilities of the old policy.
367
+ completion_ids (torch.Tensor): [Batch, Token_length] Completion token IDs (bool).
368
+ pad_token_id: Pad token ID.
369
+ logits_to_keep (int): Number of logits to keep for masking.
370
+ rewards (torch.Tensor): [Batch] Rewards for each generation.
371
+ beta (float) = 0.2: A hyperparameter for weighting the KL divergence term.
372
+ epsilon (float) = 0.2: An float hyperparameter for clipping the importance weights.
373
+
374
+ Returns:
375
+ torch.Tensor: The computed GRPO loss.
376
+ """
377
+ B = logps.shape[0]
378
+ assert B > 1, "Batch * Num generations should be greater than 1"
379
+
380
+ rewards_shaped = rewards.view(-1, B) # B,num_generations
381
+ advantages = (rewards_shaped - rewards_shaped.mean(dim=1, keepdim=True)) / \
382
+ (rewards_shaped.std(dim=1, keepdim=True) + 1e-8)
383
+ advantages = advantages.view(-1) # B*num_generations
384
+ # Calculate the per - token KL divergence
385
+ per_token_kl = torch.exp(ref_logps - logps) - (ref_logps - logps) - 1
386
+
387
+ # Calculate the ratio of probabilities (importance weights)
388
+ # Importance weights are calculated as exp(log_pi_theta - log_pi_theta_old)
389
+ importance_weights = torch.exp(logps - old_logps)
390
+
391
+ # Clip the importance weights to the range [1 - epsilon, 1 + epsilon]
392
+ importance_weights_clipped = torch.clamp(importance_weights, 1 - epsilon, 1 + epsilon)
393
+
394
+ # Create a completion mask. It checks which positions are valid based on logits_to_keep
395
+ completion_mask = torch.arange(logits_to_keep, device=logps.device)[None, :] >= 0
396
+
397
+ # Combine the completion mask and padding mask
398
+ completion_mask = completion_mask & pad_mask # Ensure matching shape
399
+
400
+ # Add an extra dimension to advantages to match the shape for element - wise multiplication
401
+ advantages = advantages.unsqueeze(1)
402
+
403
+ # Calculate the per - token loss. It takes the minimum of the unclipped and clipped importance weights
404
+ # and subtracts the KL divergence term weighted by beta, then multiplies by the completion mask
405
+ token_loss = -(torch.min(advantages * importance_weights, advantages *
406
+ importance_weights_clipped) - beta * per_token_kl) * completion_mask
407
+
408
+ # Calculate the final loss by summing the token losses and normalizing by the number of valid tokens
409
+ loss = -token_loss.sum() / completion_mask.sum()
410
+
411
+ return loss
fla/modules/l2norm.py ADDED
@@ -0,0 +1,285 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Copyright (c) 2023-2025, Songlin Yang, Yu Zhang
3
+
4
+ from typing import Optional
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import triton
9
+ import triton.language as tl
10
+
11
+ from fla.utils import input_guard, is_amd
12
+
13
+ BT_LIST = [8, 16, 32, 64, 128]
14
+ NUM_WARPS_AUTOTUNE = [1, 2, 4, 8, 16] if is_amd else [1, 2, 4, 8, 16, 32]
15
+
16
+
17
+ @triton.autotune(
18
+ configs=[
19
+ triton.Config({}, num_warps=num_warps)
20
+ for num_warps in NUM_WARPS_AUTOTUNE
21
+ ],
22
+ key=['D']
23
+ )
24
+ @triton.jit
25
+ def l2norm_fwd_kernel1(
26
+ x,
27
+ y,
28
+ rstd,
29
+ eps,
30
+ D,
31
+ BD: tl.constexpr,
32
+ ):
33
+ i_t = tl.program_id(0)
34
+ x += i_t * D
35
+ y += i_t * D
36
+ # Compute mean and variance
37
+ cols = tl.arange(0, BD)
38
+ mask = cols < D
39
+
40
+ b_x = tl.load(x + cols, mask=mask, other=0.0).to(tl.float32)
41
+ b_rstd = 1 / tl.sqrt(tl.sum(b_x * b_x) + eps)
42
+ b_y = b_x * b_rstd
43
+ tl.store(y + cols, b_y, mask=mask)
44
+ tl.store(rstd + i_t, b_rstd)
45
+
46
+
47
+ @triton.autotune(
48
+ configs=[
49
+ triton.Config({}, num_warps=num_warps)
50
+ for num_warps in NUM_WARPS_AUTOTUNE
51
+ ],
52
+ key=['D']
53
+ )
54
+ @triton.jit
55
+ def l2norm_bwd_kernel1(
56
+ y,
57
+ rstd,
58
+ dy,
59
+ dx,
60
+ eps,
61
+ D,
62
+ BD: tl.constexpr,
63
+ ):
64
+ i_t = tl.program_id(0)
65
+ y += i_t * D
66
+ dx += i_t * D
67
+ dy += i_t * D
68
+
69
+ cols = tl.arange(0, BD)
70
+ mask = cols < D
71
+ b_y = tl.load(y + cols, mask=mask, other=0.0).to(tl.float32)
72
+ b_rstd = tl.load(rstd + i_t).to(tl.float32)
73
+ b_dy = tl.load(dy + cols, mask=mask, other=0.0).to(tl.float32)
74
+ b_dx = b_dy * b_rstd - tl.sum(b_dy * b_y) * b_y * b_rstd
75
+ tl.store(dx + cols, b_dx, mask=mask)
76
+
77
+
78
+ @triton.autotune(
79
+ configs=[
80
+ triton.Config({'BT': BT}, num_warps=num_warps)
81
+ for num_warps in [1, 2, 4, 8, 16]
82
+ for BT in BT_LIST
83
+ ],
84
+ key=['D', 'NB']
85
+ )
86
+ @triton.jit
87
+ def l2norm_fwd_kernel(
88
+ x,
89
+ y,
90
+ rstd,
91
+ eps,
92
+ T: tl.constexpr,
93
+ D: tl.constexpr,
94
+ BD: tl.constexpr,
95
+ NB: tl.constexpr,
96
+ BT: tl.constexpr,
97
+ ):
98
+ i_t = tl.program_id(0)
99
+ p_x = tl.make_block_ptr(x, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
100
+ p_y = tl.make_block_ptr(y, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
101
+ p_rstd = tl.make_block_ptr(rstd, (T,), (1,), (i_t * BT,), (BT,), (0,))
102
+
103
+ b_x = tl.load(p_x, boundary_check=(0, 1)).to(tl.float32)
104
+ b_rstd = 1 / tl.sqrt(tl.sum(b_x * b_x, 1) + eps)
105
+ b_y = b_x * b_rstd[:, None]
106
+
107
+ tl.store(p_y, b_y.to(p_y.dtype.element_ty), boundary_check=(0, 1))
108
+ tl.store(p_rstd, b_rstd.to(p_rstd.dtype.element_ty), boundary_check=(0,))
109
+
110
+
111
+ @triton.autotune(
112
+ configs=[
113
+ triton.Config({'BT': BT}, num_warps=num_warps)
114
+ for num_warps in [1, 2, 4, 8, 16]
115
+ for BT in BT_LIST
116
+ ],
117
+ key=['D', 'NB']
118
+ )
119
+ @triton.jit
120
+ def l2norm_bwd_kernel(
121
+ y,
122
+ rstd,
123
+ dy,
124
+ dx,
125
+ eps,
126
+ T: tl.constexpr,
127
+ D: tl.constexpr,
128
+ BD: tl.constexpr,
129
+ NB: tl.constexpr,
130
+ BT: tl.constexpr,
131
+ ):
132
+ i_t = tl.program_id(0)
133
+ p_y = tl.make_block_ptr(y, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
134
+ p_rstd = tl.make_block_ptr(rstd, (T,), (1,), (i_t * BT,), (BT,), (0,))
135
+ p_dy = tl.make_block_ptr(dy, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
136
+ p_dx = tl.make_block_ptr(dx, (T, D), (D, 1), (i_t * BT, 0), (BT, BD), (1, 0))
137
+
138
+ b_y = tl.load(p_y, boundary_check=(0, 1)).to(tl.float32)
139
+ b_rstd = tl.load(p_rstd, boundary_check=(0,)).to(tl.float32)
140
+ b_dy = tl.load(p_dy, boundary_check=(0, 1)).to(tl.float32)
141
+ b_dx = b_dy * b_rstd[:, None] - tl.sum(b_dy * b_y, 1)[:, None] * b_y * b_rstd[:, None]
142
+ tl.store(p_dx, b_dx.to(p_dx.dtype.element_ty), boundary_check=(0, 1))
143
+
144
+
145
+ def l2norm_fwd(
146
+ x: torch.Tensor,
147
+ eps: float = 1e-6,
148
+ output_dtype: Optional[torch.dtype] = None
149
+ ):
150
+ x_shape_og = x.shape
151
+ x = x.view(-1, x.shape[-1])
152
+ # allocate output
153
+ if output_dtype is None:
154
+ y = torch.empty_like(x)
155
+ else:
156
+ y = torch.empty_like(x, dtype=output_dtype)
157
+ assert y.stride(-1) == 1
158
+ T, D = x.shape[0], x.shape[-1]
159
+ # Less than 64KB per feature: enqueue fused kernel
160
+ MAX_FUSED_SIZE = 65536 // x.element_size()
161
+ BD = min(MAX_FUSED_SIZE, triton.next_power_of_2(D))
162
+ if D > BD:
163
+ raise RuntimeError("This layer doesn't support feature dim >= 64KB.")
164
+
165
+ rstd = torch.empty((T,), dtype=torch.float32, device=x.device)
166
+ if D <= 512:
167
+ NB = triton.cdiv(T, 2048)
168
+ def grid(meta): return (triton.cdiv(T, meta['BT']), )
169
+ l2norm_fwd_kernel[grid](
170
+ x=x,
171
+ y=y,
172
+ rstd=rstd,
173
+ eps=eps,
174
+ T=T,
175
+ D=D,
176
+ BD=BD,
177
+ NB=NB,
178
+ )
179
+ else:
180
+ l2norm_fwd_kernel1[(T,)](
181
+ x=x,
182
+ y=y,
183
+ rstd=rstd,
184
+ eps=eps,
185
+ D=D,
186
+ BD=BD,
187
+ )
188
+ return y.view(x_shape_og), rstd.view(x_shape_og[:-1])
189
+
190
+
191
+ def l2norm_bwd(
192
+ y: torch.Tensor,
193
+ rstd: torch.Tensor,
194
+ dy: torch.Tensor,
195
+ eps: float = 1e-6
196
+ ):
197
+ y_shape_og = y.shape
198
+ y = y.view(-1, dy.shape[-1])
199
+ dy = dy.view(-1, dy.shape[-1])
200
+ assert dy.shape == y.shape
201
+ # allocate output
202
+ dx = torch.empty_like(y)
203
+ T, D = y.shape[0], y.shape[-1]
204
+ # Less than 64KB per feature: enqueue fused kernel
205
+ MAX_FUSED_SIZE = 65536 // y.element_size()
206
+ BD = min(MAX_FUSED_SIZE, triton.next_power_of_2(D))
207
+ if D > BD:
208
+ raise RuntimeError("This layer norm doesn't support feature dim >= 64KB.")
209
+
210
+ if D <= 512:
211
+ NB = triton.cdiv(T, 2048)
212
+ def grid(meta): return (triton.cdiv(T, meta['BT']), )
213
+ l2norm_bwd_kernel[grid](
214
+ y=y,
215
+ rstd=rstd,
216
+ dy=dy,
217
+ dx=dx,
218
+ eps=eps,
219
+ T=T,
220
+ D=D,
221
+ BD=BD,
222
+ NB=NB,
223
+ )
224
+ else:
225
+ l2norm_bwd_kernel1[(T,)](
226
+ y=y,
227
+ rstd=rstd,
228
+ dy=dy,
229
+ dx=dx,
230
+ eps=eps,
231
+ D=D,
232
+ BD=BD,
233
+ )
234
+
235
+ return dx.view(y_shape_og)
236
+
237
+
238
+ class L2NormFunction(torch.autograd.Function):
239
+
240
+ @staticmethod
241
+ @input_guard
242
+ def forward(
243
+ ctx,
244
+ x,
245
+ eps=1e-6,
246
+ output_dtype=None
247
+ ):
248
+ y, rstd = l2norm_fwd(x, eps, output_dtype)
249
+ ctx.eps = eps
250
+ ctx.x_dtype = x.dtype
251
+ ctx.save_for_backward(y, rstd)
252
+ return y
253
+
254
+ @staticmethod
255
+ @input_guard
256
+ def backward(ctx, dy):
257
+ y, rstd = ctx.saved_tensors
258
+ dx = l2norm_bwd(y, rstd, dy, ctx.eps)
259
+ return dx, None, None
260
+
261
+
262
+ def l2norm(
263
+ x: torch.Tensor,
264
+ eps: float = 1e-6,
265
+ output_dtype: Optional[torch.dtype] = None
266
+ ) -> torch.Tensor:
267
+ return L2NormFunction.apply(x, eps, output_dtype)
268
+
269
+
270
+ l2_norm = l2norm
271
+
272
+
273
+ class L2Norm(nn.Module):
274
+
275
+ def __init__(
276
+ self,
277
+ eps: float = 1e-6,
278
+ output_dtype: Optional[torch.dtype] = None
279
+ ):
280
+ super().__init__()
281
+ self.eps = eps
282
+ self.output_dtype = output_dtype
283
+
284
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
285
+ return l2norm(x, self.eps, self.output_dtype)