occult/layers/router.py SHA256 eccd1aa385642a651746ea20715cfdf9f4be4de6df077c33fc987146ad76da43
43: # NOTE: To enable end-to-end benchmarking without convergence we
44: # support a flag to force the router to assign tokens uniformly
45: # across the experts. We do this with a custom autograd operation
46: # so that PyTorch still executes the full set of router operation.
47: class _UniformExpertAssignment(torch.autograd.Function):
48: 
49:     @staticmethod
50:     def forward(ctx: Any, x: torch.Tensor, num_experts: int):
51:         out = torch.arange(x.numel(), dtype=x.dtype, device=x.device)
52:         out = torch.remainder(out, num_experts)
53:         return out.view(x.shape)
54: 
55: 
56: _uniform_expert_assignment = _UniformExpertAssignment.apply
57: 
58: 
59: class LearnedRouter(torch.nn.Module):
60: 
61:     def __init__(self, args: Arguments):
62:         super().__init__()
63:         self.args = args
64: 
65:         # Learned router parameters.
66:         #
67:         # NOTE: This weight matrix is not parallelized with expert model
68:         # parallelism. Each device needs the entire router weight matrix
69:         # so that it can route its batch of data correctly.
70:         self.layer = torch.nn.Linear(
71:             args.hidden_size,
72:             args.moe_num_experts,
73:             bias=False,
74:             dtype=common.dtype(args),
75:             device=args.device,
76:         )
77:         args.init_method(self.layer.weight)
78: 
79:     def jitter(self, x: torch.Tensor):
80:         low: float = 1.0 - self.args.moe_jitter_eps
81:         high: float = 1.0 + self.args.moe_jitter_eps
82:         noise = torch.rand(x.size(), dtype=x.dtype, device=x.device)
83:         return low + noise * (high - low)
84: 
85:     def _top_k(self, scores: torch.Tensor):
86:         if self.args.moe_top_k == 1:
87:             return scores.max(dim=-1, keepdim=True)
88:         return torch.topk(scores, self.args.moe_top_k, dim=-1)
89: 
90:     def forward(self, x: torch.Tensor):
91:         if self.training and self.args.moe_jitter_eps is not None:
92:             x = x * self.jitter(x)
93: 
94:         logits = self.layer(x.view(-1, x.shape[-1]))
95:         _save_router_logits(logits, self.args)
96:         scores = logits.softmax(dim=-1)
97:         expert_weights, expert_indices = self._top_k(scores)
98:         if self.args.moe_normalize_expert_weights:
99:             expert_weights = expert_weights / torch.norm(
100:                 expert_weights,
101:                 p=self.args.moe_normalize_expert_weights,
102:                 dim=-1,
103:                 keepdim=True,
104:             )
105: 
106:         expert_indices = (
107:             _uniform_expert_assignment(
108:                 expert_indices,
109:                 self.args.moe_num_experts,
110:             ) if self.args.uniform_expert_assignment else expert_indices
111:         )
112:         return scores, expert_weights, expert_indices
occult/layers/dmoe.py SHA256 e24b1c61788077dab9f9f89472ba6a2c29dd1e78165c23d067eef3899e05ffc7
93:         # owned by this rank.
94:         self.num_experts = args.moe_num_experts
95:         self.top_k = self.args.moe_top_k
96: 
97:         self.world_size = mpu.get_expert_parallel_world_size(self.args)
98:         self.local_rank = mpu.get_expert_parallel_rank(self.args)
99: 
100:         if self.world_size == 2:
101:             ep_config = args.ep_size_2
102:             table_devs_config = args.table_devices_2
103:         elif self.world_size == 3:
104:             ep_config = args.ep_size_3
105:             table_devs_config = args.table_devices_3
106:         elif self.world_size == 4:
107:             ep_config = args.ep_size_4
108:             table_devs_config = args.table_devices_4
109:         elif self.world_size == 5:
110:             ep_config = args.ep_size_5
111:             table_devs_config = args.table_devices_5
112:         elif self.world_size == 6:
113:             ep_config = args.ep_size_6
114:             table_devs_config = args.table_devices_6
115:         elif self.world_size == 8:
116:             ep_config = args.ep_size_8
117:             table_devs_config = args.table_devices_8
118:         elif self.world_size == 16:
119:             ep_config = args.ep_size_16
120:             table_devs_config = args.table_devices_16
121: 
122:         table_exps_config = args.table_experts
123: 
124:         self.local_expert_list = torch.cuda.ShortTensor(ep_config['layer_' + str(args.layer_idx)]["local_expert_lists"][self.local_rank])
125:         self.global_expert_list = torch.cuda.ShortTensor(ep_config['layer_' + str(args.layer_idx)]["global_expert_list"])
126: 
127:         self.table_exps = torch.cuda.ShortTensor(table_exps_config['layer_' + str(args.layer_idx)])
128:         self.table_devs = torch.cuda.ShortTensor(table_devs_config['layer_' + str(args.layer_idx)])
129: 
130:         self.bias: Optional[torch.Tensor]
131:         if self.args.bias:
132:             # Note that the output bias is not parallelized with expert
201:         orig_dtype = x.dtype
202: 
203:         if (common.dtype(self.args)):
204:             expert_weights = expert_weights.to(common.dtype(self.args))
205:             x = x.view(-1, x.shape[-1]).to(common.dtype(self.args))
206:         else:
207:             x = x.view(-1, x.shape[-1])
208:         top_experts = top_experts.to(torch.int16)
209:         
210:         with torch.no_grad():
211:             re_idx_mat_0, tokens_per_device = (self.pre_dispatch(top_experts))
212: 
213:             summed_tokens_per_device = torch.empty_like(tokens_per_device)
214:             tpd_handle = dist.all_to_all_single(
215:                 summed_tokens_per_device,
216:                 tokens_per_device,
217:                 group=self.args.expert_parallel_group,
218:                 async_op=True,
219:             )
220:  
221:         x_sfd, top_experts_sfd, expert_weights_sfd = self.pre_dispatch_assign_re_idx(x, \
222:             top_experts.reshape(-1, self.top_k), expert_weights, re_idx_mat_0)
223: 
224:         with torch.no_grad():
225:             tpd_handle.wait()
226:             summed_tokens_per_device_list = summed_tokens_per_device.tolist()
227:             tokens_per_device_list = tokens_per_device.tolist()
228: 
229:             summed_te_sfd, _ = all_to_all(
230:                 top_experts_sfd.to(torch.int32),
231:                 summed_tokens_per_device_list,
232:                 tokens_per_device_list,
233:                 self.args.expert_parallel_group,
234:             )
235: 
236:             summed_ew_sfd, _ = all_to_all(
237:                 expert_weights_sfd,
238:                 summed_tokens_per_device_list,
239:                 tokens_per_device_list,
240:                 self.args.expert_parallel_group,
241:             )
242: 
243:             re_idx_mat_1, re_idx_mat_w = self.post_dispatch(summed_te_sfd.to(torch.int16), summed_ew_sfd)
244: 
245:         summed_x_sfd, _ = all_to_all(
246:             x_sfd,
247:             summed_tokens_per_device_list,
248:             tokens_per_device_list,
249:             self.args.expert_parallel_group,
250:         )
251: 
252:         summed_x_sfd_output = self.expert_compute(
253:             summed_x_sfd,
254:             re_idx_mat_1, 
255:             re_idx_mat_w,
256:         )
257: 
258:         x, _ = all_to_all(
259:             summed_x_sfd_output,
260:             tokens_per_device_list,
261:             summed_tokens_per_device_list,
262:             self.args.expert_parallel_group,
263:         )
264: 
265:         x = ops.post_combine_merge_r(x, re_idx_mat_0)
266: 
267:         return x.to(orig_dtype), None
268: 
269:     def forward(self, x: torch.Tensor, scores: torch.Tensor, expert_weights: torch.Tensor, top_experts: torch.Tensor):
270:         in_shape = x.size()
271: 
272:         # Compute the experts.
273:         x, tokens_per_expert = self.forward_fn(x, expert_weights, top_experts)
274: 
275:         if self.training and self.args.moe_loss_weight > 0:
276:             save_load_balancing_loss((tokens_per_expert, scores))
277:         x = x.view(in_shape)
278:         if self.bias is not None:
279:             if self.args.return_bias:
280:                 return x, self.bias
342: class dMoE(torch.nn.Module):
343: 
344:     def __init__(self, args: Arguments):
345:         super(dMoE, self).__init__()
346: 
347:         # Token router.
348:         self.router = router.LearnedRouter(args)
349: 
350:         # Expert computation helper.
351:         self.experts = self._init_experts_mlp(args)
352: 
353:     def _init_experts_mlp(self, args: Arguments):
354:         return ParallelDroplessMLP(args)
355: 
356:     def collaboration_encourage(self, 
357:             scores: torch.Tensor,
358:             max_devices_per_tok: int,
359:             router_based: bool = True
360:     ):
361:         sorted_weights, sorted_experts = torch.sort(scores, descending=True, dim=1)
362:         local_experts = self.experts.global_expert_list.reshape(self.experts.world_size, -1)
363: 
364:         if router_based:
365:             dist, selected_exps = ops.re_routing_dist(sorted_weights, sorted_experts, \
366:                     local_experts, max_devices_per_tok, self.experts.top_k)
367:         else:
368:             dist, selected_exps = ops.sim_based_routing(sorted_weights, sorted_experts, \
369:                     local_experts, self.experts.table_exps, self.experts.table_devs, \
370:                             max_devices_per_tok, self.experts.top_k)
371: 
372:         return selected_exps, dist
373: 
374:     def forward(self, 
375:             x: torch.Tensor, 
376:             scores = None, 
377:             expert_weights = None, 
378:             top_experts = None
379:     ):
380:         # NOTE: If we're going to cast the activations to lower precision
381:         # do it before we permute the tokens to save bandwidth.
382:         x = common.cast_if_autocast_enabled(x)
383: 
384:         if (scores == None or expert_weights == None or top_experts == None):
385:             # Compute the expert scores and assignments.
386:             scores, expert_weights, top_experts = self.router(x)
387: 
388:         # Compute the experts.
389:         out = self.experts(x, scores, expert_weights, top_experts)
390: 
391:         return out
occult/layers/glu.py SHA256 9bda248596d333d1b14c624f27d42df858df92132de87a43e8e7b0f51ffe58b2
188:     def forward(self, x, brim, brim_w):
189:         w1, v1, w2 = self.scale_grad(self.w1), self.scale_grad(self.v1,), self.scale_grad(self.w2)
190:         w1, v1, w2 = resolve_dtensor(w1), resolve_dtensor(v1,), resolve_dtensor(w2)
191:         w1, v1, w2 = w1.reshape(self.num_local_experts, self.num_ffn_hidden_size, self.num_hidden_size), \
192:                         v1.reshape(self.num_local_experts, self.num_ffn_hidden_size, self.num_hidden_size), \
193:                         w2.reshape(self.num_local_experts, self.num_ffn_hidden_size, self.num_hidden_size)
194: 
195:         with torch.no_grad():
196:             exps_list, tiles_list_sfd, tiles_list_epd, tiles_list_w, exp_bounds = \
197:                 ops.brim_condense(brim, brim_w)
198:         
199:         x1, x2 = ops.fused_sfd_to_epd_condense(x, w1.permute(0, 2, 1), v1.permute(0, 2, 1), \
200:             exp_bounds, exps_list, tiles_list_sfd, tiles_list_epd)
201: 
202:         x1 = torch.mul(self.args.activation_fn(x1), x2)
203: 
204:         y = ops.epd_to_sfd_condense(x1, w2, x.shape[0], \
205:             exp_bounds, exps_list, tiles_list_sfd, tiles_list_epd, tiles_list_w)
206: 
207:         return y
occult/ops/pre_dispatch.py SHA256 424d2484764b4ce728a947a97a118a140d600f0de48e7d897ad131e789e135c2
24: class PreDispatchAssignReIdxOp(torch.autograd.Function):
25: 
26:     @staticmethod
27:     def forward(ctx: Any, \
28:                 x: torch.Tensor, \
29:                 te: torch.Tensor, \
30:                 ew: torch.Tensor, \
31:                 re_idx_mat: torch.Tensor, \
32:                 num_sfd_toks: int) -> torch.Tensor:
33:         
34:         num_features = x.shape[1]
35:         top_k = te.shape[1]
36: 
37:         ctx.save_for_backward(re_idx_mat)
38: 
39:         x_sfd = torch.empty(num_sfd_toks, num_features, dtype=x.dtype, device=x.device)
40:         te_sfd = torch.empty(num_sfd_toks, top_k, dtype=te.dtype, device=te.device)
41:         ew_sfd = torch.empty(num_sfd_toks, top_k, dtype=ew.dtype, device=ew.device)
42: 
43:         kernels_sfd.fused_pre_dispatch_assign_r(x_sfd, te_sfd, ew_sfd, x, te, ew, re_idx_mat)
44: 
45:         return x_sfd, te_sfd, ew_sfd
46: 
47:     @staticmethod
48:     def backward(ctx, x_sfd_grad, te_sfd_grad, ew_sfd_grad):
49:         # Sum the sfd grad of x using re_idx_mat
50:         re_idx_mat = ctx.saved_tensors[0]
51: 
52:         num_orig_toks = re_idx_mat.shape[0]
53:         num_features = x_sfd_grad.shape[1]
54: 
55:         x_grad_merged = torch.empty(num_orig_toks, num_features, dtype=x_sfd_grad.dtype, device=x_sfd_grad.device)
56: 
57:         kernels_sfd.merge_with_sum(x_grad_merged, x_sfd_grad, re_idx_mat)
58: 
59:         return x_grad_merged, None, None, None, None
60: 
61: 
62: pre_dispatch = PreDispatch0Op.apply
63: pre_dispatch_assign_re_idx = PreDispatchAssignReIdxOp.apply
occult/ops/condense.py SHA256 22eacfb3dcb035de9d78c423893560289e3c23bd5a667a87ab6f0a7541dd0ae2
75:         return input_sfd_grad.to(output_epd_w_grad.dtype), w_grad, v_grad, None, None, None, None
76:         
77: 
78: # NOTE: Does not support gradients.
79: class Epd2SfdCondenseOp(torch.autograd.Function):
80: 
81:     @staticmethod
82:     def forward(ctx: Any, \
83:                 input_epd: torch.Tensor, \
84:                 weights: torch.Tensor, \
85:                 num_sfd_tokens: int, \
86:                 exp_bounds: torch.Tensor, \
87:                 exps_list: torch.Tensor, \
88:                 tiles_list_sfd: torch.Tensor, \
89:                 tiles_list_epd: torch.Tensor, \
90:                 tiles_list_w: torch.Tensor) -> torch.Tensor:
91:         
92:         # assert input_epd.shape[0] == tiles_list_epd.numel() - torch.sum(tiles_list_epd < 0).item() and \
93:         #     input_epd.shape[1] == weights.shape[1] and \
94:         #     weights.shape[0] == (1 + torch.max(exps_list)).to(torch.int32).item()
95: 
96:         exp_bounds = torch.cat(
97:             (torch.zeros(1, dtype=torch.int32, device=exp_bounds.device), exp_bounds)
98:         ).contiguous()
99: 
100:         ctx.save_for_backward(exp_bounds, exps_list, tiles_list_sfd, tiles_list_epd, tiles_list_w, input_epd, weights)
101: 
102:         output_sfd = torch.zeros(num_sfd_tokens, weights.shape[2], \
103:             dtype=torch.float32, device=input_epd.device)
104: 
105:         kernels_mm_condense.epd_to_sfd_condense(output_sfd, input_epd, weights, \
106:             exps_list, tiles_list_sfd, tiles_list_epd, tiles_list_w)
107: 
108:         return output_sfd.to(input_epd.dtype)
109: 
110:     @staticmethod
111:     def backward(ctx, output_sfd_grad):
112:         # backward and merge
113:         exp_bounds, exps_list, tiles_list_sfd, tiles_list_epd, tiles_list_w, input_epd, weights = ctx.saved_tensors
114: 
115:         num_epd_tokens = input_epd.shape[0]
116:         num_in_features = weights.shape[1]
117: 
118:         input_epd_grad = torch.empty(num_epd_tokens, num_in_features, \
119:             dtype=output_sfd_grad.dtype, device=output_sfd_grad.device)
120:         weights_grad = torch.empty_like(weights)
121: 
122:         kernels_mm_condense.fused_sfd_to_epd_backward_condense(input_epd_grad, weights_grad, \
123:             input_epd, weights, output_sfd_grad, exp_bounds, exps_list, tiles_list_sfd, tiles_list_epd, tiles_list_w)
124: 
125:         return input_epd_grad, weights_grad, None, None, None, None, None, None
126: 
127: 
128: fused_sfd_to_epd_condense = FusedSfd2EpdCondenseOp.apply
129: epd_to_sfd_condense = Epd2SfdCondenseOp.apply
occult/backend/kernels_mm_condense.py SHA256 954b762ace6fb0e94045a85b4bd39c9e5424ef1d989bf9fb1b28de116a6eff5c
495:         a = tl.load(toks_epd_ptrs, mask=mask_tok_epd, other=0.0)
496:         b = tl.load(w_ptrs, mask=mask_w, other=0.0)
497: 
498:         accumulator = tl.dot(a, b, accumulator)
499: 
500:         toks_epd_ptrs += BLOCK_SIZE_K * input_epd_stride_1
501:         w_ptrs += BLOCK_SIZE_K * weights_stride_1
502:     
503:     ew_vals = tl.load(tiles_list_w + pid_m * tiles_list_w_stride_0 + t_ids[:] * tiles_list_w_stride_1).to(tl.float32)
504: 
505:     c = ew_vals[:, None] * accumulator
506: 
507:     toks_sfd_ptrs = output_sfd + toks_sfd_ids[:, None] * output_sfd_stride_0 + offs_out[None, :] * output_sfd_stride_1
508:     mask_write = (toks_epd_ids[:, None] >= 0) & (offs_out[None, :] < NUM_FEATURES_OUT)
509: 
510:     tl.atomic_add(toks_sfd_ptrs, c, mask=mask_write)
511: 
512: 
513: def epd_to_sfd_condense(output_sfd, input_epd, weights, exps_list, tiles_list_sfd, tiles_list_epd, tiles_list_w):
occult/layers/all_to_all.py SHA256 7b08a5e53a801f804c22e8d31882674c0ee79073a07dc711be481b901736146a
1: import torch
2: import torch.distributed as dist
3: 
4: 
5: class AllToAllOp(torch.autograd.Function):
6: 
7:     @staticmethod
8:     def forward(ctx, x, output_split_sizes, input_split_sizes, group, async_op):
9:         out = torch.empty((sum(output_split_sizes),) + x.shape[1:], device=x.device, dtype=x.dtype)
10: 
11:         ctx.input_shape = x.shape
12:         ctx.output_split_sizes = output_split_sizes
13:         ctx.input_split_sizes = input_split_sizes
14:         ctx.group = group
15:         handle = dist.all_to_all_single(
16:             out,
17:             x,
18:             output_split_sizes=output_split_sizes,
19:             input_split_sizes=input_split_sizes,
20:             group=group,
21:             async_op=async_op,
22:         )
23:         return out, handle
24: 
25:     @staticmethod
26:     def backward(ctx, grad, _):
27:         if ctx.needs_input_grad[0]:
28:             out = torch.empty(
29:                 ctx.input_shape,
30:                 device=grad.device,
31:                 dtype=grad.dtype,
32:             )
33:             dist.all_to_all_single(
34:                 out,
35:                 grad,
36:                 output_split_sizes=ctx.input_split_sizes,
37:                 input_split_sizes=ctx.output_split_sizes,
38:                 group=ctx.group,
39:             )
40:             return out, None, None, None, None
41:         return None, None, None, None, None
42: 
43: 
44: def all_to_all(x, output_split_sizes, input_split_sizes, group, async_op=False):
45:     return AllToAllOp.apply(
46:         x,
47:         output_split_sizes,
48:         input_split_sizes,
49:         group,
50:         async_op,
51:     )
csrc/graph.h SHA256 dbec47b3b9af1c19e4023508039b0c64d5cf6d926d128290147faf8e84e8d53e
20: __global__ void BuildCollaborateGraphKernel(
21:         int * __restrict__ graph,
22:         const short * __restrict__ te,
23:         int kTokensPerBlock,
24:         int num_tokens,
25:         int top_k,
26:         int num_experts) {
27:   int tok_chunk_start = kTokensPerBlock * blockIdx.x;
28: 
29:   for (int i = 0; i < kTokensPerBlock; i += 1) {
30:     int tok_idx = tok_chunk_start + i;
31:     if (tok_idx < num_tokens) {
32:         for (int j = 0; j < top_k; j += 1) {
33:             for (int k = 0; k < top_k; k += 1) {
34:                 if (k != j) {
35:                     at::native::fastAtomicAdd(graph, te[tok_idx * top_k + j] * num_experts + te[tok_idx * top_k + k], \
36:                         num_experts * num_experts, 1, true);
37:                 }
38:             }
39:         }
40:     }
41:   }
42: }
examples/deepseek-moe-16b-base/modeling_deepseek.py SHA256 f15c4e25d418a7327414f5487f1f36db7d3784adb9fb8b8a4c6bb658f50bd116
285:     def __init__(self, config):
286:         super().__init__()
287:         self.config = config
288:         self.top_k = config.num_experts_per_tok
289:         self.n_routed_experts = config.n_routed_experts
290: 
291:         self.scoring_func = config.scoring_func
292:         self.alpha = config.aux_loss_alpha
293:         self.seq_aux = config.seq_aux
294: 
295:         # topk selection algorithm
296:         self.norm_topk_prob = config.norm_topk_prob
297:         self.gating_dim = config.hidden_size
298:         self.weight = nn.Parameter(torch.empty((self.n_routed_experts, self.gating_dim)))
299:         self.reset_parameters()
300: 
301:     def reset_parameters(self) -> None:
302:         import torch.nn.init  as init
303:         init.kaiming_uniform_(self.weight, a=math.sqrt(5))
304:     
305:     def forward(self, hidden_states):
306:         bsz, seq_len, h = hidden_states.shape        
307:         ### compute gating score
308:         hidden_states = hidden_states.view(-1, h)
309:         logits = F.linear(hidden_states, self.weight, None)
310:         if self.scoring_func == 'softmax':
311:             scores = logits.softmax(dim=-1)
312:         else:
313:             raise NotImplementedError(f'insupportable scoring function for MoE gating: {self.scoring_func}')
314:         
315:         ### select top-k experts (change to sorted=True)
316:         topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=True)
317:         
318:         ### norm gate to sum 1
319:         if self.top_k > 1 and self.norm_topk_prob:
320:             denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
321:             topk_weight = topk_weight / denominator
322: 
323:         ### expert-level computation auxiliary loss
324:         if self.training and self.alpha > 0.0:
325:             scores_for_aux = scores
326:             aux_topk = self.top_k
327:             # always compute aux loss based on the naive greedy topk method
328:             topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
329:             if self.seq_aux:
330:                 scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
331:                 ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
332:                 ce.scatter_add_(1, topk_idx_for_aux_loss, torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)).div_(seq_len * aux_topk / self.n_routed_experts)
333:                 aux_loss = (ce * scores_for_seq_aux.mean(dim = 1)).sum(dim = 1).mean() * self.alpha
334:             else:
335:                 mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
336:                 ce = mask_ce.float().mean(0)
337:                 Pi = scores_for_aux.mean(0)
338:                 fi = ce * self.n_routed_experts
339:                 aux_loss = (Pi * fi).sum() * self.alpha
340:         else:
341:             aux_loss = None
342:         return topk_idx, topk_weight, aux_loss, scores
343: 
344: 
345: class AddAuxiliaryLoss(torch.autograd.Function):
353:         ctx.dtype = loss.dtype
354:         ctx.required_aux_loss = loss.requires_grad
355:         return x
356: 
357:     @staticmethod
358:     def backward(ctx, grad_output):
359:         grad_loss = None
360:         if ctx.required_aux_loss:
361:             grad_loss = torch.ones(1, dtype=ctx.dtype, device=grad_output.device)
362:         return grad_output, grad_loss
363:     
407:     def forward(self, hidden_states):
408:         identity = hidden_states
409:         orig_shape = hidden_states.shape
410:         topk_idx, topk_weight, aux_loss, scores = self.gate(hidden_states)
411:         hidden_states = hidden_states.view(-1, hidden_states.shape[-1])
412: 
413:         # Router-based pruning, 2 devices
414:         topk_idx_, _ = self.experts.collaboration_encourage( \
415:                 scores.view(hidden_states.shape[0], -1).detach(), 2, router_based=True)
416:         topk_idx = topk_idx_.view(*topk_idx.shape)
417: 
418:         flat_topk_idx = topk_idx.view(-1)
419:         if self.training:
420:             # hidden_states = hidden_states.repeat_interleave(self.num_experts_per_tok, dim=0)
421:             # y = torch.empty_like(hidden_states)
422:             # for i, expert in enumerate(self.experts):
423:             #     y[flat_topk_idx == i] = expert(hidden_states[flat_topk_idx == i])
424:             # y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
425:             # y =  y.view(*orig_shape)
426:             y = self.experts(hidden_states, scores.view(hidden_states.shape[0], -1).to(hidden_states.dtype), \
427:                 topk_weight.view(hidden_states.shape[0], -1), topk_idx.view(hidden_states.shape[0], -1))
428:             y =  y.view(*orig_shape)
429:             y = AddAuxiliaryLoss.apply(y, aux_loss)
430:         else:
431:             y = self.experts(hidden_states, scores.view(hidden_states.shape[0], -1).to(hidden_states.dtype), \
432:                 topk_weight.view(hidden_states.shape[0], -1), topk_idx.view(hidden_states.shape[0], -1))
433:             y =  y.view(*orig_shape)
434:         if self.config.n_shared_experts is not None:
435:             y = y + self.shared_experts(identity)
README.md SHA256 549c10f7e7aaeff268b45d75c65fb587655a0056fbc8e4392583b1bb223b99c4
1: # Occult-MoE
2: 
3: Source code for paper "Occult: Optimizing Collaborative Communication across Experts for Accelerated Parallel MoE Training and Inference"
4: 
5: ## Overview
6: 
7: We present Occult, an algorithm-system co-design solution for communication-efficient expert parallelism. 
8: - We merge the token replicas transmitted to the same GPU into a single one to reduce all-to-all communication volume, together with a refactored matrix multiplication kernel tailored for this communication strategy to diminish unnecessary memory footprint.
9: - We reschedule the expert placement in expert parallelism using a profiling dataset, aiming at clustering the frequently co-activated experts to boost the efficient all-to-all communication.
10: - Occult can be integrated to both training and inference for MoE-based LLMs to achieve wall-clock speedup under heavy workloads.
11: 
12: ## Experiments
13: 
14: We examine the expert-parallelized training with 8- and 16- way expert parallelism using Occult, along with the evaluations on downstream tasks to validate the effectiveness of collaboration pruning.
15: 
16: ### 8-way expert parallelism (1 node)
17: 
18: Devices: 8 x NVIDIA A6000 Ada
19: 
20: #### Latency Analysis
21: 
22: <img src="https://github.com/UNITES-Lab/Occult/blob/main/figures/train_deepseek_8_way.svg" alt="Training Latency Analysis for DeepSeek-MoE with 8-way Expert Parallelism" width="600"/>
23: 
24: Caption: We demonstrate the training efficiency of Occult on DeepSeek-MoE (16B) with 8-way expert parallelism on a single node, compared with conventional expert parallelism MegaBlocks. The label "Occult (Pruning, $m$ GPUs)" denotes the $N_d$ value, $i.e.,$ pruning the expert collaboration for each token so that an individual token only activates experts within $m$ GPUs. We examine the training efficiency of MegaBlocks using both block sparse matrix multiplication and grouped GeMM.
140: Caption: We validate the effectiveness of the proposed collaboration pruning algorithms in Occult for 8-way expert parallelism with DeepSeek-MoE by evaluating on the popular benchmarks including MMLU, OpenBookQA, MathQA, RACE, and SST-2. The conclusions are similar to 4-way expert parallelism, $i.e.,$ pruning within 2 GPUs can obtain comparable performance than standard SFT with greatly improved training efficiency.
141: 
142: ### 16-way expert parallelism (2 nodes)
143: 
144: Devices: 2 x 8 x NVIDIA A6000 Ada
145: 
146: #### Latency Analysis
147: 
148: <img src="https://github.com/UNITES-Lab/Occult/blob/main/figures/train_deepseek_16_way.svg" alt="Training Latency Analysis for DeepSeek-MoE with 8-way Expert Parallelism" width="600"/>
149: 
150: Caption: We demonstrate the training efficiency of Occult on DeepSeek-MoE (16B) with 16-way expert parallelism on 2 nodes, compared with conventional expert parallelism MegaBlocks. In this case, the 64 dynamically-routed experts are scattered on 16 GPUs, $i.e.,$ 4 experts on each GPU$, which is consistent with DeepSeek-V3 (256 dynamically-routed experts and 64-way expert parallelism).
151: 
152: #### Performance Analysis
153: 
154: <table border="0">
155:   <tr>
156:     <th colspan="8" style="text-align: center;">DeepSeek-MoE Evaluation</th>
157:   </tr>
158:   </tr>
159:     <td>Task</td>
160:     <td>Strategy</td>