Closed
[WIP]Draft: feat(moe): bind prepared MoonEP targets through local runtime nodes #4142
Jia_AustinAdd on 24 days agoClosed at 23 days ago
[WIP]Draft: feat(moe): bind prepared MoonEP targets through local runtime nodes #4142
Closed
Total: 29 files changed+14318-2
| @@ -0,0 +1,41 @@ | |||
| 1 | +"""Canonical dummy handoff and mathematical padding; no expert backward shell.""" | ||
| 2 | +from .moonep_bindings import validate_routing_ids, group_metadata, context_charge | ||
| 3 | + | ||
| 4 | + | ||
| 5 | +def _dummy(params): | ||
| 6 | + from transformer_engine.pytorch.module.base import get_dummy_wgrad | ||
| 7 | + | ||
| 8 | + result = [] | ||
| 9 | + for param in params: | ||
| 10 | + value = get_dummy_wgrad(list(param.shape), param.dtype, | ||
| 11 | + zero=bool(getattr(param, 'zero_out_wgrad', False)), device=param.device) | ||
| 12 | + if (value.device != param.device or value.dtype != param.dtype or value.shape != param.shape | ||
| 13 | + or value.requires_grad): | ||
| 14 | + raise RuntimeError("immutable TENPU dummy cache mismatch") | ||
| 15 | + result.append(value) | ||
| 16 | + # Must be last: an invalid dummy must not publish any partial readiness. | ||
| 17 | + for param in params: | ||
| 18 | + param.grad_added_to_main_grad = True | ||
| 19 | + return tuple(result) | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def prewarm_dummy_cache(binding): | ||
| 23 | + """Check device and zero content once; thereafter the shared cache is read-only.""" | ||
| 24 | + import torch | ||
| 25 | + from transformer_engine.pytorch.module.base import get_dummy_wgrad | ||
| 26 | + | ||
| 27 | + for param in binding.parameters: | ||
| 28 | + for zero in (False, True): | ||
| 29 | + value = get_dummy_wgrad(list(param.shape), param.dtype, zero=zero, device=param.device) | ||
| 30 | + if (value.device != param.device or value.dtype != param.dtype or value.shape != param.shape | ||
| 31 | + or value.requires_grad): | ||
| 32 | + raise RuntimeError("preexisting TENPU dummy cache uses incompatible metadata") | ||
| 33 | + if zero and bool(torch.any(value != 0).item()): | ||
| 34 | + raise RuntimeError("preexisting TENPU zero dummy cache is contaminated") | ||
| 35 | + | ||
| 36 | + | ||
| 37 | +def _pad(hidden, probabilities, padding): | ||
| 38 | + # In-place mathematical padding, never payload repacking. No host token count. | ||
| 39 | + hidden.masked_fill_(padding[:, None], 0) | ||
| 40 | + if probabilities is not None: | ||
| 41 | + probabilities.masked_fill_(padding, 0) | ||
| @@ -0,0 +1,461 @@ | |||
| 1 | +"""Canonical expert references and immutable layer-to-provider association.""" | ||
| 2 | +from dataclasses import dataclass | ||
| 3 | +from threading import get_ident | ||
| 4 | +import weakref | ||
| 5 | + | ||
| 6 | +from .moonep_contract import required_scratch | ||
| 7 | + | ||
| 8 | + | ||
| 9 | +def context_charge(source, probabilities, profile, shape2): | ||
| 10 | + """Charge whole pinned storage and the fixed source plan/math upper bound.""" | ||
| 11 | + import torch | ||
| 12 | + | ||
| 13 | + backing = {} | ||
| 14 | + for tensor in (source, probabilities): | ||
| 15 | + if type(tensor) is not torch.Tensor or tensor.is_neg() or tensor.is_conj(): | ||
| 16 | + raise ValueError('plain source tensors without lazy views are required') | ||
| 17 | + storage = tensor.untyped_storage() | ||
| 18 | + size = storage.nbytes() | ||
| 19 | + if type(size) is not int or size <= 0: | ||
| 20 | + raise ValueError('positive physical source backing is required') | ||
| 21 | + key = (str(tensor.device), storage.data_ptr()) | ||
| 22 | + if key in backing and backing[key] != size: | ||
| 23 | + raise ValueError('source storage extent changed') | ||
| 24 | + backing[key] = size | ||
| 25 | + c, e, b, r = (profile[k] for k in ('NvS', 'E', 'B', 'R')) | ||
| 26 | + r4 = lambda n: (n + 3) // 4 * 4 | ||
| 27 | + server = profile.get('dedup_mode', 'rank') == 'server' | ||
| 28 | + plan = 4 * (r4(c) + r4(r * b) + r4(2 * (e + b)) + r4(2) | ||
| 29 | + + r4(3 * c) + r4((8 if server else 1) * c) | ||
| 30 | + + r4(r + 2 if server else 2) + r4(e + b)) | ||
| 31 | + if server and profile.get('_combine_use_udma', False): | ||
| 32 | + a = lambda size: (size + 511) // 512 * 512 | ||
| 33 | + plan += 512 + sum(a(size) for size in | ||
| 34 | + (16*c, 64*r, 128*c, 64*c, 512*r, 128*c, 64*((c+63)//64+r), 64*c)) | ||
| 35 | + # Persistent fuser outputs, explicit transport copies, and plan metadata. | ||
| 36 | + # Current-call mathematical temporaries are charged once by begin, not per live ctx. | ||
| 37 | + return (sum(backing.values()) + 8*c*shape2[1] + 10*c*shape2[0] | ||
| 38 | + + 4*profile['S']*profile['H'] + 17*c + 32*b + plan) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def owner_complete(buffer, *, peer=False): | ||
| 42 | + """Checked Q1/local completion, optionally followed by the provider fence.""" | ||
| 43 | + import torch_npu | ||
| 44 | + from mindspeed.ops.moonep_compute import require_native | ||
| 45 | + stream = binding = None | ||
| 46 | + try: | ||
| 47 | + ctx = buffer._require_ctx() | ||
| 48 | + stream = torch_npu.npu.current_stream(ctx['device']) | ||
| 49 | + stream.synchronize() | ||
| 50 | + binding = require_native() | ||
| 51 | + binding.checked_current_complete(ctx['device'], int(stream.npu_stream)) | ||
| 52 | + if peer: | ||
| 53 | + buffer.barrier_on_stream(stream) | ||
| 54 | + binding.checked_current_complete(ctx['device'], int(stream.npu_stream)) | ||
| 55 | + except BaseException as error: | ||
| 56 | + poison_owner(buffer, error, (stream, binding)) | ||
| 57 | + raise | ||
| 58 | + | ||
| 59 | + | ||
| 60 | +def configure_owner(buffer, *, sources, max_live_contexts, live_context_bytes, | ||
| 61 | + caller_stream, caller_thread): | ||
| 62 | + ctx = buffer._require_ctx() | ||
| 63 | + if ('_mindspeed_integration' in ctx or type(max_live_contexts) is not int | ||
| 64 | + or max_live_contexts <= 0 or type(live_context_bytes) is not int or live_context_bytes <= 0): | ||
| 65 | + raise RuntimeError('owner integration must be configured once with positive capacity') | ||
| 66 | + ctx['_mindspeed_integration'] = dict(sources=tuple(sources), caller_stream=int(caller_stream), | ||
| 67 | + caller_thread=caller_thread, max_live_contexts=max_live_contexts, | ||
| 68 | + live_context_bytes=live_context_bytes, math_bytes=15*ctx['NvS']*sources[0].shape[1], | ||
| 69 | + metadata_bytes=15*ctx['NvS']+25*(ctx['E']+ctx['B'])+9*(ctx['E']-ctx['B'])+38+84, | ||
| 70 | + live_plans={}, current=None) | ||
| 71 | + buffer.__dict__.setdefault('_native_storage_bindings', []).extend(sources) | ||
| 72 | + | ||
| 73 | + | ||
| 74 | +def _owner_state(buffer): | ||
| 75 | + import torch_npu | ||
| 76 | + ctx = buffer._require_ctx() | ||
| 77 | + state = ctx.get('_mindspeed_integration') | ||
| 78 | + if (state is None or torch_npu.npu.current_device() != ctx['device'] | ||
| 79 | + or get_ident() != state['caller_thread'] or | ||
| 80 | + int(torch_npu.npu.current_stream(ctx['device']).npu_stream) != state['caller_stream']): | ||
| 81 | + raise RuntimeError('MoonEP requires its configured caller thread and stream') | ||
| 82 | + return ctx, state | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def _owner_admission_diagnostic(ctx, identity, phase, plan, context_bytes, local_rejection, | ||
| 86 | + upstream_rejection, admission_cause, owner_cause): | ||
| 87 | + """Failure-only scalar facts; never mutate the owner or inspect payload.""" | ||
| 88 | + import torch_npu | ||
| 89 | + | ||
| 90 | + def scalar(value): | ||
| 91 | + if type(value) in (type(None), bool, int, str): | ||
| 92 | + return value | ||
| 93 | + if type(value) in (tuple, list): | ||
| 94 | + return [scalar(item) for item in value] | ||
| 95 | + if type(value) is dict and all(type(key) is str for key in value): | ||
| 96 | + return {key: scalar(item) for key, item in value.items()} | ||
| 97 | + return dict(type=type(value).__name__, object_id=id(value)) | ||
| 98 | + | ||
| 99 | + def error_info(error): | ||
| 100 | + try: | ||
| 101 | + message = str(error) | ||
| 102 | + except BaseException: | ||
| 103 | + message = 'UNPRINTABLE_EXCEPTION' | ||
| 104 | + return dict(type=type(error).__name__, message=message) | ||
| 105 | + | ||
| 106 | + def query(function): | ||
| 107 | + try: | ||
| 108 | + return scalar(function()) | ||
| 109 | + except BaseException as error: | ||
| 110 | + return dict(query_error=error_info(error)) | ||
| 111 | + | ||
| 112 | + state = ctx.get('_mindspeed_integration') | ||
| 113 | + live = state.get('live_plans') if type(state) is dict else None | ||
| 114 | + | ||
| 115 | + def live_state(): | ||
| 116 | + if type(live) is not dict: | ||
| 117 | + raise TypeError('owner live plans are not a plain dictionary') | ||
| 118 | + return live | ||
| 119 | + | ||
| 120 | + def current_state(): | ||
| 121 | + current = state['current'] | ||
| 122 | + if current is None or type(current) is not tuple or len(current) < 3: | ||
| 123 | + return scalar(current) if current is None else dict(type=type(current).__name__, object_id=id(current)) | ||
| 124 | + return dict(identity=current[0], phase=current[1], plan_id=id(current[2])) | ||
| 125 | + | ||
| 126 | + return dict(phase=scalar(phase), identity=scalar(identity), plan_id=id(plan), | ||
| 127 | + local_rejection=local_rejection, peer_only_rejection=not local_rejection, | ||
| 128 | + upstream_rejection=upstream_rejection, | ||
| 129 | + upstream_cause=error_info(admission_cause) if upstream_rejection and isinstance(admission_cause, BaseException) | ||
| 130 | + else ('UPSTREAM_GENERIC' if upstream_rejection else None), | ||
| 131 | + owner_cause=None if owner_cause is None else error_info(owner_cause), | ||
| 132 | + expected_thread=query(lambda: state['caller_thread']), actual_thread=query(get_ident), | ||
| 133 | + expected_device=query(lambda: ctx['device']), actual_device=query(torch_npu.npu.current_device), | ||
| 134 | + expected_stream=query(lambda: state['caller_stream']), | ||
| 135 | + actual_stream=query(lambda: int(torch_npu.npu.current_stream(ctx['device']).npu_stream)), | ||
| 136 | + current=query(current_state), | ||
| 137 | + live_keys=query(lambda: list(live_state())), live_count=query(lambda: len(live_state())), | ||
| 138 | + exact_live_plan=query(lambda: live_state().get(identity) is plan | ||
| 139 | + if type(identity) is tuple and all(type(value) is int for value in identity) else 'INVALID_IDENTITY'), | ||
| 140 | + live_charges=query(lambda: [dict(identity=key, plan_id=id(value), context_bytes=value.context_bytes) | ||
| 141 | + for key, value in live_state().items()]), | ||
| 142 | + math_bytes=query(lambda: state['math_bytes']), metadata_bytes=query(lambda: state['metadata_bytes']), | ||
| 143 | + additional_charge=scalar(context_bytes if type(phase) is str and phase == 'forward' else 0), | ||
| 144 | + live_context_bytes=query(lambda: state['live_context_bytes']), | ||
| 145 | + source_versions_expected=query(lambda: plan.source_versions), | ||
| 146 | + source_versions_actual=query(lambda: (plan.source._version, plan.source_probs._version)), | ||
| 147 | + weight_versions_expected=query(lambda: plan.weight_versions), | ||
| 148 | + weight_versions_actual=('NOT_CAPTURED_FORWARD' if type(phase) is str and phase == 'forward' else | ||
| 149 | + 'SEE_UPSTREAM_CAUSE_NOT_REQUERIED' if upstream_rejection else | ||
| 150 | + 'NOT_CAPTURED_UPPER_GUARD_PASSED' if type(phase) is str and phase == 'backward' else | ||
| 151 | + 'NOT_CAPTURED_INVALID_PHASE')) | ||
| 152 | + | ||
| 153 | + | ||
| 154 | +def begin_owner_operation(buffer, identity, phase, *, plan, context_bytes=0, admission_error=False, | ||
| 155 | + admission_cause=None): | ||
| 156 | + import torch | ||
| 157 | + ctx, error, state = buffer._ctx, bool(admission_error), None | ||
| 158 | + upstream_rejection, owner_cause = error, None | ||
| 159 | + if ctx is None or 'group' not in ctx: | ||
| 160 | + raise RuntimeError('original control context is unavailable; terminate the attempt') | ||
| 161 | + try: | ||
| 162 | + _, state = _owner_state(buffer) | ||
| 163 | + if (phase not in ('forward', 'backward') or state['current'] is not None | ||
| 164 | + or not isinstance(identity, tuple) or len(identity) != 4 | ||
| 165 | + or any(type(v) is not int or not 0 <= v < 2**63 for v in identity) | ||
| 166 | + or plan is None or type(context_bytes) is not int or context_bytes < 0): | ||
| 167 | + raise ValueError('invalid exact operation metadata') | ||
| 168 | + live = state['live_plans'] | ||
| 169 | + if ((phase == 'forward' and (identity in live or len(live) >= state['max_live_contexts'])) | ||
| 170 | + or (phase == 'backward' and live.get(identity) is not plan)): | ||
| 171 | + raise ValueError('invalid live plan/capacity') | ||
| 172 | + charged = sum(p.context_bytes for p in live.values()) + state['math_bytes'] + state['metadata_bytes'] | ||
| 173 | + if charged + (context_bytes if phase == 'forward' else 0) > state['live_context_bytes']: | ||
| 174 | + raise ValueError('live backing and current math exceed capacity') | ||
| 175 | + except (RuntimeError, ValueError, TypeError, AttributeError) as caught: | ||
| 176 | + owner_cause = caught | ||
| 177 | + error = True | ||
| 178 | + status = low = high = None | ||
| 179 | + try: | ||
| 180 | + status = torch.tensor([int(error)], dtype=torch.int32, device=f"npu:{ctx['device']}") | ||
| 181 | + torch.distributed.all_reduce(status, op=torch.distributed.ReduceOp.MAX, group=ctx['group']) | ||
| 182 | + rejected = int(status.item()) | ||
| 183 | + except BaseException as error: | ||
| 184 | + poison_owner(buffer, error, (plan, status)) | ||
| 185 | + raise | ||
| 186 | + if rejected: | ||
| 187 | + rejection = RuntimeError('rank-consistent owner operation/capacity admission rejected') | ||
| 188 | + cause = admission_cause if upstream_rejection and isinstance(admission_cause, BaseException) else owner_cause | ||
| 189 | + try: | ||
| 190 | + facts = _owner_admission_diagnostic(ctx, identity, phase, plan, context_bytes, error, | ||
| 191 | + upstream_rejection, admission_cause, owner_cause) | ||
| 192 | + rejection.add_note('local owner admission: ' + repr(facts)) | ||
| 193 | + except BaseException as diagnostic_error: | ||
| 194 | + try: | ||
| 195 | + rejection.add_note('owner diagnostic unavailable: ' + type(diagnostic_error).__name__) | ||
| 196 | + except BaseException: | ||
| 197 | + pass | ||
| 198 | + raise rejection from cause | ||
| 199 | + header = [int(phase == 'backward'), *identity] | ||
| 200 | + try: | ||
| 201 | + low = torch.tensor(header, dtype=torch.int64, device=status.device) | ||
| 202 | + high = low.clone() | ||
| 203 | + torch.distributed.all_reduce(low, op=torch.distributed.ReduceOp.MIN, group=ctx['group']) | ||
| 204 | + torch.distributed.all_reduce(high, op=torch.distributed.ReduceOp.MAX, group=ctx['group']) | ||
| 205 | + same = torch.equal(low, high) | ||
| 206 | + except BaseException as error: | ||
| 207 | + poison_owner(buffer, error, (plan, status, low, high)) | ||
| 208 | + raise | ||
| 209 | + if not same: | ||
| 210 | + raise RuntimeError('rank-consistent exact call identity differs') | ||
| 211 | + plan.context_bytes = context_bytes if phase == 'forward' else plan.context_bytes | ||
| 212 | + state['current'] = (identity, phase, plan, []) | ||
| 213 | + | ||
| 214 | + | ||
| 215 | +def require_owner_operation(buffer): | ||
| 216 | + _, state = _owner_state(buffer) | ||
| 217 | + if state['current'] is None: | ||
| 218 | + raise RuntimeError('MoonEP requires an active exact operation') | ||
| 219 | + return state['current'] | ||
| 220 | + | ||
| 221 | + | ||
| 222 | +def retain_owner_resources(buffer, resources): | ||
| 223 | + require_owner_operation(buffer)[3].append(resources) | ||
| 224 | + | ||
| 225 | + | ||
| 226 | +def end_owner_operation(buffer, identity, phase): | ||
| 227 | + scope = require_owner_operation(buffer) | ||
| 228 | + if scope[:2] != (identity, phase): | ||
| 229 | + raise RuntimeError('operation completion differs from the exact call') | ||
| 230 | + _, state = _owner_state(buffer) | ||
| 231 | + plan = scope[2] | ||
| 232 | + if phase == 'backward' and (plan.started != {0, 1} or plan.pending_heads): | ||
| 233 | + raise RuntimeError('both projection reductions must precede operation completion') | ||
| 234 | + owner_complete(buffer, peer=True) | ||
| 235 | + if phase == 'forward': | ||
| 236 | + state['live_plans'][identity] = plan | ||
| 237 | + else: | ||
| 238 | + del state['live_plans'][identity] | ||
| 239 | + state['current'] = None | ||
| 240 | + | ||
| 241 | + | ||
| 242 | +def assert_owner_quiescent(buffer): | ||
| 243 | + _, state = _owner_state(buffer) | ||
| 244 | + if state['current'] is not None or state['live_plans']: | ||
| 245 | + raise RuntimeError('live context or operation forbids update/close') | ||
| 246 | + owner_complete(buffer, peer=True) | ||
| 247 | + | ||
| 248 | + | ||
| 249 | +def poison_owner(buffer, error, resources=()): | ||
| 250 | + from mindspeed.ops.moonep_compute import mark_failed | ||
| 251 | + ctx = getattr(buffer, '_ctx', None) | ||
| 252 | + mark_failed(buffer, error, (ctx, *resources)) | ||
| 253 | + | ||
| 254 | + | ||
| 255 | +def storage_identity(tensor): | ||
| 256 | + return (tensor.untyped_storage().data_ptr(), tensor.untyped_storage().nbytes(), | ||
| 257 | + getattr(tensor.untyped_storage(), '_cdata', None), tensor.storage_offset(), | ||
| 258 | + tuple(tensor.shape), tuple(tensor.stride()), str(tensor.device), tensor.dtype) | ||
| 259 | + | ||
| 260 | + | ||
| 261 | +def _matrix(tensor, shape, dtype, device): | ||
| 262 | + if (tuple(tensor.shape) != tuple(shape) or tensor.dtype != dtype or tensor.device != device | ||
| 263 | + or not tensor.is_contiguous() or tuple(tensor.stride()) != (shape[1], 1)): | ||
| 264 | + raise ValueError("MoonEP requires a same-device row-major projection") | ||
| 265 | + | ||
| 266 | + | ||
| 267 | +def canonical_parameters(experts, profile, intervals=None): | ||
| 268 | + """Revalidate the same canonical contract before registration and binding.""" | ||
| 269 | + import torch | ||
| 270 | + import torch_npu | ||
| 271 | + | ||
| 272 | + local = profile['E'] // profile['R'] | ||
| 273 | + if local <= 0 or profile['E'] % profile['R'] or profile['B'] != local: | ||
| 274 | + raise ValueError("MoonEP requires E divisible by EP and B=L") | ||
| 275 | + layers = (experts.linear_fc1, experts.linear_fc2) | ||
| 276 | + weights = [] | ||
| 277 | + for linear in layers: | ||
| 278 | + if getattr(linear, 'weight', None) is not None or getattr(linear, 'num_gemms', local) != local: | ||
| 279 | + raise ValueError("MoonEP requires canonical per-expert registration") | ||
| 280 | + refs = tuple(linear._parameters.get('weight' + str(i)) for i in range(local)) | ||
| 281 | + if any(p is None or getattr(linear, 'weight' + str(i), None) is not p for i, p in enumerate(refs)): | ||
| 282 | + raise ValueError("canonical parameter registration/shadow changed") | ||
| 283 | + weights.append(refs) | ||
| 284 | + shapes = tuple(tuple(group[0].shape) for group in weights) | ||
| 285 | + if (any(len(shape) != 2 for shape in shapes) or shapes[0] != (2 * shapes[1][1], shapes[1][0]) | ||
| 286 | + or shapes[0][1] != profile['H']): | ||
| 287 | + raise ValueError("MoonEP supports paired FC1[2F,H]/FC2[H,F]") | ||
| 288 | + for linear, shape in zip(layers, shapes): | ||
| 289 | + if (getattr(linear, 'in_features', None) != shape[1] | ||
| 290 | + or getattr(linear, 'out_features', None) != shape[0] | ||
| 291 | + or getattr(linear, 'use_bias', None) is not False | ||
| 292 | + or getattr(linear, 'single_grouped_weight', False)): | ||
| 293 | + raise ValueError("canonical grouped module metadata differs from its Parameters") | ||
| 294 | + device = weights[0][0].device | ||
| 295 | + if str(device) != f"npu:{profile['device']}": | ||
| 296 | + raise ValueError("canonical device differs from the actual provider") | ||
| 297 | + intervals = [] if intervals is None else intervals | ||
| 298 | + grads = [] | ||
| 299 | + for group, shape in zip(weights, shapes): | ||
| 300 | + for param in group: | ||
| 301 | + if not isinstance(param, torch.nn.Parameter) or not param.requires_grad: | ||
| 302 | + raise ValueError("MoonEP requires original registered trainable Parameters") | ||
| 303 | + grad = getattr(param, 'main_grad', None) | ||
| 304 | + if type(grad) is not torch.Tensor or grad.requires_grad: | ||
| 305 | + raise ValueError("MoonEP requires ordinary non-Autograd main_grad Tensors") | ||
| 306 | + for tensor, dtype in ((param, torch.bfloat16), (grad, torch.float32)): | ||
| 307 | + _matrix(tensor, shape, dtype, device) | ||
| 308 | + if torch_npu.get_npu_format(tensor) != 2 or tensor.is_neg() or tensor.is_conj(): | ||
| 309 | + raise ValueError("MoonEP requires canonical ND tensors without lazy views") | ||
| 310 | + start = tensor.data_ptr() | ||
| 311 | + end = start + tensor.numel() * tensor.element_size() | ||
| 312 | + storage, offset = tensor.untyped_storage(), tensor.storage_offset() | ||
| 313 | + if (offset < 0 or (offset + tensor.numel()) * tensor.element_size() > storage.nbytes()): | ||
| 314 | + raise ValueError('canonical matrix exceeds its existing storage') | ||
| 315 | + if any(start < b and a < end for a, b in intervals): | ||
| 316 | + raise ValueError("canonical weight/grad targets must not overlap") | ||
| 317 | + intervals.append((start, end)) | ||
| 318 | + grads.append(grad) | ||
| 319 | + return layers, tuple(weights), tuple(grads), shapes | ||
| 320 | + | ||
| 321 | + | ||
| 322 | +@dataclass(frozen=True) | ||
| 323 | +class LayerBinding: | ||
| 324 | + buffer: object | ||
| 325 | + owners: tuple | ||
| 326 | + w1: tuple | ||
| 327 | + w2: tuple | ||
| 328 | + grads: tuple | ||
| 329 | + identities: tuple | ||
| 330 | + grad_identities: tuple | ||
| 331 | + push_bindings: tuple | ||
| 332 | + grad_bindings: tuple | ||
| 333 | + table_identities: tuple | ||
| 334 | + source_identities: tuple | ||
| 335 | + slots: tuple | ||
| 336 | + scratch: object | ||
| 337 | + budget: int | ||
| 338 | + shape1: tuple | ||
| 339 | + shape2: tuple | ||
| 340 | + | ||
| 341 | + @classmethod | ||
| 342 | + def from_experts(cls, experts, buffer, budget, sources, *, scratch): | ||
| 343 | + import torch | ||
| 344 | + | ||
| 345 | + profile = buffer._require_ctx() | ||
| 346 | + layers, (w1, w2), grads, (shape1, shape2) = canonical_parameters(experts, profile) | ||
| 347 | + local = len(w1) | ||
| 348 | + params = w1 + w2 | ||
| 349 | + device = w1[0].device | ||
| 350 | + if len(sources) != 4 or len({id(t) for t in sources}) != 4: | ||
| 351 | + raise ValueError('two weight/gradient source pairs are required') | ||
| 352 | + pushes = tuple(buffer.prepare_lplusb(tuple(w.detach() for w in group), sources[2*p]) | ||
| 353 | + for p, group in enumerate((w1, w2))) | ||
| 354 | + reductions = tuple(buffer.prepare_lplusb(grads[p*local:(p+1)*local], sources[2*p+1]) | ||
| 355 | + for p in range(2)) | ||
| 356 | + slots = tuple((push.slot, reduce.slot) for push, reduce in zip(pushes, reductions)) | ||
| 357 | + for (weight, grad), shape in zip(slots, (shape1, shape2)): | ||
| 358 | + expected = (local, *shape) | ||
| 359 | + if (tuple(weight.shape) != expected or tuple(grad.shape) != expected | ||
| 360 | + or weight.dtype != torch.bfloat16 or grad.dtype != torch.float32 | ||
| 361 | + or weight.device != device or grad.device != device | ||
| 362 | + or not weight.is_contiguous() or not grad.is_contiguous()): | ||
| 363 | + raise ValueError("provider slots do not match the registered projection") | ||
| 364 | + needed = required_scratch(2 * local, (shape1, shape2)) | ||
| 365 | + if (type(budget) is not int or budget < needed or scratch.dtype != torch.float32 | ||
| 366 | + or scratch.device != device or scratch.ndim != 1 or not scratch.is_contiguous() | ||
| 367 | + or scratch.numel() * scratch.element_size() < needed): | ||
| 368 | + raise ValueError("one shared full-G FP32 scratch backing exceeds the declared contract") | ||
| 369 | + tables = tuple((b.table, storage_identity(b.table), b.table._version) for b in (*pushes, *reductions)) | ||
| 370 | + backing = tuple((t, storage_identity(t), getattr(t, '_vmm_allocation', None)) | ||
| 371 | + for b in (*pushes, *reductions) for t in (b.slot_source, b.slot)) | ||
| 372 | + binding = cls(buffer, layers, w1, w2, tuple(grads), tuple(map(storage_identity, params)), | ||
| 373 | + tuple(map(storage_identity, grads)), pushes, reductions, tables, backing, slots, | ||
| 374 | + scratch, budget, shape1, shape2) | ||
| 375 | + buffer._native_storage_bindings.append(weakref.ref(binding)) | ||
| 376 | + return binding | ||
| 377 | + | ||
| 378 | + @property | ||
| 379 | + def parameters(self): | ||
| 380 | + return self.w1 + self.w2 | ||
| 381 | + | ||
| 382 | + @property | ||
| 383 | + def local_experts(self): | ||
| 384 | + return len(self.w1) | ||
| 385 | + | ||
| 386 | + @property | ||
| 387 | + def groups(self): | ||
| 388 | + return 2 * self.local_experts | ||
| 389 | + | ||
| 390 | + def check_identity(self): | ||
| 391 | + for owner, params in zip(self.owners, (self.w1, self.w2)): | ||
| 392 | + for index, param in enumerate(params): | ||
| 393 | + name = 'weight' + str(index) | ||
| 394 | + if owner._parameters.get(name) is not param or getattr(owner, name, None) is not param: | ||
| 395 | + raise RuntimeError("canonical parameter registration/shadow changed") | ||
| 396 | + if tuple(map(storage_identity, self.parameters)) != self.identities: | ||
| 397 | + raise RuntimeError("canonical weights moved; quiesce and explicitly rebind") | ||
| 398 | + if any(getattr(p, 'main_grad', None) is not grad for p, grad in zip(self.parameters, self.grads)): | ||
| 399 | + raise RuntimeError("canonical main_grad identity changed") | ||
| 400 | + if tuple(map(storage_identity, self.grads)) != self.grad_identities: | ||
| 401 | + raise RuntimeError("canonical main_grad storage changed") | ||
| 402 | + for prepared, (table, identity, version) in zip((*self.push_bindings, *self.grad_bindings), self.table_identities): | ||
| 403 | + if (prepared.table is not table or storage_identity(table) != identity or table._version != version): | ||
| 404 | + raise RuntimeError('prepared pointer table was rebound or mutated') | ||
| 405 | + prepared.validate_refs(prepared.refs) | ||
| 406 | + for source, identity, allocation in self.source_identities: | ||
| 407 | + if (storage_identity(source) != identity | ||
| 408 | + or getattr(source, '_vmm_allocation', None) is not allocation | ||
| 409 | + or getattr(allocation, '_destroyed', False)): | ||
| 410 | + raise RuntimeError('prepared slot source/backing was rebound or destroyed') | ||
| 411 | + | ||
| 412 | + def refs(self, projection): | ||
| 413 | + home = (self.w1, self.w2)[projection] | ||
| 414 | + return tuple(p.detach() for p in home) + tuple(self.slots[projection][0].unbind(0)) | ||
| 415 | + | ||
| 416 | + def targets(self, projection): | ||
| 417 | + first = projection * self.local_experts | ||
| 418 | + return self.grads[first:first + self.local_experts] + tuple(self.slots[projection][1].unbind(0)) | ||
| 419 | + | ||
| 420 | + def scratch_for(self, projection): | ||
| 421 | + o, i = (self.shape1, self.shape2)[projection] | ||
| 422 | + return self.scratch[:self.groups * o * i].view(self.groups, o, i) | ||
| 423 | + | ||
| 424 | + | ||
| 425 | +def agree_error(buffer, bad): | ||
| 426 | + """The only host scalar is a fixed control error, never counts or token totals.""" | ||
| 427 | + import torch | ||
| 428 | + | ||
| 429 | + ctx = buffer._require_ctx() | ||
| 430 | + status = bad.to(dtype=torch.int32).reshape(1) | ||
| 431 | + torch.distributed.all_reduce(status, op=torch.distributed.ReduceOp.MAX, group=ctx['group']) | ||
| 432 | + if int(status.item()): | ||
| 433 | + raise ValueError("rank-consistent MoonEP routing/counts admission failed") | ||
| 434 | + | ||
| 435 | + | ||
| 436 | +def validate_routing_ids(buffer, ids): | ||
| 437 | + """The original native planner owns histogram computation from these IDs.""" | ||
| 438 | + ctx = buffer._require_ctx() | ||
| 439 | + agree_error(buffer, ((ids < 0) | (ids >= ctx['E'])).any()) | ||
| 440 | + | ||
| 441 | + | ||
| 442 | +def group_metadata(buffer, cu): | ||
| 443 | + """Select empty-skippable global groups without moving any token payload.""" | ||
| 444 | + import torch | ||
| 445 | + | ||
| 446 | + ctx = buffer._require_ctx() | ||
| 447 | + e, b, c = ctx['E'], ctx['B'], ctx['NvS'] | ||
| 448 | + if (cu.ndim != 1 or cu.numel() != e + b or cu.dtype != torch.int32 | ||
| 449 | + or not cu.is_contiguous()): | ||
| 450 | + raise ValueError("provider CU must be contiguous device INT32[E+B]") | ||
| 451 | + total = cu.to(torch.int64) | ||
| 452 | + counts = torch.diff(total, prepend=torch.zeros(1, dtype=torch.int64, device=cu.device)) | ||
| 453 | + local = e // ctx['R'] | ||
| 454 | + start = ctx['rank'] * local | ||
| 455 | + foreign = torch.cat((counts[:start], counts[start + local:e])) | ||
| 456 | + bad = (counts < 0).any() | (foreign != 0).any() | (total[-1] != c) | ||
| 457 | + agree_error(buffer, bad) | ||
| 458 | + selected = torch.cat((counts[start:start + local], counts[e:])) | ||
| 459 | + selected[-1] += c - total[-1] | ||
| 460 | + padding = torch.arange(c, device=cu.device) >= total[-1] | ||
| 461 | + return selected, selected.cumsum(0), padding | ||
| @@ -0,0 +1,112 @@ | |||
| 1 | +"""Import-free admission contracts for the default-off shared-slot path.""" | ||
| 2 | + | ||
| 3 | +MODE = 'mindspeed_shared_slots_full_g_v1' | ||
| 4 | +PROVIDER_SOURCE_SHA = '72b8e69a43cd13b3ddbea095620af35c77c6e4d1' | ||
| 5 | +PROVIDER_BASE_SHA = 'd8b9db58ca13e2e8545575034f8f57b956fee342' | ||
| 6 | +TENPU_SOURCE_SHA = 'f3ce68ba3244720ead26a25d5b388c38293b730c' | ||
| 7 | +ACTIVATION_PROFILE = 'copy-counted-v1' | ||
| 8 | +S1_CAPABILITIES = ('standard_math', 'fuser_autograd', 'gmm_direct_out', 'no_weight_pack') | ||
| 9 | +S2_CAPABILITIES = ('native_planner_counts', 'model_tp_layout', 'cp_layout', 'urma_push', | ||
| 10 | + 'urma_gr', 'r1_exact_plan', 'resource_lifecycle', 'discrete_canonical_targets') | ||
| 11 | +RUNTIME_CAPABILITIES = S1_CAPABILITIES + S2_CAPABILITIES | ||
| 12 | +PROVIDER_RUNTIME_KEYS = ('dedup_mode', 'ranks_per_server', 'num_sms', 'planning_num_sms', | ||
| 13 | + 'grad_reduce_num_sms', 'num_sms_dedup', 'vmm_page_size', 'prefetch_barrier_mode', | ||
| 14 | + 'async_stream_barrier_mode', '_planning_use_udma', '_dispatch_use_udma', | ||
| 15 | + '_combine_use_udma', '_prefetch_use_udma', '_grad_reduce_use_udma') | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def provider_runtime(ctx): | ||
| 19 | + return {name: ctx[name] for name in PROVIDER_RUNTIME_KEYS} | ||
| 20 | + | ||
| 21 | + | ||
| 22 | +def enabled(options): | ||
| 23 | + return getattr(options, 'moonep_compute_mode', 'off') == MODE | ||
| 24 | + | ||
| 25 | + | ||
| 26 | +def validate_options(options): | ||
| 27 | + mode = getattr(options, 'moonep_compute_mode', 'off') | ||
| 28 | + if mode not in ('off', MODE): | ||
| 29 | + raise ValueError(f'unsupported MoonEP compute mode: {mode}') | ||
| 30 | + if mode == 'off': | ||
| 31 | + return | ||
| 32 | + if getattr(options, 'moonep_dedup_mode', 'rank') not in ('rank', 'server'): | ||
| 33 | + raise ValueError('MoonEP dedup mode must be rank or server') | ||
| 34 | + if getattr(options, 'moe_token_dispatcher_type', None) != 'flex': | ||
| 35 | + raise ValueError('MoonEP requires the flex dispatcher') | ||
| 36 | + if getattr(options, 'moe_flex_dispatcher_backend', None) != 'moonep': | ||
| 37 | + raise ValueError('MoonEP requires the moonep backend') | ||
| 38 | + if getattr(options, 'moonep_wgrad_scratch_bytes', 0) <= 0: | ||
| 39 | + raise ValueError('MoonEP requires a positive explicit wgrad scratch budget') | ||
| 40 | + if not getattr(options, 'moe_grouped_gemm', False): | ||
| 41 | + raise ValueError('MoonEP requires grouped experts') | ||
| 42 | + validate_model_config(options) | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +def validate_model_config(config): | ||
| 46 | + """Reject unsupported mathematics before parameters or collectives exist.""" | ||
| 47 | + if getattr(config, 'expert_tensor_parallel_size', 1) != 1: | ||
| 48 | + raise ValueError('MoonEP requires expert tensor parallel size 1') | ||
| 49 | + if not getattr(config, 'bf16', False): | ||
| 50 | + raise ValueError('MoonEP requires BF16 experts') | ||
| 51 | + if getattr(config, 'add_bias_linear', False): | ||
| 52 | + raise ValueError('MoonEP requires bias-free experts') | ||
| 53 | + if not getattr(config, 'gated_linear_unit', getattr(config, 'swiglu', False)): | ||
| 54 | + raise ValueError('MoonEP requires default SwiGLU') | ||
| 55 | + activation = getattr(config, 'activation_func', None) | ||
| 56 | + if activation is not None and getattr(activation, '__name__', '') != 'silu': | ||
| 57 | + raise ValueError('MoonEP requires silu gate activation') | ||
| 58 | + if getattr(config, 'moe_router_dtype', None) != 'fp32': | ||
| 59 | + raise ValueError('MoonEP requires FP32 router probabilities') | ||
| 60 | + balancing = getattr(config, 'moe_router_load_balancing_type', None) | ||
| 61 | + if balancing == 'sinkhorn' or (isinstance(balancing, (list, tuple)) and 'sinkhorn' in balancing): | ||
| 62 | + raise ValueError('MoonEP compact routing does not support sinkhorn') | ||
| 63 | + for name in ( | ||
| 64 | + 'fp8', 'fp4', 'fp16', 'moe_router_fusion', 'moe_router_enable_expert_bias', | ||
| 65 | + 'moe_pad_expert_input_to_capacity', 'moe_apply_probs_on_input', | ||
| 66 | + 'moe_shared_expert_overlap', 'overlap_dispatch_backward_with_experts_wgrad', | ||
| 67 | + 'overlap_moe_expert_parallel_comm', 'rampup_batch_size', | ||
| 68 | + 'delay_wgrad_compute', 'moe_use_op_fuser', 'moe_fb_overlap', 'moe_fwd_bwd_overlap', | ||
| 69 | + 'use_transformer_engine_op_fuser', 'moe_mlp_glu_interleave_size', | ||
| 70 | + 'activation_func_fp8_input_store', 'activation_func_tanh_clamp_scale', | ||
| 71 | + 'activation_func_tanh_clamp_scale_linear', | ||
| 72 | + 'fine_grained_activation_offloading', 'cpu_offloading', | ||
| 73 | + 'use_torch_fsdp2', 'use_custom_fsdp', 'use_megatron_fsdp', | ||
| 74 | + 'moe_expert_capacity_factor', 'glu_linear_offset', 'activation_func_clamp_value', | ||
| 75 | + 'glu_interleave_size', 'moe_latent_size', | ||
| 76 | + ): | ||
| 77 | + if getattr(config, name, False): | ||
| 78 | + raise ValueError(f'MoonEP does not support {name}') | ||
| 79 | + if getattr(config, 'recompute_granularity', None): | ||
| 80 | + raise ValueError('MoonEP does not support activation recomputation') | ||
| 81 | + if getattr(config, 'cuda_graph_impl', 'none') not in (None, 'none'): | ||
| 82 | + raise ValueError('MoonEP does not support graph capture') | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +def required_scratch(groups, shapes): | ||
| 86 | + if isinstance(groups, bool) or not isinstance(groups, int) or not 0 < groups <= 128: | ||
| 87 | + raise ValueError('MoonEP groups must be in [1,128]') | ||
| 88 | + if len(shapes) != 2: | ||
| 89 | + raise ValueError('MoonEP requires FC1 and FC2 shapes') | ||
| 90 | + sizes = [] | ||
| 91 | + for shape in shapes: | ||
| 92 | + if len(shape) != 2 or any(isinstance(v, bool) or not isinstance(v, int) or v <= 0 for v in shape): | ||
| 93 | + raise ValueError('MoonEP projection shapes must be positive 2D integers') | ||
| 94 | + sizes.append(shape[0] * shape[1]) | ||
| 95 | + return 4 * groups * max(sizes) | ||
| 96 | + | ||
| 97 | + | ||
| 98 | +def validate_attestation(attestation): | ||
| 99 | + """An absent or merely source-level capability never enables training.""" | ||
| 100 | + if not isinstance(attestation, dict): | ||
| 101 | + raise RuntimeError('MoonEP requires an explicit installed-runtime attestation') | ||
| 102 | + if attestation.get('mode') != MODE or attestation.get('native_abi') != 2: | ||
| 103 | + raise RuntimeError('MoonEP attestation mode/ABI mismatch') | ||
| 104 | + if attestation.get('training_integration_ready') is not True: | ||
| 105 | + raise RuntimeError('MoonEP training integration remains disabled') | ||
| 106 | + if attestation.get('activation_profile') != ACTIVATION_PROFILE: | ||
| 107 | + raise RuntimeError('MoonEP requires explicit copy-counted activation admission') | ||
| 108 | + if attestation.get('validation_status') != 'PASS': | ||
| 109 | + raise RuntimeError('MoonEP runtime validation has not passed') | ||
| 110 | + for key in ('standard_library', 'tenpu_identity', 'provider_identity', 'source_tuple'): | ||
| 111 | + if not attestation.get(key): | ||
| 112 | + raise RuntimeError(f'MoonEP missing attestation identity: {key}') | ||
| @@ -0,0 +1,166 @@ | |||
| 1 | +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| 2 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved. | ||
| 3 | +# See LICENSE for license information. | ||
| 4 | +"""Applicable PR7450 TEGroupedMLP construction and forward over TENPU. | ||
| 5 | + | ||
| 6 | +Donor experts.py at 9b60ad82e1b38d4829582b1a34863293db995ccf. Bias, packed | ||
| 7 | +weights, low precision, recompute, offload, paging and CUDA-only branches are | ||
| 8 | +excluded by the ordinary-profile preflight, not copied as unreachable code. | ||
| 9 | +""" | ||
| 10 | +from __future__ import annotations | ||
| 11 | + | ||
| 12 | +import weakref | ||
| 13 | +from itertools import chain | ||
| 14 | + | ||
| 15 | +import torch | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +class RuntimeTEGroupedMLP: | ||
| 19 | + """One unregistered TE compute chain; all Autograd belongs to TENPU fuser.""" | ||
| 20 | + | ||
| 21 | + def __init__(self, binding, load_balancer): | ||
| 22 | + self.binding = binding | ||
| 23 | + self.linear_fc1, self.linear_fc2 = binding.owners | ||
| 24 | + self._virtual_experts = weakref.ref(load_balancer) | ||
| 25 | + self._fused_ops = None | ||
| 26 | + | ||
| 27 | + def _make_fused_impl_pre_forward_hook(self): | ||
| 28 | + """Emulate canonical submodule hooks before NPU's first weight use. | ||
| 29 | + | ||
| 30 | + Unlike the GPU op pre-hook, this executes before PUSH/version capture. | ||
| 31 | + Main gradients must already exist; lazy FSDP buffers are not supported. | ||
| 32 | + """ | ||
| 33 | + def forward_pre_hook(module, *_) -> None: | ||
| 34 | + for submodule in chain(self.linear_fc1.modules(), self.linear_fc2.modules()): | ||
| 35 | + for hook in submodule._forward_pre_hooks.values(): | ||
| 36 | + # Assume that hook does not interact with input | ||
| 37 | + ret = hook(submodule, None) | ||
| 38 | + if ret is not None: | ||
| 39 | + raise RuntimeError( | ||
| 40 | + f"Applying a fused implementation for {self.__class__.__name__}, " | ||
| 41 | + f"but a {submodule.__class__.__name__} submodule " | ||
| 42 | + "has a pre-forward hook that modifies the input tensor." | ||
| 43 | + ) | ||
| 44 | + return forward_pre_hook | ||
| 45 | + | ||
| 46 | + def prepare_forward(self): | ||
| 47 | + self._make_fused_impl_pre_forward_hook()(self) | ||
| 48 | + | ||
| 49 | + def _make_fused_ops(self) -> torch.nn.Module: | ||
| 50 | + """Construct fused module for FC1, activation, and FC2.""" | ||
| 51 | + import transformer_engine as te | ||
| 52 | + from .moonep_ops import GroupedLinear, ScaledSwiGLU | ||
| 53 | + from .virtual_expert_load_balancer import _VirtualExpertFC2WgradStore | ||
| 54 | + | ||
| 55 | + def register_grouped_linear_params(op, weights): | ||
| 56 | + # GPU shadows linear.weight{i}; NPU borrows refs without changing | ||
| 57 | + # canonical attributes or the original model's parameter registry. | ||
| 58 | + op.register_parameter("weight", None) | ||
| 59 | + for idx, weight in enumerate(weights): | ||
| 60 | + op.register_parameter(f"weight{idx}", weight) | ||
| 61 | + | ||
| 62 | + # Container for fusible ops | ||
| 63 | + ops = te.pytorch.ops.Sequential() | ||
| 64 | + fc1_weight_dtype = self.linear_fc1.weight0.dtype | ||
| 65 | + fc2_weight_dtype = self.linear_fc2.weight0.dtype | ||
| 66 | + load_balancer = self._virtual_experts() | ||
| 67 | + if load_balancer is None: | ||
| 68 | + raise RuntimeError('expert load balancer was released before compute') | ||
| 69 | + runtime_experts = load_balancer.num_runtime_experts | ||
| 70 | + | ||
| 71 | + # Create a parameterless op shell and then attach the existing GroupedLinear weights below. | ||
| 72 | + # Using meta avoids allocating duplicate weights for the fused wrapper. | ||
| 73 | + op = GroupedLinear( | ||
| 74 | + runtime_experts, | ||
| 75 | + self.linear_fc1.in_features, | ||
| 76 | + self.linear_fc1.out_features, | ||
| 77 | + bias=self.linear_fc1.use_bias, | ||
| 78 | + device="meta", | ||
| 79 | + dtype=fc1_weight_dtype, | ||
| 80 | + accumulate_into_main_grad=True, | ||
| 81 | + single_grouped_weight=False, | ||
| 82 | + single_grouped_bias=False, | ||
| 83 | + delay_wgrad_compute=False, | ||
| 84 | + ) | ||
| 85 | + register_grouped_linear_params(op, load_balancer.runtime_weights(0)) | ||
| 86 | + ops.append(op) | ||
| 87 | + | ||
| 88 | + # Default SwiGLU only. RuntimeActivationSpec keeps FP32 probability math. | ||
| 89 | + op = ScaledSwiGLU(glu_interleave_size=None) | ||
| 90 | + ops.append(op) | ||
| 91 | + | ||
| 92 | + # FC2 | ||
| 93 | + op = GroupedLinear( | ||
| 94 | + runtime_experts, | ||
| 95 | + self.linear_fc2.in_features, | ||
| 96 | + self.linear_fc2.out_features, | ||
| 97 | + bias=self.linear_fc2.use_bias, | ||
| 98 | + device="meta", | ||
| 99 | + dtype=fc2_weight_dtype, | ||
| 100 | + accumulate_into_main_grad=True, | ||
| 101 | + single_grouped_weight=False, | ||
| 102 | + single_grouped_bias=False, | ||
| 103 | + delay_wgrad_compute=False, | ||
| 104 | + ) | ||
| 105 | + register_grouped_linear_params(op, load_balancer.runtime_weights(1)) | ||
| 106 | + op.wgrad_store = _VirtualExpertFC2WgradStore(load_balancer) | ||
| 107 | + ops.append(op) | ||
| 108 | + return ops | ||
| 109 | + | ||
| 110 | + def _fused_forward(self, permuted_local_hidden_states, tokens_per_expert, | ||
| 111 | + permuted_probs, *, plan): | ||
| 112 | + """Forward using existing operation fuser and exact-call NPU resources.""" | ||
| 113 | + from .moonep_ops import RuntimeLinearSpec, RuntimeActivationSpec | ||
| 114 | + from mindspeed.ops.moonep_compute import grouped_linear_out, reduce_sum_lastdim_out | ||
| 115 | + from .moonep_bindings import retain_owner_resources | ||
| 116 | + | ||
| 117 | + # Construct fused impl if needed | ||
| 118 | + if self._fused_ops is None: | ||
| 119 | + self._fused_ops = (self._make_fused_ops(),) | ||
| 120 | + (ops,) = self._fused_ops | ||
| 121 | + manager = self._virtual_experts() | ||
| 122 | + manager.require_forward_plan(plan) | ||
| 123 | + if tokens_per_expert is not plan.counts: | ||
| 124 | + raise RuntimeError('fused math metadata differs from the exact provider plan') | ||
| 125 | + buffer = self.binding.buffer | ||
| 126 | + profile = buffer._require_ctx() | ||
| 127 | + n, f, h = profile['NvS'], self.binding.shape2[1], self.binding.shape2[0] | ||
| 128 | + empty = lambda shape, dtype=torch.bfloat16: torch.empty( | ||
| 129 | + shape, dtype=dtype, device=permuted_local_hidden_states.device) | ||
| 130 | + z, x2, output, dx = empty((n, 2*f)), empty((n, f)), empty((n, h)), empty((n, h)) | ||
| 131 | + u2, dp = empty((n, f)), empty((n,), torch.float32) | ||
| 132 | + specs = [] | ||
| 133 | + for projection, out, dout in ((0, z, dx), (1, output, u2)): | ||
| 134 | + specs.append(RuntimeLinearSpec(plan.call_identity, projection, plan.counts, plan.prefix, | ||
| 135 | + plan.padding, self.binding.refs(projection), out, dout, | ||
| 136 | + self.binding.scratch_for(projection), | ||
| 137 | + (lambda: manager._restore_wgrad_input(plan)) if projection == 0 else None, | ||
| 138 | + manager._publish_wgrad, buffer, grouped_linear_out, | ||
| 139 | + lambda owner, x, dy, counts, prefix, scratch, p=projection: | ||
| 140 | + manager._wgrad_producer(p, owner, x, dy, counts, prefix, scratch))) | ||
| 141 | + plan.linear_specs = tuple(specs) | ||
| 142 | + act_spec = RuntimeActivationSpec(x2, dp, buffer, reduce_sum_lastdim_out) | ||
| 143 | + retain_owner_resources(buffer, (self.binding, plan, tuple(specs), act_spec)) | ||
| 144 | + # The existing fuser receives actual per-call metadata through op_kwargs; | ||
| 145 | + # unlike GPU GroupedLinear, NPU has no separate tensor split arguments. | ||
| 146 | + output = ops( | ||
| 147 | + permuted_local_hidden_states, | ||
| 148 | + permuted_probs, | ||
| 149 | + op_kwargs={0: {'runtime_spec': specs[0]}, 1: {'runtime_spec': act_spec}, | ||
| 150 | + 2: {'runtime_spec': specs[1]}}, | ||
| 151 | + ) | ||
| 152 | + return output | ||
| 153 | + | ||
| 154 | + def forward(self, permuted_local_hidden_states, tokens_per_expert, | ||
| 155 | + permuted_probs, *, plan): | ||
| 156 | + """The only enabled expert path is the existing TENPU fused op chain.""" | ||
| 157 | + try: | ||
| 158 | + output = self._fused_forward( | ||
| 159 | + permuted_local_hidden_states, tokens_per_expert, permuted_probs, plan=plan) | ||
| 160 | + output_bias = None | ||
| 161 | + return output, output_bias | ||
| 162 | + except BaseException as error: | ||
| 163 | + from .moonep_bindings import poison_owner | ||
| 164 | + poison_owner(self.binding.buffer, error, (self, plan, permuted_local_hidden_states, | ||
| 165 | + tokens_per_expert, permuted_probs)) | ||
| 166 | + raise | ||
| @@ -0,0 +1,304 @@ | |||
| 1 | +# Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| 2 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved. | ||
| 3 | +# See LICENSE for license information. | ||
| 4 | + | ||
| 5 | +"""MindSpeed-local runtime nodes over unmodified TENPU basic operations. | ||
| 6 | + | ||
| 7 | +The embedding framework supplies audited compute functions and operation | ||
| 8 | +resources. This module owns mathematical context, never transport or native | ||
| 9 | +memory completion. Runtime leaves have no canonical DDP hooks. | ||
| 10 | +""" | ||
| 11 | + | ||
| 12 | +from __future__ import annotations | ||
| 13 | + | ||
| 14 | +from dataclasses import dataclass | ||
| 15 | +from typing import Callable | ||
| 16 | + | ||
| 17 | +import torch | ||
| 18 | + | ||
| 19 | +from transformer_engine.pytorch.ops.op import BasicOperation, OperationContext | ||
| 20 | +from transformer_engine.pytorch.ops.basic.swiglu import ScaledSwiGLU as _BaseScaledSwiGLU | ||
| 21 | +from mindspeed.ops.moonep_compute import mark_failed as _provider_mark_failed | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +@dataclass(frozen=True) | ||
| 25 | +class RuntimeLinearSpec: | ||
| 26 | + """One call's borrowed operands, destinations and platform functions.""" | ||
| 27 | + | ||
| 28 | + call_identity: tuple | ||
| 29 | + projection: int | ||
| 30 | + counts: torch.Tensor | ||
| 31 | + prefix: torch.Tensor | ||
| 32 | + padding: torch.Tensor | ||
| 33 | + weight_refs: tuple | ||
| 34 | + output: torch.Tensor | ||
| 35 | + grad_input_output: torch.Tensor | ||
| 36 | + wgrad_scratch: torch.Tensor | ||
| 37 | + acquire_wgrad_input: Callable | None | ||
| 38 | + publish_wgrad: Callable | ||
| 39 | + operation_owner: object | ||
| 40 | + linear_out: Callable | ||
| 41 | + wgrad_producer: Callable | ||
| 42 | + | ||
| 43 | + | ||
| 44 | +@dataclass(frozen=True) | ||
| 45 | +class RuntimeActivationSpec: | ||
| 46 | + """Explicit destinations for the FP32-probability activation profile.""" | ||
| 47 | + | ||
| 48 | + output: torch.Tensor | ||
| 49 | + probability_grad_output: torch.Tensor | ||
| 50 | + operation_owner: object | ||
| 51 | + reduce_sum_out: Callable | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +def _matrix(tensor, shape, dtype, device): | ||
| 55 | + if (not isinstance(tensor, torch.Tensor) or tuple(tensor.shape) != tuple(shape) | ||
| 56 | + or tensor.dtype != dtype or tensor.device != device or not tensor.is_contiguous() | ||
| 57 | + or tensor.is_neg() or tensor.is_conj()): | ||
| 58 | + raise ValueError("runtime grouped linear requires declared contiguous tensor metadata") | ||
| 59 | + | ||
| 60 | + | ||
| 61 | +def _disjoint(destination, *sources): | ||
| 62 | + begin = destination.data_ptr() | ||
| 63 | + end = begin + destination.numel() * destination.element_size() | ||
| 64 | + for source in sources: | ||
| 65 | + start = source.data_ptr() | ||
| 66 | + stop = start + source.numel() * source.element_size() | ||
| 67 | + if begin < stop and start < end: | ||
| 68 | + raise ValueError("runtime output overlaps an input") | ||
| 69 | + | ||
| 70 | + | ||
| 71 | +def _binding_identity(tensor): | ||
| 72 | + return (tensor.data_ptr(), tensor.storage_offset(), tuple(tensor.shape), | ||
| 73 | + tuple(tensor.stride()), tensor.dtype, tensor.device) | ||
| 74 | + | ||
| 75 | + | ||
| 76 | +def _require_failure_owner(owner): | ||
| 77 | + if not callable(getattr(owner, "mark_failed", None)): | ||
| 78 | + raise TypeError("runtime operation owner must expose Buffer.mark_failed") | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +def _mark_runtime_failed(owner, error, *resources): | ||
| 82 | + _provider_mark_failed(owner, error, resources) | ||
| 83 | + | ||
| 84 | + | ||
| 85 | +class GroupedLinear(BasicOperation): | ||
| 86 | + """Single-token/list-weight/single-out grouped operation, default unusable. | ||
| 87 | + | ||
| 88 | + Meta parameters are replaced by borrowed runtime leaves before constructing | ||
| 89 | + Sequential's fuser. Every invocation requires an immutable runtime spec. | ||
| 90 | + """ | ||
| 91 | + | ||
| 92 | + def __init__(self, num_gemms, in_features, out_features, *, bias=False, | ||
| 93 | + device="meta", dtype=torch.bfloat16, accumulate_into_main_grad=True, | ||
| 94 | + single_grouped_weight=False, single_grouped_bias=False, | ||
| 95 | + delay_wgrad_compute=False): | ||
| 96 | + super().__init__() | ||
| 97 | + if (type(num_gemms) is not int or not 1 <= num_gemms <= 128 | ||
| 98 | + or any(type(v) is not int or v <= 0 for v in (in_features, out_features)) | ||
| 99 | + or bias or str(device) != "meta" or dtype != torch.bfloat16 | ||
| 100 | + or accumulate_into_main_grad is not True or single_grouped_weight | ||
| 101 | + or single_grouped_bias or delay_wgrad_compute): | ||
| 102 | + raise ValueError("only explicit ordinary BF16 per-expert meta shells are supported") | ||
| 103 | + self.num_gemms, self.in_features, self.out_features = num_gemms, in_features, out_features | ||
| 104 | + self.wgrad_store = None | ||
| 105 | + for index in range(num_gemms): | ||
| 106 | + self.register_parameter(f"weight{index}", torch.nn.Parameter( | ||
| 107 | + torch.empty((out_features, in_features), device="meta", dtype=dtype))) | ||
| 108 | + | ||
| 109 | + def op_forward(self, ctx: OperationContext, input_, *, | ||
| 110 | + prev_op_grad_output_quantizer=None, next_op_input_quantizer=None, | ||
| 111 | + runtime_spec=None): | ||
| 112 | + if (not isinstance(runtime_spec, RuntimeLinearSpec) | ||
| 113 | + or prev_op_grad_output_quantizer is not None | ||
| 114 | + or next_op_input_quantizer is not None): | ||
| 115 | + raise ValueError("an explicit unquantized runtime grouped spec is required") | ||
| 116 | + spec = runtime_spec | ||
| 117 | + _require_failure_owner(spec.operation_owner) | ||
| 118 | + try: | ||
| 119 | + if self.wgrad_store is not None: | ||
| 120 | + delayed = getattr(self.wgrad_store, "delay_wgrad_compute", None) | ||
| 121 | + if not callable(delayed) or delayed() is not True: | ||
| 122 | + raise ValueError("runtime wgrad store must implement the delayed producer protocol") | ||
| 123 | + weights = tuple(getattr(self, f"weight{i}") for i in range(self.num_gemms)) | ||
| 124 | + registered = tuple(self.parameters()) | ||
| 125 | + if (len(registered) != len(weights) | ||
| 126 | + or any(a is not b for a, b in zip(registered, weights)) | ||
| 127 | + or len(spec.weight_refs) != self.num_gemms): | ||
| 128 | + raise ValueError("runtime leaves must be exactly the registered grouped operands") | ||
| 129 | + _matrix(input_, (spec.output.shape[0], self.in_features), torch.bfloat16, input_.device) | ||
| 130 | + _matrix(spec.output, (input_.shape[0], self.out_features), torch.bfloat16, input_.device) | ||
| 131 | + _matrix(spec.grad_input_output, tuple(input_.shape), torch.bfloat16, input_.device) | ||
| 132 | + _matrix(spec.wgrad_scratch, (self.num_gemms, self.out_features, self.in_features), | ||
| 133 | + torch.float32, input_.device) | ||
| 134 | + for leaf, ref in zip(weights, spec.weight_refs): | ||
| 135 | + _matrix(ref, (self.out_features, self.in_features), torch.bfloat16, input_.device) | ||
| 136 | + if leaf.data_ptr() != ref.data_ptr() or tuple(leaf.shape) != tuple(ref.shape): | ||
| 137 | + raise ValueError("runtime leaf differs from the borrowed weight reference") | ||
| 138 | + for metadata in (spec.counts, spec.prefix): | ||
| 139 | + _matrix(metadata, (self.num_gemms,), torch.int64, input_.device) | ||
| 140 | + _disjoint(spec.output, input_, *spec.weight_refs, spec.counts, spec.prefix) | ||
| 141 | + _disjoint(spec.grad_input_output, input_, *spec.weight_refs) | ||
| 142 | + _disjoint(spec.wgrad_scratch, input_, spec.output, spec.grad_input_output, | ||
| 143 | + *spec.weight_refs, spec.counts, spec.prefix, spec.padding) | ||
| 144 | + ctx.runtime_spec, ctx.done = spec, False | ||
| 145 | + ctx.runtime_owner = spec.operation_owner | ||
| 146 | + ctx.weights = weights | ||
| 147 | + ctx.weight_bindings = tuple(map(_binding_identity, weights)) | ||
| 148 | + if spec.acquire_wgrad_input is None: | ||
| 149 | + ctx.save_for_backward(input_) # FC2's necessary mathematical input. | ||
| 150 | + else: | ||
| 151 | + ctx.save_for_backward() # FC1 obtains X through exact-plan R1. | ||
| 152 | + # Custom Autograd forward keeps Tensor.requires_grad flags. Native | ||
| 153 | + # primitives borrow detached metadata aliases, while ctx/spec retain | ||
| 154 | + # the original graph owners and caller-visible output identity. | ||
| 155 | + spec.linear_out(spec.operation_owner, input_.detach(), | ||
| 156 | + tuple(ref.detach() for ref in spec.weight_refs), spec.counts, | ||
| 157 | + spec.output.detach(), transpose_weights=True) | ||
| 158 | + return spec.output | ||
| 159 | + except BaseException as error: | ||
| 160 | + _mark_runtime_failed(spec.operation_owner, error, ctx, spec, input_) | ||
| 161 | + raise | ||
| 162 | + | ||
| 163 | + def op_backward(self, ctx: OperationContext, grad_output): | ||
| 164 | + if ctx.done: | ||
| 165 | + error = RuntimeError("repeated grouped backward is unsupported") | ||
| 166 | + _mark_runtime_failed(ctx.runtime_owner, error, ctx, grad_output) | ||
| 167 | + raise error | ||
| 168 | + spec = ctx.runtime_spec | ||
| 169 | + source = None | ||
| 170 | + try: | ||
| 171 | + if ctx.done or torch.is_grad_enabled(): | ||
| 172 | + raise RuntimeError("repeated or higher-order grouped backward is unsupported") | ||
| 173 | + ctx.done = True | ||
| 174 | + registered = tuple(self.parameters()) | ||
| 175 | + if (len(registered) != len(ctx.weights) | ||
| 176 | + or any(a is not b for a, b in zip(registered, ctx.weights)) | ||
| 177 | + or tuple(map(_binding_identity, ctx.weights)) != ctx.weight_bindings): | ||
| 178 | + raise RuntimeError("runtime weight binding changed while the exact call was live") | ||
| 179 | + # Shared remote payload is deliberately refilled. Canonical version | ||
| 180 | + # admission belongs to the framework before backward PUSH. | ||
| 181 | + _matrix(grad_output, tuple(spec.output.shape), torch.bfloat16, spec.output.device) | ||
| 182 | + _disjoint(spec.grad_input_output, grad_output, *spec.weight_refs) | ||
| 183 | + if spec.acquire_wgrad_input is None: | ||
| 184 | + _disjoint(spec.grad_input_output, ctx.saved_tensors[0]) | ||
| 185 | + spec.linear_out(spec.operation_owner, grad_output.detach(), | ||
| 186 | + tuple(ref.detach() for ref in spec.weight_refs), spec.counts, | ||
| 187 | + spec.grad_input_output.detach(), transpose_weights=False) | ||
| 188 | + source = (ctx.saved_tensors[0] if spec.acquire_wgrad_input is None | ||
| 189 | + else spec.acquire_wgrad_input()) | ||
| 190 | + _disjoint(source, spec.grad_input_output) | ||
| 191 | + produced = False | ||
| 192 | + | ||
| 193 | + def wgrad_gemm(x, dy): | ||
| 194 | + nonlocal produced | ||
| 195 | + if produced: | ||
| 196 | + raise RuntimeError("grouped wgrad producer cannot run twice") | ||
| 197 | + produced = True | ||
| 198 | + spec.wgrad_producer(spec.operation_owner, x.detach(), dy.detach(), spec.counts, | ||
| 199 | + spec.prefix, spec.wgrad_scratch) | ||
| 200 | + spec.publish_wgrad(spec, spec.wgrad_scratch) | ||
| 201 | + | ||
| 202 | + if self.wgrad_store is None: | ||
| 203 | + wgrad_gemm(source, grad_output) | ||
| 204 | + else: | ||
| 205 | + self.wgrad_store.put((source, grad_output), wgrad_gemm) | ||
| 206 | + if not produced: | ||
| 207 | + raise RuntimeError("ordinary runtime wgrad store must execute immediately") | ||
| 208 | + # Only the outer original-canonical hook publishes DDP readiness. | ||
| 209 | + result = spec.grad_input_output | ||
| 210 | + ctx.runtime_spec, ctx.weights, ctx.weight_bindings = None, (), () | ||
| 211 | + return result, (None,) * self.num_gemms | ||
| 212 | + except BaseException as error: | ||
| 213 | + _mark_runtime_failed(spec.operation_owner, error, ctx, spec, grad_output, source) | ||
| 214 | + raise | ||
| 215 | + | ||
| 216 | + | ||
| 217 | +class ScaledSwiGLU(_BaseScaledSwiGLU): | ||
| 218 | + """FP32 probability profile; reuse original TENPU SwiGLU kernels and fuser.""" | ||
| 219 | + | ||
| 220 | + def fuser_forward(self, basic_op_ctxs, input_, *, basic_op_extra_inputs, | ||
| 221 | + prev_op_grad_output_quantizer, next_op_input_quantizer, | ||
| 222 | + basic_op_kwargs): | ||
| 223 | + if (len(basic_op_ctxs) != 1 or len(basic_op_extra_inputs) != 1 | ||
| 224 | + or len(basic_op_extra_inputs[0]) != 1 or len(basic_op_kwargs) != 1): | ||
| 225 | + raise ValueError('runtime activation requires one context and probability input') | ||
| 226 | + return self._runtime_forward(basic_op_ctxs[0], input_, basic_op_extra_inputs[0][0], | ||
| 227 | + basic_op_kwargs[0].get('runtime_spec'), prev_op_grad_output_quantizer, | ||
| 228 | + next_op_input_quantizer) | ||
| 229 | + | ||
| 230 | + def fuser_backward(self, basic_op_ctxs, grad_output, *, basic_op_grad_extra_outputs): | ||
| 231 | + if (len(basic_op_ctxs) != 1 or len(basic_op_grad_extra_outputs) != 1 | ||
| 232 | + or len(basic_op_grad_extra_outputs[0]) != 0): | ||
| 233 | + raise ValueError('runtime activation has no extra outputs') | ||
| 234 | + return self._runtime_backward(basic_op_ctxs[0], grad_output) | ||
| 235 | + | ||
| 236 | + def _runtime_forward(self, ctx, x, probabilities, spec, previous_quantizer, next_quantizer): | ||
| 237 | + """Explicit BF16 SwiGLU with preserved FP32 probability operands.""" | ||
| 238 | + if not isinstance(spec, RuntimeActivationSpec): | ||
| 239 | + raise ValueError("invalid runtime activation spec") | ||
| 240 | + _require_failure_owner(spec.operation_owner) | ||
| 241 | + activation = activation_fp32 = None | ||
| 242 | + try: | ||
| 243 | + if (type(self).__name__ != "ScaledSwiGLU" or self.activation_recompute_in_mlp | ||
| 244 | + or previous_quantizer is not None or next_quantizer is not None | ||
| 245 | + or x.ndim != 2 or x.shape[1] % 2): | ||
| 246 | + raise ValueError("runtime profile supports ordinary unquantized SwiGLU only") | ||
| 247 | + rows, width = x.shape[0], x.shape[1] // 2 | ||
| 248 | + _matrix(x, (rows, 2 * width), torch.bfloat16, x.device) | ||
| 249 | + _matrix(probabilities, (rows,), torch.float32, x.device) | ||
| 250 | + _matrix(spec.output, (rows, width), torch.bfloat16, x.device) | ||
| 251 | + _matrix(spec.probability_grad_output, (rows,), torch.float32, x.device) | ||
| 252 | + _disjoint(spec.output, x, probabilities) | ||
| 253 | + ctx.runtime_spec, ctx.runtime_done = spec, False | ||
| 254 | + ctx.runtime_owner = spec.operation_owner | ||
| 255 | + ctx.save_for_backward(x, probabilities) | ||
| 256 | + activation = self._glu_forward(x) | ||
| 257 | + activation_fp32 = activation.float() | ||
| 258 | + activation = None # Ordinary Torch conversion owns its queued input use. | ||
| 259 | + torch.mul(activation_fp32, probabilities[:, None], out=spec.output) | ||
| 260 | + return spec.output, [()] | ||
| 261 | + except BaseException as error: | ||
| 262 | + _mark_runtime_failed(spec.operation_owner, error, ctx, spec, x, probabilities, | ||
| 263 | + activation, activation_fp32) | ||
| 264 | + raise | ||
| 265 | + | ||
| 266 | + def _runtime_backward(self, ctx, grad_output): | ||
| 267 | + if ctx.runtime_done: | ||
| 268 | + error = RuntimeError("repeated runtime activation backward") | ||
| 269 | + _mark_runtime_failed(ctx.runtime_owner, error, ctx, grad_output) | ||
| 270 | + raise error | ||
| 271 | + spec = ctx.runtime_spec | ||
| 272 | + x = probabilities = grad = activation = activation_fp32 = None | ||
| 273 | + product = scaled_grad = da = grad_input = None | ||
| 274 | + try: | ||
| 275 | + if ctx.runtime_done or torch.is_grad_enabled(): | ||
| 276 | + raise RuntimeError("repeated or higher-order runtime activation backward") | ||
| 277 | + ctx.runtime_done = True | ||
| 278 | + x, probabilities = ctx.saved_tensors | ||
| 279 | + _matrix(grad_output, tuple(spec.output.shape), torch.bfloat16, x.device) | ||
| 280 | + _disjoint(spec.probability_grad_output, grad_output, x, probabilities) | ||
| 281 | + grad = grad_output.float() | ||
| 282 | + activation = self._glu_forward(x) | ||
| 283 | + activation_fp32 = activation.float() | ||
| 284 | + activation = None | ||
| 285 | + product = grad * activation_fp32 | ||
| 286 | + activation_fp32 = None | ||
| 287 | + spec.reduce_sum_out(spec.operation_owner, product, spec.probability_grad_output) | ||
| 288 | + product = None # Direct ReduceSum callback guarantees local completion. | ||
| 289 | + # Native activation owns its mathematical result; this is neither a | ||
| 290 | + # GEMM temporary nor a copyback into a promised destination. | ||
| 291 | + scaled_grad = grad * probabilities[:, None] | ||
| 292 | + grad = None | ||
| 293 | + da = scaled_grad.to(torch.bfloat16) | ||
| 294 | + scaled_grad = None | ||
| 295 | + grad_input = self._glu_backward(da, x) | ||
| 296 | + _matrix(grad_input, tuple(x.shape), torch.bfloat16, x.device) | ||
| 297 | + ctx.runtime_spec = None | ||
| 298 | + return grad_input, [()], [(spec.probability_grad_output,)] | ||
| 299 | + except BaseException as error: | ||
| 300 | + _mark_runtime_failed(spec.operation_owner, error, ctx, spec, grad_output, | ||
| 301 | + x, probabilities, grad, activation, activation_fp32, | ||
| 302 | + product, scaled_grad, da, grad_input) | ||
| 303 | + raise | ||
| 304 | + | ||
| @@ -0,0 +1,273 @@ | |||
| 1 | +"""Validation evidence for source-prebuilt installations; never grants a device PASS.""" | ||
| 2 | +import hashlib | ||
| 3 | +import importlib | ||
| 4 | +import json | ||
| 5 | +from pathlib import Path | ||
| 6 | +import subprocess | ||
| 7 | + | ||
| 8 | +from .moonep_contract import (MODE, PROVIDER_SOURCE_SHA, PROVIDER_BASE_SHA, TENPU_SOURCE_SHA, ACTIVATION_PROFILE, | ||
| 9 | + S1_CAPABILITIES, S2_CAPABILITIES, RUNTIME_CAPABILITIES) | ||
| 10 | + | ||
| 11 | +# Admit only reviewed, implemented native drivers. No such driver is complete | ||
| 12 | +# yet; production training remains SOURCE_BLOCKED even after a validation build. | ||
| 13 | +_COMPONENT_DRIVERS = {} | ||
| 14 | +_STAGE_ASSERTIONS = {'S0': {'source_build', 'symbol_provider', 'installed_fuser'}, | ||
| 15 | + 'S1': set(S1_CAPABILITIES), 'S2': set(S2_CAPABILITIES)} | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +def file_identity(path): | ||
| 19 | + path = Path(path).resolve(strict=True) | ||
| 20 | + before = path.stat() | ||
| 21 | + digest = hashlib.sha256() | ||
| 22 | + with path.open('rb') as stream: | ||
| 23 | + for block in iter(lambda: stream.read(1024 * 1024), b''): | ||
| 24 | + digest.update(block) | ||
| 25 | + after = path.stat() | ||
| 26 | + if (before.st_ino, before.st_size, before.st_mtime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns): | ||
| 27 | + raise RuntimeError('installation changed while hashing') | ||
| 28 | + return dict(realpath=str(path), sha256=digest.hexdigest()) | ||
| 29 | + | ||
| 30 | + | ||
| 31 | +def _source(root, package): | ||
| 32 | + def git(*args): | ||
| 33 | + return subprocess.check_output(['git', '-C', str(root), *args], stderr=subprocess.DEVNULL) | ||
| 34 | + if Path(git('rev-parse', '--show-toplevel').decode().strip()).resolve() != root: | ||
| 35 | + raise RuntimeError('source-prebuilt requires its own auditable Git checkout') | ||
| 36 | + files = {} | ||
| 37 | + for name in git('ls-files', '--cached', '--others', '--exclude-standard', '--', package, | ||
| 38 | + 'setup.py', 'setup.cfg', 'pyproject.toml', 'requirements.txt', 'CMakeLists.txt').decode().splitlines(): | ||
| 39 | + if (Path(name).suffix in ('.py', '.cpp', '.h', '.json', '.cmake', '.sh', '.txt', '.hpp', '.c', '.toml', '.cfg', '.in') | ||
| 40 | + and (root / name).is_file()): | ||
| 41 | + files[name] = file_identity(root / name)['sha256'] | ||
| 42 | + changes = git('diff', '--binary', 'HEAD') | ||
| 43 | + head = git('rev-parse', 'HEAD').decode().strip() | ||
| 44 | + immutable = {'npu_patch': PROVIDER_SOURCE_SHA, 'transformer_engine': TENPU_SOURCE_SHA} | ||
| 45 | + if package in immutable: | ||
| 46 | + untracked = git('ls-files', '--others', '--exclude-standard') | ||
| 47 | + if head != immutable[package] or changes or untracked: | ||
| 48 | + raise RuntimeError(package + ' must be the unmodified fixed source') | ||
| 49 | + dirty = dict(diff=hashlib.sha256(changes).hexdigest(), source_files=files) | ||
| 50 | + return dict(head=head, source_files=files, | ||
| 51 | + dirty_sha256=hashlib.sha256(json.dumps(dirty, sort_keys=True).encode()).hexdigest()) | ||
| 52 | + | ||
| 53 | + | ||
| 54 | +_TENPU_MODULES = ( | ||
| 55 | + 'transformer_engine', 'transformer_engine.pytorch.module.base', | ||
| 56 | + 'transformer_engine.pytorch.ops.basic.npu_activation', | ||
| 57 | + 'transformer_engine.pytorch.ops.basic.swiglu', 'transformer_engine.pytorch.ops.op', | ||
| 58 | + 'transformer_engine.pytorch.ops.fuser', 'transformer_engine.pytorch.ops.sequential') | ||
| 59 | +_CORE_MODULES = ( | ||
| 60 | + 'megatron.core', 'megatron.core.distributed.param_and_grad_buffer', | ||
| 61 | + 'megatron.core.distributed.distributed_data_parallel', | ||
| 62 | + 'megatron.core.transformer.moe.experts', 'megatron.core.transformer.moe.token_dispatcher', | ||
| 63 | + 'megatron.core.transformer.moe.moe_layer', 'megatron.core.parallel_state', | ||
| 64 | + 'megatron.core.pipeline_parallel.schedules') | ||
| 65 | +_MS_RUNTIME_MODULES = ('mindspeed.core.transformer.moe.moonep_ops',) | ||
| 66 | + | ||
| 67 | + | ||
| 68 | +def _package_root(module, package): | ||
| 69 | + path = Path(module.__file__).resolve(strict=True) | ||
| 70 | + for parent in path.parents: | ||
| 71 | + if parent.name == package: | ||
| 72 | + marker = parent / ('core/__init__.py' if package == 'megatron' else '__init__.py') | ||
| 73 | + if marker.is_file(): | ||
| 74 | + return parent.parent | ||
| 75 | + raise RuntimeError('installed module is outside its source package: ' + package) | ||
| 76 | + | ||
| 77 | + | ||
| 78 | +def collect_installed_identity(device): | ||
| 79 | + """Import existing libraries, never construct Buffer or initialize SHMEM. | ||
| 80 | + | ||
| 81 | + Lock full TENPU/Core source trees as well as loaded math/schedule modules. | ||
| 82 | + A matching provider/MS binary cannot validate changed TENPU math or DDP. | ||
| 83 | + """ | ||
| 84 | + from mindspeed.ops.moonep_compute import runtime_identity, _SYMBOLS | ||
| 85 | + names = (('mindspeed', 'mindspeed._moonep_compute', 'npu_patch', 'npu_patch._C') | ||
| 86 | + + _MS_RUNTIME_MODULES + _TENPU_MODULES + _CORE_MODULES) | ||
| 87 | + modules = {name: importlib.import_module(name) for name in names} | ||
| 88 | + dependencies = {name: importlib.import_module(name) for name in ('torch', 'torch._C', 'torch_npu', 'torch_npu._C')} | ||
| 89 | + stream_modules = [importlib.import_module(name) for name in ('torch_npu.npu.streams', 'torch_npu.npu.utils')] | ||
| 90 | + try: | ||
| 91 | + npu_version = importlib.import_module('torch_npu.version') | ||
| 92 | + except ModuleNotFoundError as error: | ||
| 93 | + if error.name != 'torch_npu.version': | ||
| 94 | + raise | ||
| 95 | + npu_version = None | ||
| 96 | + roots = {key: _package_root(modules[name], package) for key, name, package in ( | ||
| 97 | + ('ms', 'mindspeed', 'mindspeed'), ('provider', 'npu_patch', 'npu_patch'), | ||
| 98 | + ('tenpu', 'transformer_engine', 'transformer_engine'), ('core', 'megatron.core', 'megatron'))} | ||
| 99 | + for name, module in modules.items(): | ||
| 100 | + package = name.split('.')[0] | ||
| 101 | + key = {'mindspeed': 'ms', 'npu_patch': 'provider', | ||
| 102 | + 'transformer_engine': 'tenpu', 'megatron': 'core'}[package] | ||
| 103 | + if _package_root(module, package) != roots[key]: | ||
| 104 | + raise RuntimeError('mixed installed source roots: ' + name) | ||
| 105 | + candidate = {key: _source(roots[key], package) for key, package in ( | ||
| 106 | + ('ms', 'mindspeed'), ('provider', 'npu_patch'), ('tenpu', 'transformer_engine'), ('core', 'megatron'))} | ||
| 107 | + candidate['provider']['base_sha'] = PROVIDER_BASE_SHA | ||
| 108 | + caps = runtime_identity(device) | ||
| 109 | + if len(caps.get('symbol_providers', ())) != len(_SYMBOLS): | ||
| 110 | + raise RuntimeError('all six standard symbol providers must be identified') | ||
| 111 | + from npu_patch.runtime_audit import audit_loaded_shmem_library, _decode_maps_path | ||
| 112 | + shmem = audit_loaded_shmem_library() | ||
| 113 | + mapped = set() | ||
| 114 | + for line in Path('/proc/self/maps').read_text().splitlines(): | ||
| 115 | + fields = line.split(None, 5) | ||
| 116 | + if len(fields) == 6 and fields[5].startswith('/'): | ||
| 117 | + mapped.add(str(Path(_decode_maps_path(fields[5])).resolve())) | ||
| 118 | + kernels = [p for p in mapped if Path(p).name == 'libascend_moonep_kernels.so'] | ||
| 119 | + torch_native = [p for p in mapped if Path(p).name == 'libtorch_npu.so'] | ||
| 120 | + if len(kernels) != 1 or len(torch_native) != 1: | ||
| 121 | + raise RuntimeError('exactly one loaded provider kernel and torch_npu image are required') | ||
| 122 | + torch_package = Path(dependencies['torch'].__file__).resolve(strict=True).parent | ||
| 123 | + npu_package = Path(dependencies['torch_npu'].__file__).resolve(strict=True).parent | ||
| 124 | + torch_core = [] | ||
| 125 | + for name in ('libtorch.so', 'libtorch_cpu.so', 'libtorch_python.so', 'libc10.so'): | ||
| 126 | + images = [Path(path) for path in mapped if Path(path).name == name] | ||
| 127 | + if len(images) != 1 or images[0].parent != torch_package / 'lib': | ||
| 128 | + raise RuntimeError('mixed or missing loaded Torch core image: ' + name) | ||
| 129 | + torch_core.append(images[0]) | ||
| 130 | + if not Path(torch_native[0]).is_relative_to(npu_package): | ||
| 131 | + raise RuntimeError('torch_npu Python/native installation differs') | ||
| 132 | + stream_files = [] | ||
| 133 | + for module in stream_modules: | ||
| 134 | + actual = file_identity(module.__file__) | ||
| 135 | + if not Path(actual['realpath']).is_relative_to(npu_package): | ||
| 136 | + raise RuntimeError('torch_npu stream implementation is outside the selected installation') | ||
| 137 | + stream_files.append(actual) | ||
| 138 | + artifacts = dict(manifest=file_identity(roots['ms'] / 'mindspeed/ops/moonep_compute_capabilities.json'), | ||
| 139 | + ms_extension=file_identity(modules['mindspeed._moonep_compute'].__file__), | ||
| 140 | + provider_extension=file_identity(modules['npu_patch._C'].__file__), | ||
| 141 | + provider_kernel=file_identity(kernels[0]), shmem=file_identity(shmem['realpath']), | ||
| 142 | + torch_npu_native=file_identity(torch_native[0]), | ||
| 143 | + torch_entry=file_identity(dependencies['torch'].__file__), | ||
| 144 | + torch_extension=file_identity(dependencies['torch._C'].__file__), | ||
| 145 | + torch_core=[file_identity(path) for path in torch_core], | ||
| 146 | + torch_npu_entry=file_identity(dependencies['torch_npu'].__file__), | ||
| 147 | + torch_npu_extension=file_identity(dependencies['torch_npu._C'].__file__), | ||
| 148 | + torch_npu_stream_files=stream_files, | ||
| 149 | + mindspeed_runtime_files=[file_identity(modules[n].__file__) for n in _MS_RUNTIME_MODULES], | ||
| 150 | + tenpu_files=[file_identity(modules[n].__file__) for n in _TENPU_MODULES], | ||
| 151 | + core_files=[file_identity(modules[n].__file__) for n in _CORE_MODULES], | ||
| 152 | + standard_symbols=[dict(symbol=n, **file_identity(p)) for n, p in zip(_SYMBOLS, caps['symbol_providers'])]) | ||
| 153 | + if any(artifacts[n]['realpath'] not in mapped for n in ('ms_extension', 'provider_extension', 'provider_kernel', 'shmem', | ||
| 154 | + 'torch_extension', 'torch_npu_extension')): | ||
| 155 | + raise RuntimeError('native artifact is not the actually loaded image') | ||
| 156 | + if npu_version is not None and getattr(npu_version, '__file__', None): | ||
| 157 | + version_path = Path(npu_version.__file__).resolve(strict=True) | ||
| 158 | + if not version_path.is_relative_to(npu_package): | ||
| 159 | + raise RuntimeError('torch_npu version module is outside the selected installation') | ||
| 160 | + artifacts['torch_npu_version_file'] = file_identity(version_path) | ||
| 161 | + versions = dict(torch=getattr(dependencies['torch'], '__version__', None), | ||
| 162 | + torch_git=getattr(getattr(dependencies['torch'], 'version', None), 'git_version', None), | ||
| 163 | + torch_cxx11_abi=getattr(dependencies['torch._C'], '_GLIBCXX_USE_CXX11_ABI', None), | ||
| 164 | + torch_npu=getattr(dependencies['torch_npu'], '__version__', None), | ||
| 165 | + torch_npu_git=getattr(npu_version, 'git_version', None)) | ||
| 166 | + if not versions['torch'] or not versions['torch_npu']: | ||
| 167 | + raise RuntimeError('installed Torch/torch_npu version metadata is missing') | ||
| 168 | + return dict(installation_mode='source-prebuilt', candidate=candidate, artifacts=artifacts, | ||
| 169 | + dependency_versions=versions, source_roots={key: str(root) for key, root in roots.items()}, | ||
| 170 | + declared_source_tuple=caps['declared_source_tuple'], capabilities=caps) | ||
| 171 | + | ||
| 172 | + | ||
| 173 | +def load_validation_bundle(path, *, group, profile, actual_identity, topology=None): | ||
| 174 | + """Check this candidate's executed component receipts before controlled S3.""" | ||
| 175 | + path = Path(path).resolve(strict=True) | ||
| 176 | + bundle = json.loads(path.read_text()) | ||
| 177 | + if bundle.get('schema') != 2 or bundle.get('stage') != 'S2_COMPONENTS': | ||
| 178 | + raise RuntimeError('a schema2 S2_COMPONENTS bundle is required') | ||
| 179 | + if bundle.get('activation_profile') != ACTIVATION_PROFILE: | ||
| 180 | + raise RuntimeError('explicit copy-counted activation profile is required') | ||
| 181 | + if actual_identity.get('installation_mode') != 'source-prebuilt': | ||
| 182 | + raise RuntimeError('only audited source-prebuilt installations are supported') | ||
| 183 | + for key in ('candidate', 'artifacts', 'declared_source_tuple', 'dependency_versions', 'source_roots'): | ||
| 184 | + if bundle.get(key) != actual_identity.get(key): | ||
| 185 | + raise RuntimeError('component bundle identity mismatch: ' + key) | ||
| 186 | + if bundle.get('profile') != profile or bundle.get('topology') != topology: | ||
| 187 | + raise RuntimeError('component bundle profile/topology mismatch') | ||
| 188 | + if not isinstance(bundle.get('provider_runtime'), dict) or not bundle['provider_runtime']: | ||
| 189 | + raise RuntimeError('component bundle requires actual provider runtime geometry') | ||
| 190 | + roots = [Path(p).resolve(strict=True) for p in bundle.get('installation_roots', [])] | ||
| 191 | + entries = [] | ||
| 192 | + for value in actual_identity['artifacts'].values(): | ||
| 193 | + entries.extend(value if isinstance(value, list) else [value]) | ||
| 194 | + if not roots or any(not any(Path(v['realpath']).is_relative_to(r) for r in roots) for v in entries): | ||
| 195 | + raise RuntimeError('artifact outside the component installation lock') | ||
| 196 | + for stage in ('S0', 'S1', 'S2'): | ||
| 197 | + driver = _COMPONENT_DRIVERS.get(stage) | ||
| 198 | + if driver is None: | ||
| 199 | + raise RuntimeError('SOURCE_BLOCKED: reviewed native driver is not implemented: ' + stage) | ||
| 200 | + entry = bundle.get('receipts', {}).get(stage, {}) | ||
| 201 | + receipt_path = (path.parent / entry.get('path', '')).resolve(strict=True) | ||
| 202 | + if not receipt_path.is_relative_to(path.parent) or file_identity(receipt_path)['sha256'] != entry.get('receipt_hash'): | ||
| 203 | + raise RuntimeError('component receipt path/hash mismatch') | ||
| 204 | + receipt = json.loads(receipt_path.read_text()) | ||
| 205 | + if stage == 'S2' and receipt.get('provider_runtime') != bundle['provider_runtime']: | ||
| 206 | + raise RuntimeError('S2 provider mode/engine/geometry evidence differs') | ||
| 207 | + execution = receipt.get('execution', {}) | ||
| 208 | + argv = execution.get('argv') | ||
| 209 | + if (type(execution.get('exit_code')) is not int or execution['exit_code'] != 0 | ||
| 210 | + or execution.get('completed') is not True or not isinstance(argv, list) | ||
| 211 | + or not argv or any(type(value) is not str or not value for value in argv)): | ||
| 212 | + raise RuntimeError('component execution did not terminate normally') | ||
| 213 | + if (receipt.get('stage') != stage or receipt.get('status') != 'PASS' | ||
| 214 | + or receipt.get('identity') != actual_identity or receipt.get('profile') != profile | ||
| 215 | + or receipt.get('topology') != topology or receipt.get('method') != 'native-executed'): | ||
| 216 | + raise RuntimeError('component receipt is stale, unexecuted or out of scope') | ||
| 217 | + if file_identity(driver['realpath']) != driver or receipt.get('driver') != driver: | ||
| 218 | + raise RuntimeError('component receipt was not produced by the reviewed driver') | ||
| 219 | + assertions = receipt.get('assertions', {}) | ||
| 220 | + if set(assertions) != _STAGE_ASSERTIONS[stage]: | ||
| 221 | + raise RuntimeError('component assertion coverage is incomplete') | ||
| 222 | + for name, result in assertions.items(): | ||
| 223 | + if result.get('status') != 'PASS' or not result.get('method'): | ||
| 224 | + raise RuntimeError('component assertion is unexecuted: ' + name) | ||
| 225 | + evidence = result.get('evidence', {}) | ||
| 226 | + evidence_path = (path.parent / evidence.get('path', '')).resolve(strict=True) | ||
| 227 | + if (not evidence_path.is_relative_to(path.parent) | ||
| 228 | + or file_identity(evidence_path)['sha256'] != evidence.get('sha256')): | ||
| 229 | + raise RuntimeError('component assertion evidence changed: ' + name) | ||
| 230 | + if name in ('gmm_direct_out', 'no_weight_pack'): | ||
| 231 | + if result.get('method') != 'native-payload-trace': | ||
| 232 | + raise RuntimeError('pointer identity is not native payload evidence') | ||
| 233 | + proof = result.get('standard_executor_source', {}) | ||
| 234 | + if (proof.get('source_tuple') != actual_identity['declared_source_tuple'] | ||
| 235 | + or proof.get('standard_symbols') != actual_identity['artifacts'].get('standard_symbols')): | ||
| 236 | + raise RuntimeError('standard executor proof has a different source tuple') | ||
| 237 | + mapping = proof.get('source_mapping', {}) | ||
| 238 | + if (mapping.get('method') not in ('reproducible-build-match', 'vendor-build-manifest') | ||
| 239 | + or mapping.get('artifact_hashes') != [item['sha256'] for item in proof['standard_symbols']] | ||
| 240 | + or not isinstance(mapping.get('source_refs'), list) or not mapping['source_refs'] | ||
| 241 | + or any(not isinstance(ref, dict) or not ref.get('sha') or not ref.get('executor_path') | ||
| 242 | + or not ref.get('branch') for ref in mapping['source_refs'])): | ||
| 243 | + raise RuntimeError('actual standard binary-to-source mapping is missing') | ||
| 244 | + for item in (proof, mapping.get('evidence', {}), result.get('trace_parser', {}), | ||
| 245 | + result.get('invocations', {})): | ||
| 246 | + if not isinstance(item, dict) or not item.get('path') or not item.get('sha256'): | ||
| 247 | + raise RuntimeError('payload source/parser/invocation evidence is missing') | ||
| 248 | + proof_path = (path.parent / item['path']).resolve(strict=True) | ||
| 249 | + if (not proof_path.is_relative_to(path.parent) | ||
| 250 | + or file_identity(proof_path)['sha256'] != item.get('sha256')): | ||
| 251 | + raise RuntimeError('payload source/parser evidence is absent or changed') | ||
| 252 | + if stage == 'S0': | ||
| 253 | + build = receipt.get('build', {}) | ||
| 254 | + if (build.get('candidate') != actual_identity['candidate'] | ||
| 255 | + or build.get('outputs') != actual_identity['artifacts'] | ||
| 256 | + or not isinstance(build.get('command'), list) or not build['command']): | ||
| 257 | + raise RuntimeError('source-prebuilt build provenance is missing') | ||
| 258 | + log = receipt.get('log', {}) | ||
| 259 | + log_path = (path.parent / log.get('path', '')).resolve(strict=True) | ||
| 260 | + if not log_path.is_relative_to(path.parent) or file_identity(log_path)['sha256'] != log.get('sha256'): | ||
| 261 | + raise RuntimeError('component log missing or changed') | ||
| 262 | + required = set(RUNTIME_CAPABILITIES) | ||
| 263 | + if set(bundle.get('validated_capabilities', [])) != required: | ||
| 264 | + raise RuntimeError('component capability coverage is incomplete') | ||
| 265 | + caps = actual_identity['capabilities'] | ||
| 266 | + return dict(mode=MODE, native_abi=caps['native_abi'], training_integration_ready=True, | ||
| 267 | + validation_status='PASS', activation_profile=ACTIVATION_PROFILE, source_build_validation='PASS', symbol_provider_validation='PASS', | ||
| 268 | + standard_library=caps['standard_library'], symbol_providers=caps['symbol_providers'], | ||
| 269 | + source_tuple=actual_identity['declared_source_tuple'], provider_source_sha=PROVIDER_SOURCE_SHA, | ||
| 270 | + provider_identity=actual_identity['artifacts']['provider_extension'], | ||
| 271 | + tenpu_identity=actual_identity['artifacts']['tenpu_files'], profile=profile, group=group, | ||
| 272 | + provider_runtime=bundle['provider_runtime'], | ||
| 273 | + **{name: 'PASS' for name in required}) | ||
| @@ -0,0 +1,425 @@ | |||
| 1 | +# Copyright (c) 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| 2 | +# Copyright (c) 2026, Huawei Technologies Co., Ltd. All rights reserved. | ||
| 3 | +# See LICENSE for license information. | ||
| 4 | +"""PR7450 control protocol with official MoonEP synchronous resource seams. | ||
| 5 | + | ||
| 6 | +GPU donor: 9b60ad82e1b38d4829582b1a34863293db995ccf. The provider is the | ||
| 7 | +only physical/completion/poison owner. Expert mathematics belongs to TENPU's | ||
| 8 | +existing fuser, not to a MindSpeed expert Autograd Function. | ||
| 9 | +""" | ||
| 10 | +from __future__ import annotations | ||
| 11 | + | ||
| 12 | +from dataclasses import dataclass, field | ||
| 13 | +import weakref | ||
| 14 | + | ||
| 15 | +import torch | ||
| 16 | + | ||
| 17 | +from .moonep_bindings import ( | ||
| 18 | + context_charge, group_metadata, validate_routing_ids, begin_owner_operation, | ||
| 19 | + end_owner_operation, retain_owner_resources, poison_owner, owner_complete, | ||
| 20 | +) | ||
| 21 | +from .moonep_autograd import _dummy, _pad | ||
| 22 | + | ||
| 23 | + | ||
| 24 | +@dataclass(slots=True) | ||
| 25 | +class VirtualExpertPlan: | ||
| 26 | + """One exact provider plan and its graph-owned logical scheduling state.""" | ||
| 27 | + | ||
| 28 | + call_identity: tuple | ||
| 29 | + source: object | ||
| 30 | + source_probs: object | ||
| 31 | + source_versions: tuple | ||
| 32 | + weight_versions: tuple | ||
| 33 | + provider_plan: object = None | ||
| 34 | + counts: object = None | ||
| 35 | + prefix: object = None | ||
| 36 | + padding: object = None | ||
| 37 | + started: set = field(default_factory=set) | ||
| 38 | + pending_heads: dict = field(default_factory=dict) | ||
| 39 | + linear_specs: tuple = () | ||
| 40 | + done: bool = False | ||
| 41 | + copies: list = field(default_factory=list) | ||
| 42 | + context_bytes: int = 0 | ||
| 43 | + | ||
| 44 | + | ||
| 45 | +class _VirtualExpertStorage: | ||
| 46 | + """Borrow already registered slots and scratch from one layer binding.""" | ||
| 47 | + | ||
| 48 | + def __init__(self, binding): | ||
| 49 | + self.binding = binding | ||
| 50 | + self.slot_weights = tuple(tuple(self._runtime_parameter(w, g) | ||
| 51 | + for w, g in zip(weight.unbind(0), grad.unbind(0))) | ||
| 52 | + for weight, grad in binding.slots) | ||
| 53 | + | ||
| 54 | + @staticmethod | ||
| 55 | + def _runtime_parameter(weight, main_grad, *, overwrite=True): | ||
| 56 | + """Unregistered compute leaf borrowing payload; never a model parameter.""" | ||
| 57 | + parameter = torch.nn.Parameter(weight) | ||
| 58 | + parameter.main_grad = main_grad | ||
| 59 | + parameter.overwrite_main_grad = overwrite | ||
| 60 | + return parameter | ||
| 61 | + | ||
| 62 | + | ||
| 63 | +class _VirtualExperts: | ||
| 64 | + """One layer's runtime weights over provider-owned shared storage.""" | ||
| 65 | + | ||
| 66 | + def __init__(self, storage): | ||
| 67 | + self.storage = storage | ||
| 68 | + binding = storage.binding | ||
| 69 | + self.parameters = (binding.w1, binding.w2) | ||
| 70 | + self.source_parameters = tuple(parameter for group in self.parameters for parameter in group) | ||
| 71 | + self.runtime_weights = [] | ||
| 72 | + for fc_layer, weights in enumerate(self.parameters): | ||
| 73 | + natives = tuple(storage._runtime_parameter(w, w.main_grad, overwrite=False) for w in weights) | ||
| 74 | + self.runtime_weights.append((*natives, *storage.slot_weights[fc_layer])) | ||
| 75 | + | ||
| 76 | + def hand_off_wgrads(self, fc_layer): | ||
| 77 | + # Canonical targets have already received combined owner contributions. | ||
| 78 | + return _dummy(self.parameters[fc_layer]) | ||
| 79 | + | ||
| 80 | + | ||
| 81 | +class _VirtualExpertHook(torch.autograd.Function): | ||
| 82 | + """Call a method during backward, preserving the tensor gradient. | ||
| 83 | + | ||
| 84 | + Its return values are gradients for ``inputs``. Hold the method weakly: the manager | ||
| 85 | + retains forward tensors, so a strong reference would keep the autograd graph alive. | ||
| 86 | + """ | ||
| 87 | + | ||
| 88 | + @staticmethod | ||
| 89 | + def forward(ctx, tensor, method, args, *inputs): | ||
| 90 | + """Save the callback for backward and return the tensor unchanged.""" | ||
| 91 | + ctx.method, ctx.args = weakref.WeakMethod(method), args | ||
| 92 | + return tensor | ||
| 93 | + | ||
| 94 | + @staticmethod | ||
| 95 | + def backward(ctx, grad): | ||
| 96 | + """Run the callback to obtain input gradients and preserve the tensor gradient.""" | ||
| 97 | + return (grad, None, None, *(ctx.method()(*ctx.args) or ())) | ||
| 98 | + | ||
| 99 | + | ||
| 100 | + | ||
| 101 | +class _VirtualExpertFC2WgradStore: | ||
| 102 | + """Run the producer and publish its partials before starting FC2 GR.""" | ||
| 103 | + | ||
| 104 | + context = None | ||
| 105 | + | ||
| 106 | + def __init__(self, load_balancer): | ||
| 107 | + self._load_balancer = weakref.proxy(load_balancer) | ||
| 108 | + | ||
| 109 | + @staticmethod | ||
| 110 | + def delay_wgrad_compute() -> bool: | ||
| 111 | + """TE routes the wgrad GEMM through :meth:`put` when this is true.""" | ||
| 112 | + return True | ||
| 113 | + | ||
| 114 | + def put(self, tensors, wgrad_gemm): | ||
| 115 | + """Run the wgrad GEMM now and start FC2's virtual-expert reduction behind it.""" | ||
| 116 | + wgrad_gemm(*tensors) | ||
| 117 | + self._load_balancer.start_fc2_grad_reduce() | ||
| 118 | + | ||
| 119 | + | ||
| 120 | +class _Dispatch(torch.autograd.Function): | ||
| 121 | + """Only token transport Autograd; there is no expert mathematics here.""" | ||
| 122 | + | ||
| 123 | + @staticmethod | ||
| 124 | + def forward(ctx, source, probs, ids, manager, plan): | ||
| 125 | + buffer = manager.binding.buffer | ||
| 126 | + carrier, probabilities, cu, handle = buffer.dispatch( | ||
| 127 | + source, probs, ids.to(torch.int32), | ||
| 128 | + buffer._require_ctx()['_mindspeed_integration']['compat_tpe'], async_finish=False, | ||
| 129 | + zero_copy=False, router_weights_zero_copy=False) | ||
| 130 | + plan.provider_plan = handle | ||
| 131 | + plan.counts, plan.prefix, plan.padding = group_metadata(buffer, cu) | ||
| 132 | + _pad(carrier, probabilities, plan.padding) | ||
| 133 | + manager._count_copy(plan, 'Z1', carrier) | ||
| 134 | + manager._count_copy(plan, 'P', probabilities) | ||
| 135 | + ctx.manager, ctx.plan = manager, plan | ||
| 136 | + return carrier, probabilities | ||
| 137 | + | ||
| 138 | + @staticmethod | ||
| 139 | + def backward(ctx, grad, dp): | ||
| 140 | + manager, plan = ctx.manager, ctx.plan | ||
| 141 | + try: | ||
| 142 | + manager.require_backward_plan(plan) | ||
| 143 | + manager._start_pending_grad_reduces() | ||
| 144 | + if grad is None or dp is None: | ||
| 145 | + raise RuntimeError('partial transport Autograd is outside the admitted profile') | ||
| 146 | + dx, route_grad, _ = manager.binding.buffer.combine( | ||
| 147 | + plan.provider_plan, grad, dp, async_finish=False, | ||
| 148 | + zero_copy=False, router_weights_zero_copy=False) | ||
| 149 | + manager._count_copy(plan, 'Z4', grad) | ||
| 150 | + manager._count_copy(plan, 'dP', dp) | ||
| 151 | + return dx, route_grad, None, None, None | ||
| 152 | + except BaseException as error: | ||
| 153 | + poison_owner(manager.binding.buffer, error, (manager, plan, grad, dp)) | ||
| 154 | + raise | ||
| 155 | + | ||
| 156 | + | ||
| 157 | +class _Combine(torch.autograd.Function): | ||
| 158 | + @staticmethod | ||
| 159 | + def forward(ctx, source, manager, plan): | ||
| 160 | + output, _, _ = manager.binding.buffer.combine( | ||
| 161 | + plan.provider_plan, source, async_finish=False, zero_copy=False) | ||
| 162 | + manager._count_copy(plan, 'Z2', source) | ||
| 163 | + ctx.manager, ctx.plan = manager, plan | ||
| 164 | + return output | ||
| 165 | + | ||
| 166 | + @staticmethod | ||
| 167 | + def backward(ctx, grad): | ||
| 168 | + manager, plan = ctx.manager, ctx.plan | ||
| 169 | + try: | ||
| 170 | + manager.require_backward_plan(plan) | ||
| 171 | + if grad is None or not grad.is_contiguous(): | ||
| 172 | + raise RuntimeError('backward requires a contiguous gradient, no implicit copy') | ||
| 173 | + d2, backward_probs, _, returned = manager.binding.buffer.dispatch( | ||
| 174 | + grad, plan.source_probs, plan=plan.provider_plan, async_finish=False, | ||
| 175 | + zero_copy=False, router_weights_zero_copy=False) | ||
| 176 | + if returned is not plan.provider_plan: | ||
| 177 | + raise RuntimeError('backward replaced the original provider plan') | ||
| 178 | + _pad(d2, None, plan.padding) | ||
| 179 | + manager._count_copy(plan, 'Z3', d2) | ||
| 180 | + manager._count_copy(plan, 'P-backward', backward_probs) | ||
| 181 | + return d2, None, None | ||
| 182 | + except BaseException as error: | ||
| 183 | + poison_owner(manager.binding.buffer, error, (manager, plan, grad)) | ||
| 184 | + raise | ||
| 185 | + | ||
| 186 | + | ||
| 187 | +class VirtualExpertLoadBalancer: | ||
| 188 | + """GPU logical VE protocol; original Buffer owns all physical state.""" | ||
| 189 | + | ||
| 190 | + def __init__(self, binding): | ||
| 191 | + self.binding = binding | ||
| 192 | + self.num_owned_experts = binding.local_experts | ||
| 193 | + self.virtual_experts = _VirtualExperts(_VirtualExpertStorage(binding)) | ||
| 194 | + self._plan = None | ||
| 195 | + from .moonep_experts import RuntimeTEGroupedMLP | ||
| 196 | + self._expert_compute = RuntimeTEGroupedMLP(binding, self) | ||
| 197 | + | ||
| 198 | + @property | ||
| 199 | + def num_runtime_experts(self) -> int: | ||
| 200 | + """Natives plus virtual-expert slots per rank.""" | ||
| 201 | + return 2 * self.num_owned_experts | ||
| 202 | + | ||
| 203 | + def runtime_weights(self, fc_layer: int) -> tuple[torch.nn.Parameter, ...]: | ||
| 204 | + """Native-then-virtual-expert runtime parameters of one FC layer (0 = FC1, 1 = FC2).""" | ||
| 205 | + return self.virtual_experts.runtime_weights[fc_layer] | ||
| 206 | + | ||
| 207 | + @property | ||
| 208 | + def source_parameters(self) -> tuple[torch.nn.Parameter, ...]: | ||
| 209 | + """The optimizer-owned FC1 then FC2 parameters.""" | ||
| 210 | + return self.virtual_experts.source_parameters | ||
| 211 | + | ||
| 212 | + def _runtime_init(self, hidden_states): | ||
| 213 | + self.binding.check_identity() | ||
| 214 | + if self._plan is not None: | ||
| 215 | + raise RuntimeError('another exact pass is active on this synchronous manager') | ||
| 216 | + | ||
| 217 | + def wrap_layer_input(self, hidden_states): | ||
| 218 | + self._runtime_init(hidden_states) | ||
| 219 | + return _VirtualExpertHook.apply( | ||
| 220 | + hidden_states, self._finish_grad_reduce, (), *self.source_parameters) | ||
| 221 | + | ||
| 222 | + def prepare_virtual_expert_combine(self, hidden_states: torch.Tensor) -> torch.Tensor: | ||
| 223 | + """Attach the backward weight-push wait before transport combine.""" | ||
| 224 | + return _VirtualExpertHook.apply(hidden_states, self._prepare_expert_backward, ()) | ||
| 225 | + | ||
| 226 | + def finalize_layer_output(self, output: torch.Tensor) -> torch.Tensor: | ||
| 227 | + """Close the forward; the layer output's backward hook hands the plan back for its | ||
| 228 | + backward and starts the backward weight push.""" | ||
| 229 | + plan, self._plan = self._plan, None | ||
| 230 | + return _VirtualExpertHook.apply(output, self._start_backward, (plan,)) | ||
| 231 | + | ||
| 232 | + def _prefetch(self, plan): | ||
| 233 | + buffer = self.binding.buffer | ||
| 234 | + self.binding.check_identity() | ||
| 235 | + owner_complete(buffer, peer=True) # All previous peer consumers precede clear. | ||
| 236 | + for weight, _ in self.binding.slots: | ||
| 237 | + weight.zero_() | ||
| 238 | + owner_complete(buffer) | ||
| 239 | + for prepared in self.binding.push_bindings: | ||
| 240 | + buffer.prefetch_lplusb(plan.provider_plan, prepared, async_finish=False) | ||
| 241 | + owner_complete(buffer) | ||
| 242 | + | ||
| 243 | + def _start_backward(self, plan): | ||
| 244 | + try: | ||
| 245 | + if self._plan is not None or plan.done: | ||
| 246 | + raise RuntimeError('backward started twice or overlaps an active pass') | ||
| 247 | + bad, cause = False, None | ||
| 248 | + try: | ||
| 249 | + self.binding.check_identity() | ||
| 250 | + weight_versions = tuple(p._version for p in self.source_parameters) | ||
| 251 | + if weight_versions != plan.weight_versions: | ||
| 252 | + raise RuntimeError('canonical weights changed while a plan was live; expected=' | ||
| 253 | + + repr(plan.weight_versions) + '; actual=' + repr(weight_versions)) | ||
| 254 | + source_versions = (plan.source._version, plan.source_probs._version) | ||
| 255 | + if source_versions != plan.source_versions: | ||
| 256 | + raise RuntimeError('pinned source backing changed while a plan was live; expected=' | ||
| 257 | + + repr(plan.source_versions) + '; actual=' + repr(source_versions)) | ||
| 258 | + except (RuntimeError, ValueError, TypeError) as error: | ||
| 259 | + bad, cause = True, error | ||
| 260 | + begin_owner_operation(self.binding.buffer, plan.call_identity, 'backward', | ||
| 261 | + plan=plan, admission_error=bad, admission_cause=cause) | ||
| 262 | + self._plan = plan | ||
| 263 | + self._prefetch(plan) | ||
| 264 | + except BaseException as error: | ||
| 265 | + poison_owner(self.binding.buffer, error, (self, plan)) | ||
| 266 | + raise | ||
| 267 | + | ||
| 268 | + def _prepare_expert_backward(self): | ||
| 269 | + self.require_backward_plan(self._plan) | ||
| 270 | + | ||
| 271 | + def require_forward_plan(self, plan): | ||
| 272 | + if self._plan is not plan or plan is None or plan.done or plan.provider_plan is None: | ||
| 273 | + raise RuntimeError('foreign or incomplete forward plan') | ||
| 274 | + | ||
| 275 | + def require_backward_plan(self, plan): | ||
| 276 | + if self._plan is not plan or plan is None or plan.done: | ||
| 277 | + raise RuntimeError('foreign or retired exact plan') | ||
| 278 | + | ||
| 279 | + def _wgrad_producer(self, projection, owner, x, dy, counts, prefix, scratch): | ||
| 280 | + from mindspeed.ops.moonep_compute import validate_full_g_wgrad, full_g_wgrad_out | ||
| 281 | + | ||
| 282 | + plan = self._plan | ||
| 283 | + self.require_backward_plan(plan) | ||
| 284 | + if plan.pending_heads or projection in plan.started: | ||
| 285 | + raise RuntimeError('scratch cannot be overwritten before the prior head commits') | ||
| 286 | + spec = plan.linear_specs[projection] | ||
| 287 | + if (spec.call_identity != plan.call_identity or scratch is not spec.wgrad_scratch | ||
| 288 | + or counts is not spec.counts or prefix is not spec.prefix or owner is not self.binding.buffer): | ||
| 289 | + raise RuntimeError('producer specification differs from the exact call') | ||
| 290 | + validate_full_g_wgrad(x, dy, counts, prefix, scratch, self.binding.targets(projection), | ||
| 291 | + local_experts=self.num_owned_experts, scratch_budget_bytes=self.binding.budget) | ||
| 292 | + return full_g_wgrad_out(owner, x, dy, counts, prefix, scratch) | ||
| 293 | + | ||
| 294 | + def _publish_wgrad(self, spec, scratch): | ||
| 295 | + plan = self._plan | ||
| 296 | + self.require_backward_plan(plan) | ||
| 297 | + projection = spec.projection | ||
| 298 | + if (spec.call_identity != plan.call_identity or type(projection) is not int | ||
| 299 | + or projection not in (0, 1) or len(plan.linear_specs) != 2 | ||
| 300 | + or plan.linear_specs[projection] is not spec | ||
| 301 | + or scratch is not spec.wgrad_scratch): | ||
| 302 | + raise RuntimeError('foreign runtime projection specification') | ||
| 303 | + if projection in plan.pending_heads or projection in plan.started: | ||
| 304 | + raise RuntimeError('projection producer cannot publish twice') | ||
| 305 | + buffer = self.binding.buffer | ||
| 306 | + targets = self.binding.targets(projection) | ||
| 307 | + slot = self.binding.slots[projection][1] | ||
| 308 | + retain_owner_resources(buffer, (self.binding, plan, scratch, targets, slot)) | ||
| 309 | + try: | ||
| 310 | + owner_complete(buffer, peer=True) | ||
| 311 | + slot.zero_() | ||
| 312 | + # Publish each producer exactly once. Existing local targets already | ||
| 313 | + # contain any no_sync/previous-microbatch contribution. | ||
| 314 | + for index, target in enumerate(targets): | ||
| 315 | + target.add_(scratch[index]) | ||
| 316 | + plan.pending_heads[projection] = self.binding.grad_bindings[projection] | ||
| 317 | + except BaseException as error: | ||
| 318 | + poison_owner(buffer, error, (self.binding, plan, scratch, targets, slot)) | ||
| 319 | + raise | ||
| 320 | + | ||
| 321 | + def _start_grad_reduce(self, fc_layer): | ||
| 322 | + plan = self._plan | ||
| 323 | + self.require_backward_plan(plan) | ||
| 324 | + if fc_layer in plan.started or fc_layer not in plan.pending_heads: | ||
| 325 | + raise RuntimeError('GR requires one published canonical target binding') | ||
| 326 | + prepared = plan.pending_heads[fc_layer] | ||
| 327 | + buffer = self.binding.buffer | ||
| 328 | + try: | ||
| 329 | + self.binding.check_identity() | ||
| 330 | + owner_complete(buffer, peer=True) | ||
| 331 | + buffer.reduce_grad(plan=plan.provider_plan, lplusb=prepared, async_finish=False) | ||
| 332 | + owner_complete(buffer, peer=True) | ||
| 333 | + # Native GR writes the real bank. Separate aliases may have separate | ||
| 334 | + # version counters: expose the raw write on every canonical target. | ||
| 335 | + torch.autograd.graph.increment_version( | ||
| 336 | + self.binding.targets(fc_layer)[:self.num_owned_experts]) | ||
| 337 | + plan.started.add(fc_layer) | ||
| 338 | + del plan.pending_heads[fc_layer] | ||
| 339 | + except BaseException as error: | ||
| 340 | + poison_owner(buffer, error, (self.binding, plan, prepared)) | ||
| 341 | + raise | ||
| 342 | + | ||
| 343 | + def start_fc2_grad_reduce(self) -> None: | ||
| 344 | + """Start FC2's reduction from the expert backward, right behind FC2's wgrad GEMM.""" | ||
| 345 | + self._start_grad_reduce(1) | ||
| 346 | + | ||
| 347 | + def _start_pending_grad_reduces(self) -> None: | ||
| 348 | + for fc_layer in (1, 0): | ||
| 349 | + if fc_layer not in self._plan.started: | ||
| 350 | + self._start_grad_reduce(fc_layer) | ||
| 351 | + | ||
| 352 | + def _finish_grad_reduce(self): | ||
| 353 | + plan = self._plan | ||
| 354 | + try: | ||
| 355 | + self.require_backward_plan(plan) | ||
| 356 | + if plan.started != {0, 1} or plan.pending_heads: | ||
| 357 | + raise RuntimeError('both projection commits must precede canonical DDP handoff') | ||
| 358 | + end_owner_operation(self.binding.buffer, plan.call_identity, 'backward') | ||
| 359 | + plan.done = True | ||
| 360 | + self._plan = None | ||
| 361 | + fc2_grads = self.virtual_experts.hand_off_wgrads(1) | ||
| 362 | + result = (*self.virtual_experts.hand_off_wgrads(0), *fc2_grads) | ||
| 363 | + plan.source = plan.source_probs = None | ||
| 364 | + plan.linear_specs = () | ||
| 365 | + plan.provider_plan = plan.counts = plan.prefix = plan.padding = None | ||
| 366 | + return result | ||
| 367 | + except BaseException as error: | ||
| 368 | + poison_owner(self.binding.buffer, error, (self, plan)) | ||
| 369 | + raise | ||
| 370 | + | ||
| 371 | + def _restore_wgrad_input(self, plan): | ||
| 372 | + self.require_backward_plan(plan) | ||
| 373 | + try: | ||
| 374 | + restored, _, _, returned = self.binding.buffer.dispatch( | ||
| 375 | + plan.source, None, plan=plan.provider_plan, async_finish=False, zero_copy=False) | ||
| 376 | + if returned is not plan.provider_plan: | ||
| 377 | + raise RuntimeError('R1 replaced the original provider plan') | ||
| 378 | + _pad(restored, None, plan.padding) | ||
| 379 | + self._count_copy(plan, 'R1', restored) | ||
| 380 | + return restored | ||
| 381 | + except BaseException as error: | ||
| 382 | + poison_owner(self.binding.buffer, error, (self, plan)) | ||
| 383 | + raise | ||
| 384 | + | ||
| 385 | + @staticmethod | ||
| 386 | + def _count_copy(plan, edge, value): | ||
| 387 | + if value is not None: | ||
| 388 | + # Source-derived scheduled bytes: provider api.py dispatch 663-669 / combine 685-691. | ||
| 389 | + # These are explicit boundary copies, not a measured native staging trace. | ||
| 390 | + plan.copies.append((edge, value.numel() * value.element_size())) | ||
| 391 | + | ||
| 392 | + def run(self, source, probs, ids, call_identity): | ||
| 393 | + buffer = self.binding.buffer | ||
| 394 | + profile = buffer._require_ctx() | ||
| 395 | + bad, charge, plan = False, 0, None | ||
| 396 | + try: | ||
| 397 | + self._expert_compute.prepare_forward() | ||
| 398 | + self.binding.check_identity() | ||
| 399 | + if (not torch.is_grad_enabled() or source.dtype != torch.bfloat16 | ||
| 400 | + or probs.dtype != torch.float32 or source.shape != (profile['S'], profile['H']) | ||
| 401 | + or probs.shape != (profile['S'], profile['K']) or ids.shape != probs.shape | ||
| 402 | + or ids.dtype not in (torch.int32, torch.int64) | ||
| 403 | + or any(not t.is_contiguous() or t.device != source.device for t in (source, probs, ids))): | ||
| 404 | + raise ValueError('invalid ordinary source/routing contract') | ||
| 405 | + charge = context_charge(source, probs, profile, self.binding.shape2) | ||
| 406 | + plan = VirtualExpertPlan(call_identity, source.detach(), probs.detach(), | ||
| 407 | + (source._version, probs._version), tuple(p._version for p in self.source_parameters)) | ||
| 408 | + except Exception: | ||
| 409 | + bad = True | ||
| 410 | + begin_owner_operation(buffer, call_identity, 'forward', plan=plan, | ||
| 411 | + admission_error=bad, context_bytes=charge) | ||
| 412 | + try: | ||
| 413 | + self._plan = plan | ||
| 414 | + validate_routing_ids(buffer, ids) | ||
| 415 | + carrier, probabilities = _Dispatch.apply(source, probs, ids, self, plan) | ||
| 416 | + self._prefetch(plan) | ||
| 417 | + expert_output, _ = self._expert_compute.forward( | ||
| 418 | + carrier, plan.counts, probabilities, plan=plan) | ||
| 419 | + expert_output = self.prepare_virtual_expert_combine(expert_output) | ||
| 420 | + result = _Combine.apply(expert_output, self, plan) | ||
| 421 | + end_owner_operation(buffer, call_identity, 'forward') | ||
| 422 | + return self.finalize_layer_output(result) | ||
| 423 | + except BaseException as error: | ||
| 424 | + poison_owner(buffer, error, (self, plan, source, probs, ids)) | ||
| 425 | + raise | ||
| @@ -39,6 +39,7 @@ from mindspeed.features_manager.tensor_parallel.locl_coc import CoCFeature | |||
| 39 | 39 | ||
| 40 | from mindspeed.features_manager.moe.tp_extend_ep import MoETpExtendEpFeature | 40 | from mindspeed.features_manager.moe.tp_extend_ep import MoETpExtendEpFeature |
| 41 | from mindspeed.features_manager.moe.gmm import MoEGmmFeature | 41 | from mindspeed.features_manager.moe.gmm import MoEGmmFeature |
| 42 | +from mindspeed.features_manager.moe.moonep import MoonEPFeature | ||
| 42 | from mindspeed.features_manager.moe.shared_expert import MoESharedExpertsFeature | 43 | from mindspeed.features_manager.moe.shared_expert import MoESharedExpertsFeature |
| 43 | from mindspeed.features_manager.moe.fb_overlap import MoEFwdBwdOverlapFeature | 44 | from mindspeed.features_manager.moe.fb_overlap import MoEFwdBwdOverlapFeature |
| 44 | from mindspeed.features_manager.moe.balanced_moe import BalancedMoEFeature | 45 | from mindspeed.features_manager.moe.balanced_moe import BalancedMoEFeature |
| @@ -226,6 +227,7 @@ def add_transformer_features(features_list: List[MindSpeedFeature]): | |||
| 226 | def add_moe_features(features_list: List[MindSpeedFeature]): | 227 | def add_moe_features(features_list: List[MindSpeedFeature]): |
| 227 | features_list.extend( | 228 | features_list.extend( |
| 228 | [ | 229 | [ |
| 230 | + MoonEPFeature(), | ||
| 229 | MoEGmmFeature(), | 231 | MoEGmmFeature(), |
| 230 | MoETpExtendEpFeature(), | 232 | MoETpExtendEpFeature(), |
| 231 | MoESharedExpertsFeature(), | 233 | MoESharedExpertsFeature(), |
| @@ -157,6 +157,13 @@ class MoEGmmFeature(MindSpeedFeature): | |||
| 157 | raise AssertionError('MindSpeed --moe-grouped-gemm requires --transformer-impl transformer_engine.') | 157 | raise AssertionError('MindSpeed --moe-grouped-gemm requires --transformer-impl transformer_engine.') |
| 158 | 158 | ||
| 159 | def register_patches(self, patch_manager, args): | 159 | def register_patches(self, patch_manager, args): |
| 160 | + from mindspeed.core.transformer.moe.moonep_contract import enabled, validate_options | ||
| 161 | + | ||
| 162 | + validate_options(args) | ||
| 163 | + if enabled(args): | ||
| 164 | + # New mode owns the whole expert boundary. Do not import the old | ||
| 165 | + # weighted helper or register any TENPU constructor/forward patch. | ||
| 166 | + return | ||
| 160 | if args.moe_grouped_gemm: | 167 | if args.moe_grouped_gemm: |
| 161 | patch_manager.register_patch( | 168 | patch_manager.register_patch( |
| 162 | 'megatron.core.extensions.transformer_engine.TEGroupedLinear.forward', | 169 | 'megatron.core.extensions.transformer_engine.TEGroupedLinear.forward', |
| @@ -0,0 +1,62 @@ | |||
| 1 | +"""Default-off shared-slot admission; does not import an accelerator runtime.""" | ||
| 2 | + | ||
| 3 | +from mindspeed.core.transformer.moe.moonep_contract import MODE, enabled, validate_options | ||
| 4 | +from mindspeed.features_manager.feature import MindSpeedFeature | ||
| 5 | + | ||
| 6 | + | ||
| 7 | +class MoonEPFeature(MindSpeedFeature): | ||
| 8 | + def __init__(self): | ||
| 9 | + super().__init__('moonep-compute-mode', 2) | ||
| 10 | + | ||
| 11 | + def is_need_apply(self, args): | ||
| 12 | + return getattr(args, 'moonep_compute_mode', 'off') != 'off' | ||
| 13 | + | ||
| 14 | + def register_args(self, parser): | ||
| 15 | + self.add_parser_argument_choices_value(parser, '--moe-flex-dispatcher-backend', 'moonep') | ||
| 16 | + group = parser.add_argument_group(title='MoonEP standard CANN compute') | ||
| 17 | + group.add_argument('--moonep-compute-mode', choices=('off', MODE), default='off') | ||
| 18 | + group.add_argument('--moonep-wgrad-scratch-bytes', type=int, default=0) | ||
| 19 | + group.add_argument('--moonep-validation-bundle', default=None) | ||
| 20 | + group.add_argument('--moonep-source-rows', type=int, default=0) | ||
| 21 | + group.add_argument('--moonep-live-context-bytes', type=int, default=0) | ||
| 22 | + group.add_argument('--moonep-dedup-mode', choices=('rank', 'server'), default='rank') | ||
| 23 | + | ||
| 24 | + def validate_args(self, args): | ||
| 25 | + validate_options(args) | ||
| 26 | + | ||
| 27 | + def register_patches(self, patch_manager, args): | ||
| 28 | + if not enabled(args): | ||
| 29 | + return | ||
| 30 | + from mindspeed.core.transformer.moe.moonep_adapter import ( | ||
| 31 | + MoonEPDispatcher, compact_routing_wrapper, compact_topk_wrapper, | ||
| 32 | + caller_thread_backward_wrapper, destroy_moonep_wrapper, forward_step_wrapper, per_expert_init_wrapper, route_input_wrapper, routed_experts_wrapper, training_setup_wrapper, | ||
| 33 | + ) | ||
| 34 | + for target in ( | ||
| 35 | + 'megatron.core.transformer.moe.token_dispatcher.MoEFlexTokenDispatcher', | ||
| 36 | + 'megatron.core.transformer.moe.moe_layer.MoEFlexTokenDispatcher', | ||
| 37 | + ): | ||
| 38 | + patch_manager.register_patch(target, MoonEPDispatcher, force_patch=True) | ||
| 39 | + for target in ( | ||
| 40 | + 'megatron.core.transformer.moe.moe_layer.MoELayer.__init__', | ||
| 41 | + 'megatron.core.transformer.moe.experts.TEGroupedMLP.__init__', | ||
| 42 | + ): | ||
| 43 | + patch_manager.register_patch(target, per_expert_init_wrapper) | ||
| 44 | + patch_manager.register_patch( | ||
| 45 | + 'megatron.core.transformer.moe.router.TopKRouter.routing', compact_routing_wrapper) | ||
| 46 | + patch_manager.register_patch( | ||
| 47 | + 'megatron.core.transformer.moe.router.topk_routing_with_score_function', compact_topk_wrapper) | ||
| 48 | + patch_manager.register_patch( | ||
| 49 | + 'megatron.core.transformer.moe.moe_layer.MoELayer.route', route_input_wrapper) | ||
| 50 | + patch_manager.register_patch( | ||
| 51 | + 'megatron.core.transformer.moe.moe_layer.MoELayer.routed_experts_compute', routed_experts_wrapper) | ||
| 52 | + patch_manager.register_patch( | ||
| 53 | + 'megatron.training.training.setup_model_and_optimizer', training_setup_wrapper) | ||
| 54 | + patch_manager.register_patch( | ||
| 55 | + 'megatron.core.pipeline_parallel.schedules.forward_step', forward_step_wrapper) | ||
| 56 | + patch_manager.register_patch( | ||
| 57 | + 'megatron.core.pipeline_parallel.schedules.backward_step', caller_thread_backward_wrapper) | ||
| 58 | + for target in ( | ||
| 59 | + 'megatron.training.training.destroy_model_parallel', | ||
| 60 | + 'megatron.core.parallel_state.destroy_model_parallel', | ||
| 61 | + ): | ||
| 62 | + patch_manager.register_patch(target, destroy_moonep_wrapper) | ||
| @@ -0,0 +1,428 @@ | |||
| 1 | +// Standard-CANN thin binding. No operator core, custom OPP, JIT or fallback. | ||
| 2 | +#include <torch/extension.h> | ||
| 3 | +#include <torch_npu/csrc/core/npu/NPUStream.h> | ||
| 4 | +#include <torch_npu/csrc/core/npu/NPUFunctions.h> | ||
| 5 | +#include <torch_npu/csrc/core/npu/NPUGraphsUtils.h> | ||
| 6 | +#include <torch_npu/csrc/core/npu/NPUCachingAllocator.h> | ||
| 7 | +#include <torch_npu/csrc/aten/CustomFunctions.h> | ||
| 8 | +#include <torch_npu/csrc/framework/OpCommand.h> | ||
| 9 | +#include <acl/acl.h> | ||
| 10 | +#include <aclnn/acl_meta.h> | ||
| 11 | +#include <aclnn/aclnn_base.h> | ||
| 12 | +#include <aclnn/opdev/op_errno.h> | ||
| 13 | +#include <dlfcn.h> | ||
| 14 | +#include <atomic> | ||
| 15 | +#include <functional> | ||
| 16 | +#include <cstdlib> | ||
| 17 | +#include <filesystem> | ||
| 18 | +#include <limits> | ||
| 19 | +#include <memory> | ||
| 20 | +#include <string> | ||
| 21 | +#include <utility> | ||
| 22 | +#include <vector> | ||
| 23 | + | ||
| 24 | +#ifndef MINDSPEED_MOONEP_VALIDATION_WIRING | ||
| 25 | +#define MINDSPEED_MOONEP_VALIDATION_WIRING 0 | ||
| 26 | +#endif | ||
| 27 | + | ||
| 28 | +namespace { | ||
| 29 | +using Phase2 = aclnnStatus (*)(void*, uint64_t, aclOpExecutor*, aclrtStream); | ||
| 30 | +using V5Get = aclnnStatus (*)( | ||
| 31 | + const aclTensorList*, const aclTensorList*, const aclTensorList*, | ||
| 32 | + const aclTensorList*, const aclTensorList*, const aclTensorList*, | ||
| 33 | + const aclTensorList*, const aclTensorList*, const aclTensor*, | ||
| 34 | + const aclTensorList*, const aclTensorList*, const aclTensorList*, | ||
| 35 | + int64_t, int64_t, int64_t, int64_t, aclIntArray*, aclTensorList*, | ||
| 36 | + aclTensorList*, aclTensorList*, uint64_t*, aclOpExecutor**); | ||
| 37 | +using AddGet = aclnnStatus (*)(const aclTensor*, const aclTensor*, const aclTensor*, | ||
| 38 | + aclTensor*, bool, bool, int64_t, int64_t, | ||
| 39 | + uint64_t*, aclOpExecutor**); | ||
| 40 | +using SumGet = aclnnStatus (*)(const aclTensor*, const aclIntArray*, bool, | ||
| 41 | + aclDataType, aclTensor*, uint64_t*, aclOpExecutor**); | ||
| 42 | + | ||
| 43 | +struct Symbols { | ||
| 44 | + void* handle; | ||
| 45 | + std::string path; | ||
| 46 | + std::vector<std::string> providers; | ||
| 47 | + V5Get v5_get; | ||
| 48 | + Phase2 v5_run; | ||
| 49 | + AddGet add_get; | ||
| 50 | + Phase2 add_run; | ||
| 51 | + SumGet sum_get; | ||
| 52 | + Phase2 sum_run; | ||
| 53 | + | ||
| 54 | + template<class T> T get(const char* name) { | ||
| 55 | + auto* symbol = dlsym(handle, name); | ||
| 56 | + TORCH_CHECK(symbol, "required standard CANN symbol missing: ", name); | ||
| 57 | + Dl_info info{}; | ||
| 58 | + TORCH_CHECK(dladdr(symbol, &info) && info.dli_fname, | ||
| 59 | + "cannot identify symbol provider: ", name); | ||
| 60 | + providers.push_back(std::filesystem::canonical(info.dli_fname).string()); | ||
| 61 | + return reinterpret_cast<T>(symbol); | ||
| 62 | + } | ||
| 63 | + | ||
| 64 | + Symbols() { | ||
| 65 | + const char* configured = std::getenv("MINDSPEED_MOONEP_OPAPI_LIBRARY"); | ||
| 66 | + TORCH_CHECK(configured && std::filesystem::path(configured).is_absolute(), | ||
| 67 | + "an audited absolute standard libopapi.so is required"); | ||
| 68 | + path = std::filesystem::canonical(configured).string(); | ||
| 69 | + TORCH_CHECK(std::filesystem::path(path).filename() == "libopapi.so", | ||
| 70 | + "custom OPP libraries are not accepted"); | ||
| 71 | + handle = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); | ||
| 72 | + TORCH_CHECK(handle, "cannot load selected standard library: ", path); | ||
| 73 | + std::unique_ptr<void, decltype(&dlclose)> pending(handle, dlclose); | ||
| 74 | + v5_get = get<V5Get>("aclnnGroupedMatmulV5GetWorkspaceSize"); | ||
| 75 | + v5_run = get<Phase2>("aclnnGroupedMatmulV5"); | ||
| 76 | + add_get = get<AddGet>("aclnnGroupedMatmulAddV2GetWorkspaceSize"); | ||
| 77 | + add_run = get<Phase2>("aclnnGroupedMatmulAddV2"); | ||
| 78 | + sum_get = get<SumGet>("aclnnReduceSumGetWorkspaceSize"); | ||
| 79 | + sum_run = get<Phase2>("aclnnReduceSum"); | ||
| 80 | + pending.release(); // Keep code/registrations loaded for process lifetime. | ||
| 81 | + } | ||
| 82 | +}; | ||
| 83 | + | ||
| 84 | +Symbols& symbols() { | ||
| 85 | + static Symbols value; | ||
| 86 | + const char* configured = std::getenv("MINDSPEED_MOONEP_OPAPI_LIBRARY"); | ||
| 87 | + TORCH_CHECK(configured && std::filesystem::canonical(configured).string() == value.path, | ||
| 88 | + "changing the standard library after load is unsupported"); | ||
| 89 | + return value; | ||
| 90 | +} | ||
| 91 | + | ||
| 92 | +std::string admit_device(c10::DeviceIndex device) { | ||
| 93 | + TORCH_CHECK(c10_npu::current_device() == device, | ||
| 94 | + "caller current device must equal all compute tensors"); | ||
| 95 | + TORCH_CHECK(!c10_npu::is_core_control_enabled(), | ||
| 96 | + "caller-sync-launch-v1 requires default core-control resources"); | ||
| 97 | + TORCH_CHECK(c10_npu::currentStreamCaptureStatusMayInitCtx() == c10_npu::CaptureStatus::None, | ||
| 98 | + "MindSpeed MoonEP compute is eager-only; active/invalidated capture is rejected"); | ||
| 99 | + const char* soc = aclrtGetSocName(); | ||
| 100 | + TORCH_CHECK(soc && std::string(soc).rfind("Ascend950", 0) == 0, | ||
| 101 | + "strict direct-out is restricted to the audited Ascend950 family"); | ||
| 102 | + return soc; | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +void check(const at::Tensor& t, at::ScalarType dtype, int64_t rank, | ||
| 106 | + const at::Device& device, bool contiguous = true) { | ||
| 107 | + TORCH_CHECK(t.defined() && t.device() == device && | ||
| 108 | + t.device().type() == c10::DeviceType::PrivateUse1 && | ||
| 109 | + t.scalar_type() == dtype && t.dim() == rank && !t.requires_grad(), | ||
| 110 | + "invalid compute dtype/rank/device/Autograd state"); | ||
| 111 | + TORCH_CHECK(!contiguous || t.is_contiguous(), "no implicit contiguous copy"); | ||
| 112 | + TORCH_CHECK(!t.is_neg() && !t.is_conj(), "lazy views require forbidden materialization"); | ||
| 113 | + TORCH_CHECK(at_npu::native::custom_ops::get_npu_format(t) == ACL_FORMAT_ND, | ||
| 114 | + "only ND format is admitted"); | ||
| 115 | +} | ||
| 116 | + | ||
| 117 | +void disjoint(const at::Tensor& a, const at::Tensor& b) { | ||
| 118 | + if (!a.numel() || !b.numel()) return; | ||
| 119 | + auto x = reinterpret_cast<uintptr_t>(a.data_ptr()); | ||
| 120 | + auto y = reinterpret_cast<uintptr_t>(b.data_ptr()); | ||
| 121 | + TORCH_CHECK(x <= std::numeric_limits<uintptr_t>::max() - a.nbytes() && | ||
| 122 | + y <= std::numeric_limits<uintptr_t>::max() - b.nbytes(), "address overflow"); | ||
| 123 | + TORCH_CHECK(x + a.nbytes() <= y || y + b.nbytes() <= x, "output overlaps input"); | ||
| 124 | + // Different VAs may still physically alias. The provider backing manifest | ||
| 125 | + // must prove physical disjointness; this VA check does not replace it. | ||
| 126 | +} | ||
| 127 | + | ||
| 128 | +struct Call { | ||
| 129 | + struct TensorDeleter { void operator()(aclTensor* x) const { aclDestroyTensor(x); } }; | ||
| 130 | + struct ListDeleter { void operator()(aclTensorList* x) const { aclDestroyTensorList(x); } }; | ||
| 131 | + struct ArrayDeleter { void operator()(aclIntArray* x) const { aclDestroyIntArray(x); } }; | ||
| 132 | + using TensorOwner = std::unique_ptr<aclTensor, TensorDeleter>; | ||
| 133 | + using ListOwner = std::unique_ptr<aclTensorList, ListDeleter>; | ||
| 134 | + using ArrayOwner = std::unique_ptr<aclIntArray, ArrayDeleter>; | ||
| 135 | + std::vector<ListOwner> lists; | ||
| 136 | + std::vector<TensorOwner> singles; | ||
| 137 | + std::vector<ArrayOwner> arrays; | ||
| 138 | + std::vector<at::Tensor> borrowed; | ||
| 139 | + at::Tensor allocator_probe; | ||
| 140 | + at::Tensor workspace; | ||
| 141 | + c10_npu::NPUCachingAllocator::NPUAllocator* allocator = nullptr; | ||
| 142 | + c10::DeviceIndex device; | ||
| 143 | + aclrtStream stream; | ||
| 144 | + uint64_t workspace_bytes = 0; | ||
| 145 | + aclOpExecutor* executor = nullptr; | ||
| 146 | + bool prepared = false; | ||
| 147 | + bool allocator_admitted = false; | ||
| 148 | + std::atomic<bool> entered{false}; | ||
| 149 | + std::atomic<bool> handler_started{false}; | ||
| 150 | + bool phase2_returned = false; | ||
| 151 | + | ||
| 152 | + Call(const at::Tensor& owner, const std::vector<at::Tensor>& refs) : borrowed(refs) { | ||
| 153 | + TORCH_CHECK(owner.defined() && owner.device().type() == c10::DeviceType::PrivateUse1, | ||
| 154 | + "Call requires an NPU owner"); | ||
| 155 | + borrowed.push_back(owner); | ||
| 156 | + device = owner.get_device(); | ||
| 157 | + admit_device(device); | ||
| 158 | + auto current = c10_npu::getCurrentNPUStream(device); | ||
| 159 | + TORCH_CHECK(current.isSyncLaunchStream(), "ABI2 Call requires public SyncLaunchStream"); | ||
| 160 | + stream = current.stream(false); | ||
| 161 | + TORCH_CHECK(stream, "captured launch stream is null"); | ||
| 162 | + allocator = c10_npu::NPUCachingAllocator::get(); | ||
| 163 | + check_allocator_identity(); | ||
| 164 | + } | ||
| 165 | + | ||
| 166 | + ~Call() { | ||
| 167 | + // Phase2 may consume/delete executor even on error. Never restore its | ||
| 168 | + // pointer or free it again after entering the SDK. | ||
| 169 | + if (executor && !entered.load()) aclDestroyAclOpExecutor(executor); | ||
| 170 | + } | ||
| 171 | + | ||
| 172 | + void check_allocator_identity() const { | ||
| 173 | + TORCH_CHECK(allocator && c10_npu::NPUCachingAllocator::get() == allocator && | ||
| 174 | + allocator->name() == "native", "native allocator identity changed or is unsupported"); | ||
| 175 | + } | ||
| 176 | + | ||
| 177 | + void check_cached_allocation(const at::Tensor& tensor) const { | ||
| 178 | + check_allocator_identity(); | ||
| 179 | + // The public allocator lookup returns null for a non-cached allocation. | ||
| 180 | + // Check the real storage DataPtr, not an environment variable whose | ||
| 181 | + // value can differ from OptionsManager's process-cached decision. | ||
| 182 | + TORCH_CHECK(tensor.defined() && tensor.numel() > 0 && tensor.storage_offset() == 0 && | ||
| 183 | + allocator->getBlockPtr(tensor.storage().data_ptr()), | ||
| 184 | + "ordinary allocation lacks an actual native cached block"); | ||
| 185 | + } | ||
| 186 | + | ||
| 187 | + void admit_allocator() { | ||
| 188 | + TORCH_CHECK(!allocator_admitted && !prepared, "allocator admission cannot replay"); | ||
| 189 | + admit_device(device); | ||
| 190 | + check_allocator_identity(); | ||
| 191 | + auto current = c10_npu::getCurrentNPUStream(device); | ||
| 192 | + TORCH_CHECK(current.isSyncLaunchStream() && current.stream(false) == stream, | ||
| 193 | + "allocator admission requires the captured synchronous launch stream"); | ||
| 194 | + // Called only after the original provider retains this Call. Keep the | ||
| 195 | + // tiny real probe alive with the Call, including uncertain failures. | ||
| 196 | + allocator_probe = at::empty({1}, borrowed.back().options().dtype(at::kByte)); | ||
| 197 | + check_cached_allocation(allocator_probe); | ||
| 198 | + allocator_admitted = true; | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + void begin() { | ||
| 202 | + TORCH_CHECK(allocator_admitted && !prepared, "a native Call requires allocator admission and cannot replay"); | ||
| 203 | + prepared = true; | ||
| 204 | + admit_device(device); | ||
| 205 | + check_allocator_identity(); | ||
| 206 | + TORCH_CHECK(c10_npu::getCurrentNPUStream(device).stream(false) == stream, | ||
| 207 | + "compute stream changed after Call capture"); | ||
| 208 | + TORCH_CHECK(c10_npu::getCurrentNPUStream(device).isSyncLaunchStream(), | ||
| 209 | + "ABI2 operation requires its captured synchronous launch stream"); | ||
| 210 | + // Standard wrappers apply resources before the DSO captures/applies its | ||
| 211 | + // own snapshot. Never call hidden snapshot/TLS helpers from this DSO. | ||
| 212 | + TORCH_CHECK(aclrtUseStreamResInCurrentThread(stream) == ACL_SUCCESS, | ||
| 213 | + "cannot apply launch stream resources"); | ||
| 214 | + } | ||
| 215 | + | ||
| 216 | + TensorOwner descriptor(const at::Tensor& t) { | ||
| 217 | + auto shape = t.sizes().vec(); | ||
| 218 | + auto storage_shape = shape; | ||
| 219 | + if (t.dim() == 2 && !t.is_contiguous()) std::swap(storage_shape[0], storage_shape[1]); | ||
| 220 | + aclDataType dtype = t.scalar_type() == at::kBFloat16 ? ACL_BF16 : | ||
| 221 | + t.scalar_type() == at::kFloat ? ACL_FLOAT : ACL_INT64; | ||
| 222 | + auto* value = aclCreateTensor(shape.data(), shape.size(), dtype, t.strides().data(), | ||
| 223 | + 0, ACL_FORMAT_ND, storage_shape.data(), storage_shape.size(), t.data_ptr()); | ||
| 224 | + TORCH_CHECK(value, "aclCreateTensor failed"); | ||
| 225 | + return TensorOwner(value); // data_ptr already includes storage_offset. | ||
| 226 | + } | ||
| 227 | + | ||
| 228 | + aclTensor* single(const at::Tensor& t) { | ||
| 229 | + borrowed.push_back(t); | ||
| 230 | + auto value = descriptor(t); | ||
| 231 | + auto* pointer = value.get(); | ||
| 232 | + singles.push_back(std::move(value)); | ||
| 233 | + return pointer; | ||
| 234 | + } | ||
| 235 | + | ||
| 236 | + aclTensorList* list(const std::vector<at::Tensor>& tensors) { | ||
| 237 | + std::vector<const aclTensor*> elements; | ||
| 238 | + std::vector<TensorOwner> owners; | ||
| 239 | + for (const auto& t : tensors) { | ||
| 240 | + borrowed.push_back(t); | ||
| 241 | + owners.push_back(descriptor(t)); | ||
| 242 | + elements.push_back(owners.back().get()); | ||
| 243 | + } | ||
| 244 | + ListOwner value(aclCreateTensorList(elements.data(), elements.size())); | ||
| 245 | + TORCH_CHECK(value, "aclCreateTensorList failed"); | ||
| 246 | + for (auto& owner : owners) owner.release(); // TensorList owns descriptors, not payload. | ||
| 247 | + auto* pointer = value.get(); | ||
| 248 | + lists.push_back(std::move(value)); | ||
| 249 | + return pointer; | ||
| 250 | + } | ||
| 251 | + | ||
| 252 | + aclIntArray* last_dim() { | ||
| 253 | + int64_t dim = -1; | ||
| 254 | + ArrayOwner value(aclCreateIntArray(&dim, 1)); | ||
| 255 | + TORCH_CHECK(value, "aclCreateIntArray failed"); | ||
| 256 | + auto* pointer = value.get(); | ||
| 257 | + arrays.push_back(std::move(value)); | ||
| 258 | + return pointer; | ||
| 259 | + } | ||
| 260 | +}; | ||
| 261 | + | ||
| 262 | +void checked_current_complete(c10::DeviceIndex device, uintptr_t expected) { | ||
| 263 | + admit_device(device); | ||
| 264 | + auto current = c10_npu::getCurrentNPUStream(device); | ||
| 265 | + auto stream = reinterpret_cast<aclrtStream>(expected); | ||
| 266 | + TORCH_CHECK(stream && current.stream(false) == stream, | ||
| 267 | + "completion requires the explicitly expected current stream"); | ||
| 268 | + auto drained = current.stream(); | ||
| 269 | + TORCH_CHECK(drained && drained == stream, "Q1 drain failed or changed stream"); | ||
| 270 | + TORCH_CHECK(aclrtUseStreamResInCurrentThread(stream) == ACL_SUCCESS, | ||
| 271 | + "cannot restore current stream resources"); | ||
| 272 | + TORCH_CHECK(aclrtSynchronizeStream(stream) == ACL_SUCCESS, | ||
| 273 | + "current-stream local completion failed"); | ||
| 274 | +} | ||
| 275 | + | ||
| 276 | +void complete(const std::shared_ptr<Call>& call) { | ||
| 277 | + TORCH_CHECK(call->phase2_returned, "incomplete native Call cannot be released"); | ||
| 278 | + call->check_allocator_identity(); | ||
| 279 | + TORCH_CHECK(c10_npu::getCurrentNPUStream(call->device).isSyncLaunchStream(), | ||
| 280 | + "native Call completion requires its launch stream"); | ||
| 281 | + checked_current_complete(call->device, reinterpret_cast<uintptr_t>(call->stream)); | ||
| 282 | +} | ||
| 283 | + | ||
| 284 | +void submit(const char* name, const std::function<aclnnStatus()>& phase1, | ||
| 285 | + Phase2 run, const std::shared_ptr<Call>& call, const at::Tensor& owner) { | ||
| 286 | + // The public runner's synchronous-launch branch uses InnerRunOpApi, which | ||
| 287 | + // owns capture/apply/TLS. All SDK phases and the allocator stay inside it. | ||
| 288 | + at_npu::native::OpCommand::RunOpApiV2(name, [call, run, phase1, owner]() -> int { | ||
| 289 | + admit_device(call->device); | ||
| 290 | + auto current = c10_npu::getCurrentNPUStream(call->device); | ||
| 291 | + TORCH_CHECK(current.isSyncLaunchStream() && current.stream(false) == call->stream, | ||
| 292 | + "standard handler is not on the captured synchronous launch stream"); | ||
| 293 | + TORCH_CHECK(!call->handler_started.exchange(true), "native handler cannot replay"); | ||
| 294 | + auto status = phase1(); | ||
| 295 | + TORCH_CHECK(status == ACLNN_SUCCESS, "standard phase1 failed: ", status); | ||
| 296 | + call->check_allocator_identity(); | ||
| 297 | + if (call->workspace_bytes) { | ||
| 298 | + TORCH_CHECK(call->workspace_bytes <= static_cast<uint64_t>(std::numeric_limits<int64_t>::max()), | ||
| 299 | + "workspace size overflow"); | ||
| 300 | + call->workspace = at::empty({static_cast<int64_t>(call->workspace_bytes)}, | ||
| 301 | + owner.options().dtype(at::kByte)); | ||
| 302 | + call->check_cached_allocation(call->workspace); | ||
| 303 | + } | ||
| 304 | + // A zero-byte workspace needs no allocation; the retained real probe | ||
| 305 | + // still proves the allocator, and identity is rechecked before phase2. | ||
| 306 | + call->check_allocator_identity(); | ||
| 307 | + auto* executor = std::exchange(call->executor, nullptr); | ||
| 308 | + TORCH_CHECK(executor, "phase2 requires an unconsumed executor"); | ||
| 309 | + TORCH_CHECK(!call->entered.exchange(true), "phase2 cannot replay"); | ||
| 310 | + status = run(call->workspace_bytes ? call->workspace.data_ptr() : nullptr, | ||
| 311 | + call->workspace_bytes, executor, call->stream); | ||
| 312 | + TORCH_CHECK(status == ACLNN_SUCCESS, "standard phase2 failed: ", status); | ||
| 313 | + call->phase2_returned = true; | ||
| 314 | + return static_cast<int>(status); | ||
| 315 | + }); | ||
| 316 | + TORCH_CHECK(call->phase2_returned, "runner did not execute its synchronous handler"); | ||
| 317 | +} | ||
| 318 | + | ||
| 319 | +at::Tensor linear_out(const std::shared_ptr<Call>& call, const at::Tensor& x, | ||
| 320 | + const std::vector<at::Tensor>& weights, const at::Tensor& counts, | ||
| 321 | + const at::Tensor& out) { | ||
| 322 | + call->begin(); | ||
| 323 | + check(x, at::kBFloat16, 2, x.device()); | ||
| 324 | + check(out, at::kBFloat16, 2, x.device()); | ||
| 325 | + check(counts, at::kLong, 1, x.device()); | ||
| 326 | + TORCH_CHECK(x.get_device() == call->device && !weights.empty() && weights.size() <= 128 && | ||
| 327 | + counts.numel() == static_cast<int64_t>(weights.size()) && x.size(0) > 0 && | ||
| 328 | + x.size(0) <= 2147483647 && out.size(0) == x.size(0) && | ||
| 329 | + x.size(1) > 0 && out.size(1) > 0, "linear shape/groups mismatch"); | ||
| 330 | + disjoint(out, x); | ||
| 331 | + disjoint(out, counts); | ||
| 332 | + bool transpose = !weights.front().is_contiguous(); | ||
| 333 | + for (const auto& weight : weights) { | ||
| 334 | + check(weight, at::kBFloat16, 2, x.device(), false); | ||
| 335 | + bool view = weight.stride(0) == 1 && weight.stride(1) == weight.size(0); | ||
| 336 | + TORCH_CHECK((weight.is_contiguous() || view) && | ||
| 337 | + (!weight.is_contiguous()) == transpose && | ||
| 338 | + weight.size(0) == x.size(1) && weight.size(1) == out.size(1), | ||
| 339 | + "uniform row-major/transpose weight layout required"); | ||
| 340 | + disjoint(out, weight); | ||
| 341 | + } | ||
| 342 | + auto& api = symbols(); | ||
| 343 | + submit("mindspeed_moonep/aclnnGroupedMatmulV5", [call, x, weights, counts, out, &api]() { | ||
| 344 | + auto* inputs = call->list({x}); | ||
| 345 | + auto* refs = call->list(weights); | ||
| 346 | + auto* outputs = call->list({out}); | ||
| 347 | + auto* groups = call->single(counts); | ||
| 348 | + return api.v5_get(inputs, refs, nullptr, nullptr, nullptr, nullptr, nullptr, | ||
| 349 | + nullptr, groups, nullptr, nullptr, nullptr, 3, 0, 1, 0, nullptr, outputs, | ||
| 350 | + nullptr, nullptr, &call->workspace_bytes, &call->executor); | ||
| 351 | + }, api.v5_run, call, x); | ||
| 352 | + return out; | ||
| 353 | +} | ||
| 354 | + | ||
| 355 | +at::Tensor wgrad_accumulate(const std::shared_ptr<Call>& call, const at::Tensor& scratch, | ||
| 356 | + const at::Tensor& dy, const at::Tensor& x, const at::Tensor& prefix) { | ||
| 357 | + call->begin(); | ||
| 358 | + check(x, at::kBFloat16, 2, x.device()); | ||
| 359 | + check(dy, at::kBFloat16, 2, x.device()); | ||
| 360 | + check(scratch, at::kFloat, 3, x.device()); | ||
| 361 | + check(prefix, at::kLong, 1, x.device()); | ||
| 362 | + TORCH_CHECK(x.get_device() == call->device && prefix.numel() > 0 && prefix.numel() <= 128 && | ||
| 363 | + scratch.size(0) == prefix.numel() && scratch.size(1) == dy.size(1) && | ||
| 364 | + scratch.size(2) == x.size(1) && x.size(0) == dy.size(0) && | ||
| 365 | + x.size(0) > 0 && x.size(0) <= 2147483647 && | ||
| 366 | + x.size(1) > 0 && dy.size(1) > 0, "wgrad shape mismatch"); | ||
| 367 | + for (const auto& input : {x, dy, prefix}) disjoint(scratch, input); | ||
| 368 | + auto& api = symbols(); | ||
| 369 | + submit("mindspeed_moonep/aclnnGroupedMatmulAddV2", [call, dy, x, prefix, scratch, &api]() { | ||
| 370 | + auto* d = call->single(dy); | ||
| 371 | + auto* input = call->single(x); | ||
| 372 | + auto* groups = call->single(prefix); | ||
| 373 | + auto* output = call->single(scratch); | ||
| 374 | + return api.add_get(d, input, groups, output, true, false, 2, 0, | ||
| 375 | + &call->workspace_bytes, &call->executor); | ||
| 376 | + }, api.add_run, call, x); | ||
| 377 | + return scratch; | ||
| 378 | +} | ||
| 379 | + | ||
| 380 | +at::Tensor reduce_sum_out(const std::shared_ptr<Call>& call, | ||
| 381 | + const at::Tensor& product, const at::Tensor& out) { | ||
| 382 | + call->begin(); | ||
| 383 | + check(product, at::kFloat, 2, product.device()); | ||
| 384 | + check(out, at::kFloat, 1, product.device()); | ||
| 385 | + TORCH_CHECK(product.get_device() == call->device && product.size(0) > 0 && | ||
| 386 | + product.size(1) > 0 && out.size(0) == product.size(0), "reduce shape mismatch"); | ||
| 387 | + disjoint(out, product); | ||
| 388 | + auto& api = symbols(); | ||
| 389 | + submit("mindspeed_moonep/aclnnReduceSum", [call, product, out, &api]() { | ||
| 390 | + auto* input = call->single(product); | ||
| 391 | + auto* output = call->single(out); | ||
| 392 | + return api.sum_get(input, call->last_dim(), false, ACL_FLOAT, output, | ||
| 393 | + &call->workspace_bytes, &call->executor); | ||
| 394 | + }, api.sum_run, call, product); | ||
| 395 | + return out; | ||
| 396 | +} | ||
| 397 | +} // namespace | ||
| 398 | + | ||
| 399 | +PYBIND11_MODULE(TORCH_EXTENSION_NAME, module) { | ||
| 400 | + module.attr("ABI_VERSION") = 2; | ||
| 401 | + pybind11::class_<Call, std::shared_ptr<Call>>(module, "Call"); | ||
| 402 | + module.def("create_call", [](const at::Tensor& owner, const std::vector<at::Tensor>& borrowed) { | ||
| 403 | + return std::make_shared<Call>(owner, borrowed); | ||
| 404 | + }); | ||
| 405 | + module.def("admit_call", [](const std::shared_ptr<Call>& call) { call->admit_allocator(); }); | ||
| 406 | + module.def("library_path", []() { return symbols().path; }); | ||
| 407 | + module.def("capabilities", [](c10::DeviceIndex device) { | ||
| 408 | + auto soc = admit_device(device); | ||
| 409 | + auto& api = symbols(); | ||
| 410 | + pybind11::dict result; | ||
| 411 | + result["native_abi"] = 2; | ||
| 412 | + result["mode"] = "mindspeed_shared_slots_full_g_v1"; | ||
| 413 | + result["wgrad_submission"] = "canonical-targets-before-gr-v1"; | ||
| 414 | + result["execution_profile"] = "caller-sync-launch-v1"; | ||
| 415 | + result["completion"] = "caller-sync-launch-local-complete"; | ||
| 416 | + result["opapi_library"] = api.path; | ||
| 417 | + result["symbol_providers"] = api.providers; | ||
| 418 | + result["soc_name"] = soc; | ||
| 419 | + result["training_integration_ready"] = static_cast<bool>(MINDSPEED_MOONEP_VALIDATION_WIRING); | ||
| 420 | + result["device_validation"] = "NOT_RUN"; | ||
| 421 | + return result; | ||
| 422 | + }); | ||
| 423 | + module.def("linear_out", &linear_out); | ||
| 424 | + module.def("wgrad_accumulate", &wgrad_accumulate); | ||
| 425 | + module.def("reduce_sum_out", &reduce_sum_out); | ||
| 426 | + module.def("complete", &complete); | ||
| 427 | + module.def("checked_current_complete", &checked_current_complete); | ||
| 428 | +} | ||
| @@ -0,0 +1,371 @@ | |||
| 1 | +"""First-order standard-CANN out primitives; no JIT, transport or DDP owner. | ||
| 2 | + | ||
| 3 | +The caller supplies the original provider context and mark_failed interface. | ||
| 4 | +The synchronous stack holds the Call until completion, or transfers uncertain | ||
| 5 | +resources to that provider before unwinding. Native installation and device | ||
| 6 | +validation are separate gates; this module never advertises training readiness. | ||
| 7 | +""" | ||
| 8 | + | ||
| 9 | +import hashlib | ||
| 10 | +import importlib._bootstrap | ||
| 11 | +import importlib.machinery | ||
| 12 | +import json | ||
| 13 | +import os | ||
| 14 | +from pathlib import Path | ||
| 15 | +import sys | ||
| 16 | + | ||
| 17 | + | ||
| 18 | +ABI_VERSION = 2 | ||
| 19 | +MODE = "mindspeed_shared_slots_full_g_v1" | ||
| 20 | +EXECUTION_PROFILE = "caller-sync-launch-v1" | ||
| 21 | +COMPLETION = "caller-sync-launch-local-complete" | ||
| 22 | +MAX_GROUPS = 128 | ||
| 23 | +WGRAD_SUBMISSION = "canonical-targets-before-gr-v1" | ||
| 24 | +_LIBRARY_IDENTITY = None | ||
| 25 | +_DTYPES = {"linear_input": "bf16", "linear_output": "bf16", "wgrad_input": "bf16", | ||
| 26 | + "wgrad_output": "fp32", "probability_grad": "fp32"} | ||
| 27 | +_SYMBOLS = ["aclnnGroupedMatmulV5GetWorkspaceSize", "aclnnGroupedMatmulV5", | ||
| 28 | + "aclnnGroupedMatmulAddV2GetWorkspaceSize", "aclnnGroupedMatmulAddV2", | ||
| 29 | + "aclnnReduceSumGetWorkspaceSize", "aclnnReduceSum"] | ||
| 30 | + | ||
| 31 | + | ||
| 32 | +def full_g_scratch_bytes(groups, projection_shapes): | ||
| 33 | + if type(groups) is not int or not 1 <= groups <= MAX_GROUPS: | ||
| 34 | + raise ValueError("group count must be 1..128") | ||
| 35 | + shapes = tuple(tuple(shape) for shape in projection_shapes) | ||
| 36 | + if not shapes or any(len(s) != 2 or any(type(v) is not int or v <= 0 for v in s) for s in shapes): | ||
| 37 | + raise ValueError("projection shapes must be positive integer [O,I] pairs") | ||
| 38 | + return max(4 * groups * o * i for o, i in shapes) | ||
| 39 | + | ||
| 40 | + | ||
| 41 | +def _audit_library(): | ||
| 42 | + global _LIBRARY_IDENTITY | ||
| 43 | + configured = Path(os.environ.get("MINDSPEED_MOONEP_OPAPI_LIBRARY", "")) | ||
| 44 | + digest = os.environ.get("MINDSPEED_MOONEP_OPAPI_SHA256", "") | ||
| 45 | + if not configured.is_absolute() or len(digest) != 64 or any(c not in "0123456789abcdef" for c in digest): | ||
| 46 | + raise RuntimeError("an audited absolute standard libopapi.so and lowercase SHA256 are required") | ||
| 47 | + path = configured.resolve(strict=True) | ||
| 48 | + if path.name != "libopapi.so" or not path.is_file(): | ||
| 49 | + raise RuntimeError("only the selected standard libopapi.so is allowed") | ||
| 50 | + identity = (str(path), digest, path.stat().st_size, path.stat().st_mtime_ns) | ||
| 51 | + if _LIBRARY_IDENTITY is not None and identity != _LIBRARY_IDENTITY: | ||
| 52 | + raise RuntimeError("changing the selected standard library after admission is unsupported") | ||
| 53 | + if _LIBRARY_IDENTITY is None: | ||
| 54 | + with path.open("rb") as stream: | ||
| 55 | + value = hashlib.sha256() | ||
| 56 | + for block in iter(lambda: stream.read(1024 * 1024), b""): | ||
| 57 | + value.update(block) | ||
| 58 | + if value.hexdigest() != digest: | ||
| 59 | + raise RuntimeError("standard library SHA256 mismatch") | ||
| 60 | + _LIBRARY_IDENTITY = identity | ||
| 61 | + return path | ||
| 62 | + | ||
| 63 | + | ||
| 64 | +def preflight_compute(): | ||
| 65 | + """Inspect packaging using stdlib only; never import/load native or NPU.""" | ||
| 66 | + directory = Path(__file__).resolve().parents[1] | ||
| 67 | + manifest = json.loads((Path(__file__).with_name("moonep_compute_capabilities.json")).read_text()) | ||
| 68 | + if (type(manifest.get("schema")) is not int or manifest["schema"] != 2 | ||
| 69 | + or manifest.get("mode") != MODE or manifest.get("extension") != "mindspeed._moonep_compute" | ||
| 70 | + or type(manifest.get("native_abi")) is not int or manifest["native_abi"] != ABI_VERSION | ||
| 71 | + or type(manifest.get("training_integration_ready")) is not bool | ||
| 72 | + or manifest.get("fallback") is not False | ||
| 73 | + or manifest.get("format") != "ND" or manifest.get("dtypes") != _DTYPES | ||
| 74 | + or manifest.get("weight_layouts") != ["row-major", "uniform-transpose-view"] | ||
| 75 | + or manifest.get("linear") != "single-token-list-weights-single-direct-out" | ||
| 76 | + or manifest.get("wgrad_contract") != "two-single-bf16-independent-fp32-then-add" | ||
| 77 | + or manifest.get("wgrad_submission") != WGRAD_SUBMISSION | ||
| 78 | + or manifest.get("tenpu_changes") is not False | ||
| 79 | + or manifest.get("canonical_grad_layout") != "prepared-disjoint-targets" | ||
| 80 | + or manifest.get("probability_grad") != "fp32-product-reduce-lastdim-direct-out" | ||
| 81 | + or manifest.get("max_groups") != MAX_GROUPS or manifest.get("symbols") != _SYMBOLS | ||
| 82 | + or manifest.get("completion") != COMPLETION | ||
| 83 | + or manifest.get("execution_profile") != EXECUTION_PROFILE): | ||
| 84 | + raise RuntimeError("MindSpeed MoonEP compute manifest mismatch") | ||
| 85 | + name = "mindspeed._moonep_compute" | ||
| 86 | + spec = importlib.machinery.PathFinder.find_spec(name, [str(directory)]) | ||
| 87 | + present = (spec is not None and type(spec.loader) is importlib.machinery.ExtensionFileLoader | ||
| 88 | + and Path(spec.origin).resolve().parent == directory) | ||
| 89 | + return dict(manifest, prebuilt_extension_present=present, | ||
| 90 | + extension_path=str(Path(spec.origin).resolve()) if present else None) | ||
| 91 | + | ||
| 92 | + | ||
| 93 | +def load_compute_binding(): | ||
| 94 | + """Load only a precompiled extension from this installed MindSpeed tree.""" | ||
| 95 | + library = _audit_library() | ||
| 96 | + facts = preflight_compute() | ||
| 97 | + if not facts["prebuilt_extension_present"]: | ||
| 98 | + raise RuntimeError("prebuilt MindSpeed MoonEP extension missing; no Python/JIT fallback") | ||
| 99 | + name = "mindspeed._moonep_compute" | ||
| 100 | + spec = importlib.machinery.PathFinder.find_spec(name, [str(Path(__file__).resolve().parents[1])]) | ||
| 101 | + with importlib._bootstrap._ModuleLockManager(name): | ||
| 102 | + module = sys.modules.get(name) | ||
| 103 | + if module is None: | ||
| 104 | + module = importlib._bootstrap._load_unlocked(spec) | ||
| 105 | + loaded = getattr(module, "__spec__", None) | ||
| 106 | + if (loaded is None or type(loaded.loader) is not importlib.machinery.ExtensionFileLoader | ||
| 107 | + or Path(loaded.origin).resolve() != Path(spec.origin).resolve() | ||
| 108 | + or type(getattr(module, "ABI_VERSION", None)) is not int or module.ABI_VERSION != ABI_VERSION): | ||
| 109 | + raise RuntimeError("MindSpeed MoonEP extension origin/ABI mismatch") | ||
| 110 | + required = ("library_path", "capabilities", "create_call", "admit_call", "linear_out", | ||
| 111 | + "wgrad_accumulate", "reduce_sum_out", "complete", "checked_current_complete") | ||
| 112 | + missing = [name for name in required if not callable(getattr(module, name, None))] | ||
| 113 | + if missing: | ||
| 114 | + raise RuntimeError("MindSpeed MoonEP extension missing callable ABI2 entrypoints: " | ||
| 115 | + + ", ".join(missing)) | ||
| 116 | + if str(library) != module.library_path(): | ||
| 117 | + raise RuntimeError("native standard library differs from admitted library") | ||
| 118 | + return module | ||
| 119 | + | ||
| 120 | + | ||
| 121 | +def require_native(): | ||
| 122 | + """Explicit runtime-only entry; the adapter owns installed capability gates.""" | ||
| 123 | + return load_compute_binding() | ||
| 124 | + | ||
| 125 | + | ||
| 126 | +def _checked_capabilities(binding, device): | ||
| 127 | + facts = dict(binding.capabilities(device)) | ||
| 128 | + if (type(facts.get("native_abi")) is not int or facts["native_abi"] != ABI_VERSION | ||
| 129 | + or facts.get("mode") != MODE | ||
| 130 | + or facts.get("completion") != COMPLETION | ||
| 131 | + or facts.get("execution_profile") != EXECUTION_PROFILE | ||
| 132 | + or facts.get("wgrad_submission") != WGRAD_SUBMISSION | ||
| 133 | + or type(facts.get("training_integration_ready")) is not bool): | ||
| 134 | + raise RuntimeError("native compute capabilities differ from ABI2 sync-launch contract") | ||
| 135 | + return facts | ||
| 136 | + | ||
| 137 | + | ||
| 138 | +def runtime_identity(device): | ||
| 139 | + """Actual symbol/library facts plus declared targets, never build PASS.""" | ||
| 140 | + binding = require_native() | ||
| 141 | + facts = _checked_capabilities(binding, device) | ||
| 142 | + path = _audit_library() | ||
| 143 | + if facts.get("opapi_library") != str(path): | ||
| 144 | + raise RuntimeError("capability library differs from audited standard library") | ||
| 145 | + return dict(facts, standard_library={"path": str(path), "sha256": _LIBRARY_IDENTITY[1]}, | ||
| 146 | + declared_source_tuple=preflight_compute().get("declared_source_tuple", {}), | ||
| 147 | + source_build_validation="NOT_RUN") | ||
| 148 | + | ||
| 149 | + | ||
| 150 | +def _tensor(tensor, *, dtype, ndim, device=None, contiguous=True): | ||
| 151 | + import torch | ||
| 152 | + | ||
| 153 | + if type(tensor) is not torch.Tensor: | ||
| 154 | + raise TypeError("pass plain detached Tensor aliases; subclass dispatch is unsupported") | ||
| 155 | + if tensor.dtype != dtype or tensor.dim() != ndim or tensor.device.type != "npu": | ||
| 156 | + raise ValueError("invalid compute tensor dtype/rank/device") | ||
| 157 | + if device is not None and tensor.device != device: | ||
| 158 | + raise ValueError("all operands must be on the same NPU") | ||
| 159 | + if tensor.requires_grad or tensor.is_neg() or tensor.is_conj(): | ||
| 160 | + raise ValueError("requires_grad and lazy negative/conjugate views are unsupported") | ||
| 161 | + if contiguous and not tensor.is_contiguous(): | ||
| 162 | + raise ValueError("no implicit contiguous fallback") | ||
| 163 | + | ||
| 164 | + | ||
| 165 | +def _range(tensor): | ||
| 166 | + if tensor.numel() == 0: | ||
| 167 | + return (0, 0) | ||
| 168 | + if any(stride < 0 for stride in tensor.stride()): | ||
| 169 | + raise ValueError("negative strides are unsupported") | ||
| 170 | + span = 1 + sum((size - 1) * stride for size, stride in zip(tensor.shape, tensor.stride())) | ||
| 171 | + begin = tensor.data_ptr() | ||
| 172 | + return begin, begin + span * tensor.element_size() | ||
| 173 | + | ||
| 174 | + | ||
| 175 | +def _disjoint(left, right): | ||
| 176 | + a, b = _range(left) | ||
| 177 | + c, d = _range(right) | ||
| 178 | + if a < d and c < b: | ||
| 179 | + raise ValueError("compute operands/outputs overlap") | ||
| 180 | + | ||
| 181 | + | ||
| 182 | +def _nd(tensors): | ||
| 183 | + import torch_npu | ||
| 184 | + | ||
| 185 | + if any(torch_npu.get_npu_format(t) != 2 for t in tensors): | ||
| 186 | + raise ValueError("ND format required; no format-copy fallback") | ||
| 187 | + | ||
| 188 | + | ||
| 189 | +def _groups(counts, groups, rows, device): | ||
| 190 | + import torch | ||
| 191 | + | ||
| 192 | + _tensor(counts, dtype=torch.int64, ndim=1, device=device) | ||
| 193 | + if counts.numel() != groups or not 1 <= groups <= MAX_GROUPS or not 1 <= rows <= 2147483647: | ||
| 194 | + raise ValueError("retain exactly G groups and a positive INT32 physical row count") | ||
| 195 | + # Device values and the counts/prefix relation are admitted once from the | ||
| 196 | + # original plan by the caller. No item(), host counts or duplicate cumsum. | ||
| 197 | + | ||
| 198 | + | ||
| 199 | +def mark_failed(op, error, resources): | ||
| 200 | + """Retain uncertain work only in the original provider's failure owner.""" | ||
| 201 | + retained = (error, *resources) | ||
| 202 | + combined = (*getattr(op, '_native_async_uncertain', ()), *retained) | ||
| 203 | + try: | ||
| 204 | + op.mark_failed(error=error, resources=retained) | ||
| 205 | + except BaseException as failure: | ||
| 206 | + try: | ||
| 207 | + op._native_async_failed = True | ||
| 208 | + op._native_async_uncertain = combined | ||
| 209 | + note = 'public marker failed; original owner quarantine retains resources' | ||
| 210 | + except BaseException: | ||
| 211 | + note = 'public marker and quarantine failed; retention is unproven' | ||
| 212 | + annotate = getattr(error, 'add_note', None) | ||
| 213 | + if callable(annotate): | ||
| 214 | + try: | ||
| 215 | + annotate(note + ': ' + repr(failure)) | ||
| 216 | + except BaseException: | ||
| 217 | + pass | ||
| 218 | + | ||
| 219 | + | ||
| 220 | +def _execute(op, owner, borrowed, action, written, *, prepare=None): | ||
| 221 | + """One explicit sync-launch Call; the original Buffer owns its token.""" | ||
| 222 | + import torch | ||
| 223 | + import torch_npu | ||
| 224 | + | ||
| 225 | + for name in ("_require_ctx", "mark_failed"): | ||
| 226 | + if not callable(getattr(op, name, None)): | ||
| 227 | + raise TypeError("the original provider context/failure owner is required") | ||
| 228 | + if op._require_ctx()['device'] != owner.device.index: | ||
| 229 | + raise ValueError('provider and compute current device differ') | ||
| 230 | + binding = load_compute_binding() | ||
| 231 | + _checked_capabilities(binding, owner.device.index) | ||
| 232 | + npu = torch_npu.npu | ||
| 233 | + call = launch = token = None | ||
| 234 | + try: | ||
| 235 | + caller = npu.current_stream(owner.device.index) | ||
| 236 | + raw_caller = int(caller.npu_stream) | ||
| 237 | + if raw_caller <= 0: | ||
| 238 | + raise RuntimeError("caller raw stream is null or invalid") | ||
| 239 | + # Public NPUStream.synchronize rejects an external stream ID. It adds | ||
| 240 | + # one conservative synchronization; the checked helper still verifies | ||
| 241 | + # non-null/same Q1 drain and restores the caller's ACL resources. | ||
| 242 | + caller.synchronize() | ||
| 243 | + binding.checked_current_complete(owner.device.index, raw_caller) | ||
| 244 | + launch = npu.SyncLaunchStream(device=owner.device.index) | ||
| 245 | + with npu.stream(launch): | ||
| 246 | + call = binding.create_call(owner, tuple(borrowed)) # Metadata only. | ||
| 247 | + if int(npu.current_stream(owner.device.index).npu_stream) != raw_caller: | ||
| 248 | + raise RuntimeError("caller stream was not restored after Call creation") | ||
| 249 | + token = (call, launch) | ||
| 250 | + # The synchronous stack owns the Call/launch until local completion; | ||
| 251 | + # original PR19 receives them before unwinding any uncertain failure. | ||
| 252 | + with npu.stream(launch): | ||
| 253 | + binding.admit_call(call) # Actual cached block; before any producer zero. | ||
| 254 | + if prepare is not None: | ||
| 255 | + prepare() | ||
| 256 | + action(binding, call) | ||
| 257 | + binding.complete(call) | ||
| 258 | + if int(npu.current_stream(owner.device.index).npu_stream) != raw_caller: | ||
| 259 | + raise RuntimeError("caller stream was not restored after native execution") | ||
| 260 | + binding.checked_current_complete(owner.device.index, raw_caller) | ||
| 261 | + torch.autograd.graph.increment_version(written) | ||
| 262 | + except BaseException as error: | ||
| 263 | + # Native contexts restore the original stream before this handler. | ||
| 264 | + # Uncertain Call/launch/workspace remain in the existing owner ledger. | ||
| 265 | + mark_failed(op, error, (token, call, launch, owner, borrowed, written)) | ||
| 266 | + raise | ||
| 267 | + return written | ||
| 268 | + | ||
| 269 | + | ||
| 270 | +def grouped_linear_out(op, x, refs, counts, out, *, transpose_weights): | ||
| 271 | + """One BF16 token Tensor, G row-major weight refs, one direct BF16 out.""" | ||
| 272 | + import torch | ||
| 273 | + | ||
| 274 | + if type(transpose_weights) is not bool or not isinstance(refs, (list, tuple)): | ||
| 275 | + raise TypeError("ordered refs and a uniform transpose bool are required") | ||
| 276 | + refs = tuple(refs) | ||
| 277 | + _tensor(x, dtype=torch.bfloat16, ndim=2) | ||
| 278 | + _tensor(out, dtype=torch.bfloat16, ndim=2, device=x.device) | ||
| 279 | + _groups(counts, len(refs), x.shape[0], x.device) | ||
| 280 | + if out.shape[0] != x.shape[0] or min(x.shape[1], out.shape[1]) <= 0: | ||
| 281 | + raise ValueError("linear input/output shape mismatch") | ||
| 282 | + for source in (x, counts): | ||
| 283 | + _disjoint(out, source) | ||
| 284 | + for weight in refs: | ||
| 285 | + _tensor(weight, dtype=torch.bfloat16, ndim=2, device=x.device) | ||
| 286 | + expected = (out.shape[1], x.shape[1]) if transpose_weights else (x.shape[1], out.shape[1]) | ||
| 287 | + if tuple(weight.shape) != expected: | ||
| 288 | + raise ValueError("weight shape mismatch") | ||
| 289 | + _disjoint(out, weight) | ||
| 290 | + _nd((x, counts, out) + refs) | ||
| 291 | + views = tuple(weight.t() for weight in refs) if transpose_weights else refs | ||
| 292 | + return _execute(op, x, (x, counts, out) + views, | ||
| 293 | + lambda binding, call: binding.linear_out(call, x, views, counts, out), out) | ||
| 294 | + | ||
| 295 | + | ||
| 296 | +def validate_wgrad_targets(scratch, targets, *, local_experts, scratch_budget_bytes): | ||
| 297 | + """Metadata-only admission for the complete canonical-plus-remote target set.""" | ||
| 298 | + import torch | ||
| 299 | + | ||
| 300 | + if not isinstance(targets, (list, tuple)) or not targets: | ||
| 301 | + raise ValueError("ordered full-G targets are required") | ||
| 302 | + targets = tuple(targets) | ||
| 303 | + if type(local_experts) is not int or local_experts <= 0 or len(targets) != 2 * local_experts: | ||
| 304 | + raise ValueError("combined-head requires ordered L canonical plus B=L remote targets") | ||
| 305 | + _tensor(scratch, dtype=torch.float32, ndim=3) | ||
| 306 | + shape = tuple(scratch.shape) | ||
| 307 | + required = full_g_scratch_bytes(len(targets), (shape[1:],)) | ||
| 308 | + if (shape[0] != len(targets) | ||
| 309 | + or type(scratch_budget_bytes) is not int or scratch_budget_bytes < required): | ||
| 310 | + raise ValueError("full-G shape/budget mismatch; no automatic chunk mode") | ||
| 311 | + for index, target in enumerate(targets): | ||
| 312 | + _tensor(target, dtype=torch.float32, ndim=2, device=scratch.device) | ||
| 313 | + if tuple(target.shape) != shape[1:]: | ||
| 314 | + raise ValueError("wgrad target shape mismatch") | ||
| 315 | + for source in (scratch,) + targets[:index]: | ||
| 316 | + _disjoint(target, source) | ||
| 317 | + _nd((scratch,) + targets) | ||
| 318 | + return targets | ||
| 319 | + | ||
| 320 | + | ||
| 321 | +def validate_full_g_wgrad(x, dy, counts, prefix, scratch, targets, *, | ||
| 322 | + local_experts, scratch_budget_bytes): | ||
| 323 | + """Validate all producer inputs and targets before any zero or publication.""" | ||
| 324 | + import torch | ||
| 325 | + | ||
| 326 | + targets = validate_wgrad_targets(scratch, targets, local_experts=local_experts, | ||
| 327 | + scratch_budget_bytes=scratch_budget_bytes) | ||
| 328 | + _tensor(x, dtype=torch.bfloat16, ndim=2, device=scratch.device) | ||
| 329 | + _tensor(dy, dtype=torch.bfloat16, ndim=2, device=x.device) | ||
| 330 | + _groups(counts, len(targets), x.shape[0], x.device) | ||
| 331 | + _groups(prefix, len(targets), x.shape[0], x.device) | ||
| 332 | + if dy.shape[0] != x.shape[0] or tuple(scratch.shape[1:]) != (dy.shape[1], x.shape[1]): | ||
| 333 | + raise ValueError("full-G producer shape mismatch") | ||
| 334 | + for source in (x, dy, counts, prefix): | ||
| 335 | + for destination in (scratch,) + targets: | ||
| 336 | + _disjoint(destination, source) | ||
| 337 | + _nd((x, dy, counts, prefix)) | ||
| 338 | + return targets | ||
| 339 | + | ||
| 340 | + | ||
| 341 | +def full_g_wgrad_out(op, x, dy, counts, prefix, scratch): | ||
| 342 | + """Independent full-G FP32 producer; publication is a separate callback.""" | ||
| 343 | + import torch | ||
| 344 | + | ||
| 345 | + _tensor(scratch, dtype=torch.float32, ndim=3) | ||
| 346 | + _tensor(x, dtype=torch.bfloat16, ndim=2, device=scratch.device) | ||
| 347 | + _tensor(dy, dtype=torch.bfloat16, ndim=2, device=x.device) | ||
| 348 | + _groups(counts, scratch.shape[0], x.shape[0], x.device) | ||
| 349 | + _groups(prefix, scratch.shape[0], x.shape[0], x.device) | ||
| 350 | + if dy.shape[0] != x.shape[0] or tuple(scratch.shape[1:]) != (dy.shape[1], x.shape[1]): | ||
| 351 | + raise ValueError("full-G producer shape mismatch") | ||
| 352 | + for source in (x, dy, counts, prefix): | ||
| 353 | + _disjoint(scratch, source) | ||
| 354 | + _nd((x, dy, counts, prefix, scratch)) | ||
| 355 | + return _execute(op, x, (x, dy, counts, prefix, scratch), | ||
| 356 | + lambda binding, call: binding.wgrad_accumulate(call, scratch, dy, x, prefix), | ||
| 357 | + scratch, prepare=scratch.zero_) | ||
| 358 | + | ||
| 359 | + | ||
| 360 | +def reduce_sum_lastdim_out(op, product_fp32, out_fp32): | ||
| 361 | + """Reduce an independent FP32 product directly into caller-owned P/dP.""" | ||
| 362 | + import torch | ||
| 363 | + | ||
| 364 | + _tensor(product_fp32, dtype=torch.float32, ndim=2) | ||
| 365 | + _tensor(out_fp32, dtype=torch.float32, ndim=1, device=product_fp32.device) | ||
| 366 | + if out_fp32.shape[0] != product_fp32.shape[0] or min(product_fp32.shape) <= 0: | ||
| 367 | + raise ValueError("last-dimension reduction shape mismatch") | ||
| 368 | + _disjoint(product_fp32, out_fp32) | ||
| 369 | + _nd((product_fp32, out_fp32)) | ||
| 370 | + return _execute(op, product_fp32, (product_fp32, out_fp32), | ||
| 371 | + lambda binding, call: binding.reduce_sum_out(call, product_fp32, out_fp32), out_fp32) | ||
| @@ -0,0 +1,48 @@ | |||
| 1 | +{ | ||
| 2 | + "schema": 2, | ||
| 3 | + "native_abi": 2, | ||
| 4 | + "mode": "mindspeed_shared_slots_full_g_v1", | ||
| 5 | + "extension": "mindspeed._moonep_compute", | ||
| 6 | + "completion": "caller-sync-launch-local-complete", | ||
| 7 | + "training_integration_ready": false, | ||
| 8 | + "native_build_validation": "NOT_RUN", | ||
| 9 | + "device_validation": "NOT_RUN", | ||
| 10 | + "soc_prefix": "Ascend950", | ||
| 11 | + "format": "ND", | ||
| 12 | + "dtypes": { | ||
| 13 | + "linear_input": "bf16", | ||
| 14 | + "linear_output": "bf16", | ||
| 15 | + "wgrad_input": "bf16", | ||
| 16 | + "wgrad_output": "fp32", | ||
| 17 | + "probability_grad": "fp32" | ||
| 18 | + }, | ||
| 19 | + "max_groups": 128, | ||
| 20 | + "weight_layouts": [ | ||
| 21 | + "row-major", | ||
| 22 | + "uniform-transpose-view" | ||
| 23 | + ], | ||
| 24 | + "linear": "single-token-list-weights-single-direct-out", | ||
| 25 | + "wgrad_contract": "two-single-bf16-independent-fp32-then-add", | ||
| 26 | + "wgrad_submission": "canonical-targets-before-gr-v1", | ||
| 27 | + "probability_grad": "fp32-product-reduce-lastdim-direct-out", | ||
| 28 | + "fallback": false, | ||
| 29 | + "tenpu_changes": false, | ||
| 30 | + "declared_source_tuple": { | ||
| 31 | + "tenpu": "f3ce68ba3244720ead26a25d5b388c38293b730c", | ||
| 32 | + "ops_transformer": "545ad5daa4b876a4868403e140c94bb6f6307c0d", | ||
| 33 | + "ops_math": "c0d7ac4cf535709bc79540d4e0f419a8c67c3027", | ||
| 34 | + "opbase": "b603996f1390c8cac895b1afcb348f2f62cfe3da", | ||
| 35 | + "torch_npu": "88d6f1345157e02ea12d412f3f01c668985e94ce", | ||
| 36 | + "op_plugin": "eee88cf400f796c150db5a6203c4218b5af7ea18" | ||
| 37 | + }, | ||
| 38 | + "symbols": [ | ||
| 39 | + "aclnnGroupedMatmulV5GetWorkspaceSize", | ||
| 40 | + "aclnnGroupedMatmulV5", | ||
| 41 | + "aclnnGroupedMatmulAddV2GetWorkspaceSize", | ||
| 42 | + "aclnnGroupedMatmulAddV2", | ||
| 43 | + "aclnnReduceSumGetWorkspaceSize", | ||
| 44 | + "aclnnReduceSum" | ||
| 45 | + ], | ||
| 46 | + "canonical_grad_layout": "prepared-disjoint-targets", | ||
| 47 | + "execution_profile": "caller-sync-launch-v1" | ||
| 48 | +} | ||
| @@ -1,5 +1,6 @@ | |||
| 1 | import os | 1 | import os |
| 2 | import sys | 2 | import sys |
| 3 | +import json | ||
| 3 | from pathlib import Path | 4 | from pathlib import Path |
| 4 | 5 | ||
| 5 | import setuptools | 6 | import setuptools |
| @@ -31,6 +32,57 @@ except FileNotFoundError: | |||
| 31 | cmd_class = {} | 32 | cmd_class = {} |
| 32 | exts = [] | 33 | exts = [] |
| 33 | 34 | ||
| 35 | +# Packaging-only opt-in. Normal installation/import never loads an op builder. | ||
| 36 | +if os.environ.get("MINDSPEED_BUILD_MOONEP_COMPUTE") == "1": | ||
| 37 | + from torch.utils.cpp_extension import BuildExtension | ||
| 38 | + from torch_npu.utils.cpp_extension import NpuExtension | ||
| 39 | + import torch_npu | ||
| 40 | + | ||
| 41 | + # ABI2 delegates snapshot/TLS to the standard public synchronous runner. | ||
| 42 | + # Declarations are only a build prerequisite, never an installed export PASS. | ||
| 43 | + npu_headers = Path(torch_npu.__file__).resolve().parent / 'include/torch_npu/csrc' | ||
| 44 | + for header, symbols in ( | ||
| 45 | + ('core/npu/NPUStream.h', ('isSyncLaunchStream', 'is_core_control_enabled')), | ||
| 46 | + ('framework/OpCommand.h', ('RunOpApiV2',)), | ||
| 47 | + ): | ||
| 48 | + path = npu_headers / header | ||
| 49 | + declarations = path.read_text(encoding='utf-8') if path.is_file() else '' | ||
| 50 | + missing = [symbol for symbol in symbols if symbol not in declarations] | ||
| 51 | + if missing: | ||
| 52 | + raise RuntimeError('MoonEP ABI2 requires installed public sync-launch headers; missing ' | ||
| 53 | + + ', '.join(missing) + ' in ' + str(path)) | ||
| 54 | + if not callable(getattr(torch_npu.npu, 'SyncLaunchStream', None)): | ||
| 55 | + raise RuntimeError('MoonEP ABI2 requires public torch_npu.npu.SyncLaunchStream') | ||
| 56 | + | ||
| 57 | + validation = os.environ.get('MINDSPEED_MOONEP_VALIDATION_BUILD', '0') | ||
| 58 | + if validation not in ('0', '1'): | ||
| 59 | + raise RuntimeError('validation build must be explicitly 0 or 1') | ||
| 60 | + | ||
| 61 | + class MoonEPBuildExtension(BuildExtension): | ||
| 62 | + def run(self): | ||
| 63 | + if validation == '1' and not self.inplace: | ||
| 64 | + raise RuntimeError('validation requires a private source-prebuilt --inplace checkout') | ||
| 65 | + super().run() | ||
| 66 | + manifest = Path('mindspeed/ops/moonep_compute_capabilities.json') | ||
| 67 | + data = json.loads(manifest.read_text()) | ||
| 68 | + data['training_integration_ready'] = validation == '1' | ||
| 69 | + destination = manifest if self.inplace else Path(self.build_lib) / manifest | ||
| 70 | + destination.parent.mkdir(parents=True, exist_ok=True) | ||
| 71 | + destination.write_text(json.dumps(data, indent=2) + '\n') | ||
| 72 | + | ||
| 73 | + cann_root = Path(os.environ.get("ASCEND_HOME_PATH", "")) | ||
| 74 | + if not cann_root.is_absolute() or not (cann_root / "include").is_dir(): | ||
| 75 | + raise RuntimeError("MoonEP compute build requires an absolute ASCEND_HOME_PATH") | ||
| 76 | + exts.append(NpuExtension( | ||
| 77 | + "mindspeed._moonep_compute", | ||
| 78 | + sources=["mindspeed/ops/csrc/cann/moonep_compute.cpp"], | ||
| 79 | + include_dirs=[str(cann_root / "include")], | ||
| 80 | + library_dirs=[str(cann_root / "lib64")], | ||
| 81 | + libraries=["ascendcl", "nnopbase", "dl"], | ||
| 82 | + extra_compile_args=["-std=c++17", '-DMINDSPEED_MOONEP_VALIDATION_WIRING=' + validation], | ||
| 83 | + )) | ||
| 84 | + cmd_class["build_ext"] = MoonEPBuildExtension | ||
| 85 | + | ||
| 34 | 86 | ||
| 35 | def package_files(directory): | 87 | def package_files(directory): |
| 36 | paths = [] | 88 | paths = [] |
| @@ -80,12 +132,13 @@ setuptools.setup( | |||
| 80 | include_package_data=True, | 132 | include_package_data=True, |
| 81 | install_package_data=True, | 133 | install_package_data=True, |
| 82 | exclude_package_data={'': ['**/*.md']}, | 134 | exclude_package_data={'': ['**/*.md']}, |
| 83 | - package_data={'': package_files(src_path)}, | 135 | + package_data={'': package_files(src_path), |
| 136 | + 'mindspeed.ops': ['moonep_compute_capabilities.json']}, | ||
| 84 | bug_data={'mindspeed': ['**/*.h', '**/*.cpp', '*/*.sh', '**/*.patch']}, | 137 | bug_data={'mindspeed': ['**/*.h', '**/*.cpp', '*/*.sh', '**/*.patch']}, |
| 85 | zip_safe=False, | 138 | zip_safe=False, |
| 86 | # PyPI package information. | 139 | # PyPI package information. |
| 87 | keywords=__keywords__, | 140 | keywords=__keywords__, |
| 88 | - cmdclass={}, | 141 | + cmdclass=cmd_class, |
| 89 | entry_points={}, | 142 | entry_points={}, |
| 90 | ext_modules=exts, | 143 | ext_modules=exts, |
| 91 | ) | 144 | ) |
| @@ -0,0 +1,230 @@ | |||
| 1 | +"""Shared inert tensor metadata for host MoonEP contracts, never a math oracle.""" | ||
| 2 | + | ||
| 3 | +import importlib.util | ||
| 4 | +import math | ||
| 5 | +import sys | ||
| 6 | +import types | ||
| 7 | + | ||
| 8 | + | ||
| 9 | +def load_source(name, path): | ||
| 10 | + spec = importlib.util.spec_from_file_location(name, path) | ||
| 11 | + module = importlib.util.module_from_spec(spec) | ||
| 12 | + sys.modules[name] = module | ||
| 13 | + spec.loader.exec_module(module) | ||
| 14 | + return module | ||
| 15 | + | ||
| 16 | + | ||
| 17 | +class Tensor: | ||
| 18 | + next_address = 1000000 | ||
| 19 | + events = [] | ||
| 20 | + event_style = "training" | ||
| 21 | + | ||
| 22 | + def __init__(self, shape, dtype="bf16", device="npu:0", *, address=None, | ||
| 23 | + strides=None, counter=None, payload=None, contiguous=True): | ||
| 24 | + self.shape, self.dtype, self.device = tuple(shape), dtype, device | ||
| 25 | + self.address = Tensor.next_address if address is None else address | ||
| 26 | + Tensor.next_address += 1000000 | ||
| 27 | + self.strides = tuple(strides) if strides is not None else self._row_major(self.shape) | ||
| 28 | + self.counter, self.payload = ([0] if counter is None else counter), ({} if payload is None else payload) | ||
| 29 | + self.storage_address, self.storage_bytes = self.address, math.prod(self.shape) * self.element_size() | ||
| 30 | + self.requires_grad, self.contiguous = False, contiguous | ||
| 31 | + self.fail_add, self.negative, self.conjugate, self.format = False, False, False, 2 | ||
| 32 | + | ||
| 33 | + @staticmethod | ||
| 34 | + def _row_major(shape): | ||
| 35 | + return tuple(math.prod(shape[i + 1:]) for i in range(len(shape))) | ||
| 36 | + | ||
| 37 | + @property | ||
| 38 | + def ndim(self): | ||
| 39 | + return len(self.shape) | ||
| 40 | + | ||
| 41 | + @property | ||
| 42 | + def _version(self): | ||
| 43 | + return self.counter[0] | ||
| 44 | + | ||
| 45 | + @property | ||
| 46 | + def value(self): | ||
| 47 | + return self.payload.get(self.address, 0) | ||
| 48 | + | ||
| 49 | + @value.setter | ||
| 50 | + def value(self, value): | ||
| 51 | + self.payload[self.address] = value | ||
| 52 | + | ||
| 53 | + def dim(self): | ||
| 54 | + return self.ndim | ||
| 55 | + | ||
| 56 | + def numel(self): | ||
| 57 | + return math.prod(self.shape) | ||
| 58 | + | ||
| 59 | + def element_size(self): | ||
| 60 | + return {"bf16": 2, "fp32": 4, "i64": 8, "int64": 8, "i32": 4, "int32": 4, "bool": 1}[self.dtype.lower()] | ||
| 61 | + | ||
| 62 | + def stride(self): | ||
| 63 | + return self.strides | ||
| 64 | + | ||
| 65 | + def is_contiguous(self): | ||
| 66 | + return self.contiguous and self.strides == self._row_major(self.shape) | ||
| 67 | + | ||
| 68 | + def is_neg(self): | ||
| 69 | + return self.negative | ||
| 70 | + | ||
| 71 | + def is_conj(self): | ||
| 72 | + return self.conjugate | ||
| 73 | + | ||
| 74 | + def data_ptr(self): | ||
| 75 | + return self.address | ||
| 76 | + | ||
| 77 | + def storage_offset(self): | ||
| 78 | + return (self.address - self.storage_address) // self.element_size() | ||
| 79 | + | ||
| 80 | + def untyped_storage(self): | ||
| 81 | + return types.SimpleNamespace(data_ptr=lambda: self.storage_address, | ||
| 82 | + _cdata=getattr(self, 'storage_cdata', self.storage_address), | ||
| 83 | + nbytes=lambda: getattr(self, "backing_bytes", self.storage_bytes)) | ||
| 84 | + | ||
| 85 | + def _view(self, shape, *, address=None, strides=None): | ||
| 86 | + cls = ComputeTensor if self.event_style == "compute" else Tensor | ||
| 87 | + result = cls(shape, self.dtype, self.device, address=self.address if address is None else address, | ||
| 88 | + counter=self.counter, payload=self.payload, strides=strides) | ||
| 89 | + result.storage_address, result.storage_bytes = self.storage_address, self.storage_bytes | ||
| 90 | + return result | ||
| 91 | + | ||
| 92 | + def as_strided(self, size, stride, storage_offset=None): | ||
| 93 | + offset = self.storage_offset() if storage_offset is None else storage_offset | ||
| 94 | + return self._view(size, address=self.storage_address + offset * self.element_size(), strides=stride) | ||
| 95 | + | ||
| 96 | + def detach(self): | ||
| 97 | + return self._view(self.shape) | ||
| 98 | + | ||
| 99 | + def view(self, *shape): | ||
| 100 | + shape = shape[0] if len(shape) == 1 and isinstance(shape[0], tuple) else shape | ||
| 101 | + if -1 in shape: | ||
| 102 | + known = math.prod(d for d in shape if d != -1) | ||
| 103 | + shape = tuple(self.numel() // known if d == -1 else d for d in shape) | ||
| 104 | + return self._view(shape) | ||
| 105 | + | ||
| 106 | + def t(self): | ||
| 107 | + return self._view(self.shape[::-1], strides=self.strides[::-1]) | ||
| 108 | + | ||
| 109 | + def __getitem__(self, index): | ||
| 110 | + if isinstance(index, tuple): | ||
| 111 | + return Tensor((self.shape[0], 1), self.dtype, self.device) | ||
| 112 | + if isinstance(index, slice): | ||
| 113 | + start, stop, step = index.indices(self.shape[0]) | ||
| 114 | + return self._view((len(range(start, stop, step)), *self.shape[1:]), | ||
| 115 | + address=self.address + start * self.strides[0] * self.element_size()) | ||
| 116 | + return self._view(self.shape[1:], | ||
| 117 | + address=self.address + index * self.strides[0] * self.element_size()) | ||
| 118 | + | ||
| 119 | + def unbind(self, dim): | ||
| 120 | + return tuple(self[i] for i in range(self.shape[dim])) | ||
| 121 | + | ||
| 122 | + def float(self): | ||
| 123 | + return Tensor(self.shape, "fp32", self.device) | ||
| 124 | + | ||
| 125 | + def to(self, dtype): | ||
| 126 | + return Tensor(self.shape, dtype, self.device) | ||
| 127 | + | ||
| 128 | + def __mul__(self, other): | ||
| 129 | + return Tensor(self.shape, self.dtype, self.device) | ||
| 130 | + | ||
| 131 | + def __ne__(self, other): | ||
| 132 | + value = Tensor((), "i32", self.device) | ||
| 133 | + value.value = self.value != other | ||
| 134 | + return value | ||
| 135 | + | ||
| 136 | + def item(self): | ||
| 137 | + return self.value | ||
| 138 | + | ||
| 139 | + def zero_(self): | ||
| 140 | + self.events.append(("zero", self) if self.event_style == "compute" else ("zero", self.shape, self.address)) | ||
| 141 | + for item in self.unbind(0) if self.ndim == 3 else (self,): | ||
| 142 | + item.value = 0 | ||
| 143 | + self.counter[0] += 1 | ||
| 144 | + return self | ||
| 145 | + | ||
| 146 | + def add_(self, source): | ||
| 147 | + self.events.append(("add", self, source) if self.event_style == "compute" else ("add", self.shape, self.address)) | ||
| 148 | + self.value += source.value | ||
| 149 | + self.counter[0] += 1 | ||
| 150 | + if self.fail_add: | ||
| 151 | + raise RuntimeError("injected target add failure" if self.event_style == "compute" else "partial canonical add") | ||
| 152 | + return self | ||
| 153 | + | ||
| 154 | + def masked_fill_(self, mask, value): | ||
| 155 | + self.events.append(("pad", self.shape)) | ||
| 156 | + self.counter[0] += 1 | ||
| 157 | + return self | ||
| 158 | + | ||
| 159 | + | ||
| 160 | +class ComputeTensor(Tensor): | ||
| 161 | + event_style = "compute" | ||
| 162 | + | ||
| 163 | + def __init__(self, shape, dtype="bf16", device=0, **kwargs): | ||
| 164 | + if isinstance(device, int): | ||
| 165 | + device = types.SimpleNamespace(type="npu", index=device) | ||
| 166 | + super().__init__(shape, dtype, device, **kwargs) | ||
| 167 | + | ||
| 168 | + | ||
| 169 | +class ControlTensor: | ||
| 170 | + """Fixed host-derived collective metadata only, never routing payload.""" | ||
| 171 | + def __init__(self, values, device='npu:0'): | ||
| 172 | + self.values, self.device = list(values), device | ||
| 173 | + | ||
| 174 | + def item(self): | ||
| 175 | + return self.values[0] | ||
| 176 | + | ||
| 177 | + def clone(self): | ||
| 178 | + return ControlTensor(self.values, self.device) | ||
| 179 | + | ||
| 180 | + | ||
| 181 | +def prepared_binding(refs, source): | ||
| 182 | + """Inert model of PR19 prepared metadata; no native/data computation.""" | ||
| 183 | + refs = tuple(refs) | ||
| 184 | + signature = lambda tensor: (tensor.data_ptr(), tensor.shape, tensor.stride(), | ||
| 185 | + tensor.storage_offset(), tensor.dtype, tensor.device) | ||
| 186 | + signatures = tuple(map(signature, refs)) | ||
| 187 | + def validate(actual): | ||
| 188 | + if tuple(map(signature, actual)) != signatures: | ||
| 189 | + raise ValueError('prepared storage was rebound or its layout changed') | ||
| 190 | + return types.SimpleNamespace(refs=refs, sources=refs, slot=source, slot_source=source, | ||
| 191 | + table=Tensor((len(refs),), 'i64', source.device), validate_refs=validate) | ||
| 192 | + | ||
| 193 | + | ||
| 194 | +class Parameter(Tensor): | ||
| 195 | + def __init__(self, shape): | ||
| 196 | + if isinstance(shape, Tensor): | ||
| 197 | + super().__init__(shape.shape, shape.dtype, shape.device, address=shape.address, | ||
| 198 | + counter=shape.counter, payload=shape.payload, strides=shape.strides) | ||
| 199 | + self.storage_address, self.storage_bytes = shape.storage_address, shape.storage_bytes | ||
| 200 | + else: | ||
| 201 | + super().__init__(shape) | ||
| 202 | + self.requires_grad = True | ||
| 203 | + self.main_grad = Tensor(self.shape, "fp32") | ||
| 204 | + | ||
| 205 | + | ||
| 206 | +class ShapeTensor(Tensor): | ||
| 207 | + def __init__(self, shape, contiguous=True): | ||
| 208 | + super().__init__(shape, contiguous=contiguous) | ||
| 209 | + | ||
| 210 | + | ||
| 211 | +class AdapterParameter(Parameter): | ||
| 212 | + def __init__(self, shape): | ||
| 213 | + super().__init__(shape) | ||
| 214 | + self.dtype, self.main_grad.dtype = "BF16", "FP32" | ||
| 215 | + | ||
| 216 | + | ||
| 217 | +def canonical_linear(parameters): | ||
| 218 | + """Ordinary grouped module metadata with an existing DDP-owned grad bank.""" | ||
| 219 | + shape = parameters[0].shape | ||
| 220 | + grad = Tensor((len(parameters), *shape), parameters[0].main_grad.dtype, parameters[0].device) | ||
| 221 | + linear = types.SimpleNamespace(in_features=shape[1], out_features=shape[0], | ||
| 222 | + use_bias=False, num_gemms=len(parameters), _parameters={}, _forward_pre_hooks={}) | ||
| 223 | + for index, parameter in enumerate(parameters): | ||
| 224 | + parameter.main_grad = grad[index] | ||
| 225 | + name = f"weight{index}" | ||
| 226 | + linear._parameters[name] = parameter | ||
| 227 | + setattr(linear, name, parameter) | ||
| 228 | + linear.get_parameter = lambda name: linear._parameters[name] | ||
| 229 | + linear.modules = lambda: iter((linear,)) | ||
| 230 | + return linear | ||