forked from apple/coreai-torch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_utils.py
More file actions
1997 lines (1684 loc) · 74.1 KB
/
Copy path_utils.py
File metadata and controls
1997 lines (1684 loc) · 74.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Copyright 2026 Apple Inc.
#
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE file or at https://opensource.org/licenses/BSD-3-Clause
import math
import os
import re
import sys
from collections.abc import Iterable, Iterator, Sequence
from contextlib import contextmanager
from dataclasses import dataclass
from typing import Any, Callable
import numpy as np
import torch
import torch.fx as fx
from coreai._compiler.dialects import coreai
from coreai._compiler.ir import (
F16Type,
F32Type,
IntegerType,
Location,
OpResult,
RankedTensorType,
ShapedType,
Type,
Value,
)
from rich.progress import (
BarColumn,
MofNCompleteColumn,
Progress,
SpinnerColumn,
TaskProgressColumn,
TextColumn,
TimeElapsedColumn,
)
from rich.text import Text
from torch import Tensor
from torch.export import Dim
from torch.export.exported_program import ExportedProgram
from torch.export.graph_signature import ExportGraphSignature
from torch.fx.node import Argument
from ._composite_declaration import generate_composite_decl
from ._type_mapping import (
TORCH_TO_COREAI_DTYPE,
_get_coreai_to_torch_dtype,
)
class _BarColumn(BarColumn):
"""``BarColumn`` that renders empty for indeterminate (``total=None``) tasks.
Suppresses rich's pulsing-bar animation, which is laggy when the host
loop calls ``advance()`` frequently. Determinate tasks still get a
normal bar.
"""
def render(self, task: Any) -> Any:
if task.total is None:
return Text("")
return super().render(task)
class _ProgressBar:
"""Progress display backed by ``rich.progress.Progress``.
Two construction modes:
- ``_ProgressBar()`` — empty multi-task host. Iterate sub-sequences
via :meth:`track`; pass ``transient=True`` to have a sub-bar
disappear when its iteration finishes.
- ``_ProgressBar(total=N, description=...)`` — starts a single
streaming task driven by :meth:`update` / :meth:`set_postfix`.
Usable as a context manager.
"""
def __init__(self, *, total: int | None = None, description: str = "") -> None:
self._progress = Progress(
SpinnerColumn(),
TextColumn("[progress.description]{task.description}"),
_BarColumn(),
MofNCompleteColumn(),
TaskProgressColumn(),
TimeElapsedColumn(),
TextColumn("{task.fields[postfix]}"),
disable=not sys.stdout.isatty(),
)
self._progress.start()
self._task_id = (
self._progress.add_task(description, total=total, postfix="")
if total is not None
else None
)
def track(
self,
items: Iterable[Any],
*,
description: str,
transient: bool = False,
) -> Iterator[Any]:
task_id = self._progress.add_task(
description,
total=len(items),
postfix="", # type: ignore[arg-type]
)
for item in items:
yield item
self._progress.advance(task_id)
if transient:
self._progress.remove_task(task_id)
def update(self, n: int = 1) -> None:
assert self._task_id is not None, (
"update() requires _ProgressBar(total=..., description=...)"
)
self._progress.advance(self._task_id, n)
def set_postfix(self, fields: dict[str, Any]) -> None:
assert self._task_id is not None, (
"set_postfix() requires _ProgressBar(total=..., description=...)"
)
text = ", ".join(f"{k}={v}" for k, v in fields.items())
self._progress.update(self._task_id, postfix=text)
def print(self, *args: Any, **kwargs: Any) -> None:
"""Print through the bar's console so output stays in one stream."""
self._progress.console.print(*args, **kwargs)
@contextmanager
def stream(self, description: str) -> Iterator[Callable[[], None]]:
"""Yield an ``advance()`` callback for a transient indeterminate task.
Use when the iterable can't be materialized upfront (e.g. a stateful
generator whose body must run between yields). The caller calls
``advance()`` after each item is processed; the task is removed when
the block exits. The bar widget is suppressed (see
:class:`_BarColumn`); the user sees spinner + description + ``n/?``
count + elapsed time.
"""
task_id = self._progress.add_task(description, total=None, postfix="")
yield lambda: self._progress.advance(task_id)
self._progress.remove_task(task_id)
@contextmanager
def status(self, description: str) -> Iterator[None]:
"""Show a transient spinner-only display during a slow opaque step.
The existing progress bars are paused (and their display cleared,
not left in scrollback) for the duration of the block — rich
permits only one live display at a time — and resume when the
block exits. The spinner clears with no scrollback.
"""
live = self._progress.live
prev_transient = live.transient
live.transient = True
self._progress.stop()
live.transient = prev_transient
with self._progress.console.status(description):
yield
self._progress.start()
def close(self) -> None:
self._progress.stop()
def __enter__(self) -> "_ProgressBar":
return self
def __exit__(self, *exc: Any) -> None:
self.close()
def to_rank1_int32(v: Value) -> Value:
"""Coerce a SymInt-derived Value to canonical rank-1 si32 form.
Dim-vector concats (used to build shape operands for ``coreai.reshape``,
``coreai.interpolate``, etc.) require all inputs to share rank and
element type. SymInt values can arrive rank-0 (e.g. from
``aten._local_scalar_dense``) or with a different int variant. This
helper produces the form that aligns with ``coreai.constant([i],
dtype=np.int32)`` and ``replace_sym_size_int``.
"""
if v.type.rank == 0:
v = coreai.reshape(v, [1])
if v.type.element_type != IntegerType.get_signed(32):
v = coreai.cast(v, np.int32)
return v
def upsample_build_output_shape_dynamic(
x: Value, out_h: int | Value, out_w: int | Value
) -> Value:
"""Build 4D [N, C, H, W] output_shape as a runtime Value.
Used when either input dims or output sizes are dynamic (runtime Values).
"""
assert (
any(d < 0 for d in x.type.shape)
or isinstance(out_h, Value)
or isinstance(out_w, Value)
), (
"upsample_build_output_shape_dynamic called with fully static input and output; "
"use a plain list [N, C, H, W] instead"
)
shape = coreai.cast(coreai.get_shape(x), dtype=np.int32)
non_spatial = coreai.slice_(shape, [0], [2], [1])
h = [out_h] if isinstance(out_h, int) else to_rank1_int32(out_h)
w = [out_w] if isinstance(out_w, int) else to_rank1_int32(out_w)
return coreai.concat(0, [non_spatial, h, w])
def upsample_halfpixel_scale(x: Value, out_h: int | Value, out_w: int | Value) -> Value:
"""Compute HalfPixel scale vector [1, 1, out_h/in_h, out_w/in_w] at runtime.
Works for both static and dynamic input spatial dims.
out_h / out_w can be static ints or runtime Values (shape [1]).
"""
shape = coreai.get_shape(x)
in_h_f32 = coreai.cast(coreai.slice_(shape, [2], [3], [1]), np.float32)
in_w_f32 = coreai.cast(coreai.slice_(shape, [3], [4], [1]), np.float32)
out_h_f32 = (
coreai.cast(out_h, np.float32)
if isinstance(out_h, Value)
else coreai.constant(np.array([float(out_h)], dtype=np.float32))
)
out_w_f32 = (
coreai.cast(out_w, np.float32)
if isinstance(out_w, Value)
else coreai.constant(np.array([float(out_w)], dtype=np.float32))
)
scale_h = coreai.broadcasting_divide(out_h_f32, in_h_f32)
scale_w = coreai.broadcasting_divide(out_w_f32, in_w_f32)
return coreai.concat(0, [[1.0, 1.0], scale_h, scale_w])
def upsample_align_corners_scale_offset(
x: Value, out_h_f32: Value, out_w_f32: Value
) -> tuple[Value, Value]:
"""Compute AlignCorners scale/offset vectors at runtime.
scale_h = (out_h - 1) / (in_h - 1), offset_h = 0.5 * (1 - scale_h).
Works for both static and dynamic input spatial dims.
out_h_f32 / out_w_f32 are float32 rank-1 Values (shape [1]).
"""
shape = coreai.get_shape(x)
in_h_f32 = coreai.cast(coreai.slice_(shape, [2], [3], [1]), np.float32)
in_w_f32 = coreai.cast(coreai.slice_(shape, [3], [4], [1]), np.float32)
one = coreai.constant(np.array([1.0], dtype=np.float32))
half = coreai.constant(np.array([0.5], dtype=np.float32))
scale_h = coreai.broadcasting_divide(
coreai.broadcasting_sub(out_h_f32, one),
coreai.broadcasting_sub(in_h_f32, one),
)
scale_w = coreai.broadcasting_divide(
coreai.broadcasting_sub(out_w_f32, one),
coreai.broadcasting_sub(in_w_f32, one),
)
offset_h = coreai.broadcasting_mul(half, coreai.broadcasting_sub(one, scale_h))
offset_w = coreai.broadcasting_mul(half, coreai.broadcasting_sub(one, scale_w))
return (
coreai.concat(0, [[1.0, 1.0], scale_h, scale_w]),
coreai.concat(0, [[0.0, 0.0], offset_h, offset_w]),
)
def upsample_runtime_output_hw_from_scale_dynamic(
x: Value, scale_h_f: float, scale_w_f: float
) -> tuple[Value, Value, Value, Value]:
"""Compute output H/W at runtime by multiplying input dims by scale factors.
Returns (out_h_f32, out_w_f32, out_h_int, out_w_int) — all rank-1 Values.
Must only be called when the spatial dims of x are dynamic. For static
spatial dims, compute output H/W in Python directly as int(input_h * scale).
"""
assert x.type.shape[2] < 0 or x.type.shape[3] < 0, (
"upsample_runtime_output_hw_from_scale_dynamic called on input with static "
"spatial dims; compute output H/W in Python instead"
)
shape = coreai.get_shape(x)
in_h_f32 = coreai.cast(coreai.slice_(shape, [2], [3], [1]), np.float32)
in_w_f32 = coreai.cast(coreai.slice_(shape, [3], [4], [1]), np.float32)
out_h_f32 = coreai.broadcasting_mul(
in_h_f32, coreai.constant(np.array([scale_h_f], dtype=np.float32))
)
out_w_f32 = coreai.broadcasting_mul(
in_w_f32, coreai.constant(np.array([scale_w_f], dtype=np.float32))
)
out_h_int = coreai.cast(out_h_f32, IntegerType.get_signed(32))
out_w_int = coreai.cast(out_w_f32, IntegerType.get_signed(32))
return out_h_f32, out_w_f32, out_h_int, out_w_int
def get_promoted_type(type1: RankedTensorType, type2: RankedTensorType) -> Type:
"""Return the promoted element type for two tensor types using torch promotion rules."""
m = _get_coreai_to_torch_dtype()
return TORCH_TO_COREAI_DTYPE[
torch.promote_types(m[type1.element_type], m[type2.element_type])
]()
# Narrow int64/fp64 to int32/fp32 since coreai does not handle 64-bit types.
_NARROW_TORCH_DTYPE: dict[torch.dtype, torch.dtype] = {
torch.int64: torch.int32,
torch.float64: torch.float32,
}
def get_tensor_type(
tensor: Tensor, loc: Location | None = None, dtype: torch.dtype | None = None
) -> RankedTensorType:
"""Convert a torch.Tensor to a RankedTensorType.
int64 and float64 are automatically narrowed to int32 and float32 respectively,
since coreai does not handle 64-bit types well.
Float4Tensor packs 2 fp4 values per uint8 byte. After ``torch.export`` the
subclass is lost and the tensor has ``dtype=uint8`` with packed shape. When
the caller passes the real FP4 dtype (via ``dtype`` or ``future_dtype``), we
double the last dimension to recover the logical shape — matching Core AI's
``get_tensor_type`` in ``importer/torch/_components/types.py``.
"""
effective_dtype = (
dtype if dtype is not None else getattr(tensor, "future_dtype", tensor.dtype)
)
if isinstance(effective_dtype, str):
effective_dtype = getattr(torch, effective_dtype)
effective_dtype = _NARROW_TORCH_DTYPE.get(effective_dtype, effective_dtype)
# Detect packed FP4: caller overrode dtype to float4_e2m1fn_x2 but the
# tensor's physical dtype is still uint8 (packed, 2 values per byte).
is_packed_fp4 = (
effective_dtype == torch.float4_e2m1fn_x2 and tensor.dtype == torch.uint8
)
dims = tensor.size()
shape = []
for idx, s in enumerate(dims):
dim = ShapedType.get_dynamic_size() if isinstance(s, torch.SymInt) else s
# Packed FP4: double the last dimension to get logical element count.
if is_packed_fp4 and idx == len(dims) - 1 and not isinstance(s, torch.SymInt):
dim = 2 * dim
shape.append(dim)
return RankedTensorType.get(
shape,
TORCH_TO_COREAI_DTYPE[effective_dtype](),
loc=loc,
)
def get_result_types(node: fx.Node) -> list[RankedTensorType]:
"""Return result types for an FX node.
Handles both single-result nodes (``node.meta["val"]`` is a Tensor)
and multi-result nodes (``node.meta["val"]`` is a list/tuple of Tensors).
"""
val = node.meta["val"]
if isinstance(val, (list, tuple)):
return [get_tensor_type(v) for v in val]
return [get_tensor_type(val)]
def check_result_type(result: Value, expected: object, node: fx.Node, idx: int) -> None:
if not isinstance(expected, Tensor):
return
actual = result.type
if not isinstance(actual, RankedTensorType):
raise ValueError(f"{node.name}[{idx}]: expected RankedTensorType, got {actual}")
# coreai cannot handle int64 / fp64 well
narrow_expected_dtypes = []
if expected.dtype == torch.int64:
narrow_expected_dtypes = [
TORCH_TO_COREAI_DTYPE[torch.int64](),
TORCH_TO_COREAI_DTYPE[torch.int32](),
TORCH_TO_COREAI_DTYPE[torch.uint32](),
]
elif expected.dtype == torch.float64:
narrow_expected_dtypes = [
TORCH_TO_COREAI_DTYPE[torch.float64](),
TORCH_TO_COREAI_DTYPE[torch.float32](),
]
elif expected.dtype == torch.complex64:
# After f16 casting, view_as_complex produces complex<f16> (complex32).
# Accept both, analogous to float64 -> float32 above.
narrow_expected_dtypes = [
TORCH_TO_COREAI_DTYPE[torch.complex64](),
TORCH_TO_COREAI_DTYPE[torch.complex32](),
]
expected_type = get_tensor_type(expected)
if actual.rank != expected_type.rank:
raise ValueError(
f"{node.name}[{idx}]: rank {actual.rank} vs {expected_type.rank}"
)
if len(narrow_expected_dtypes) == 0:
if actual.element_type != expected_type.element_type:
raise ValueError(
f"{node.name}[{idx}]: dtype {actual.element_type} vs {expected_type.element_type}"
)
else:
if not any([actual.element_type == val for val in narrow_expected_dtypes]):
raise ValueError(
f"{node.name}[{idx}]: dtype {actual.element_type} vs {narrow_expected_dtypes}"
)
dyn = ShapedType.get_dynamic_size()
for i, (a, e) in enumerate(zip(actual.shape, expected_type.shape)):
if a != dyn and e != dyn and a != e:
raise ValueError(f"{node.name}[{idx}]: dim[{i}] {a} vs {e}")
def get_target(node: fx.Node) -> str:
"""Return the target name from an FX node."""
return node.target.__name__ if callable(node.target) else str(node.target)
def get_namespace(node: fx.Node) -> str | None:
"""Return the namespace of the FX node's target, or None if it has none."""
if callable(node.target) and hasattr(node.target, "namespace"):
return str(node.target.namespace)
return None
def strip_variant_from_target(target: str) -> str:
"""Strip a known variant suffix from an op target string (e.g. "add.Tensor" -> "add")."""
if "." not in target:
return target
op_name, variant = target.split(".", 1)
if variant in {"default", "Tensor", "Scalar", "dim"}:
return op_name
return target
def prepare_compute_type_for_norm(
input_value: Value,
input_ele_type: Type,
loc: Location | None = None,
) -> tuple[Value, Type, bool]:
"""Upcast fp16 input to fp32 for numerical stability in norm ops; pass other types through."""
if input_ele_type == F16Type.get():
fp32 = F32Type.get()
return coreai.cast(input_value, fp32, loc=loc), fp32, True
return input_value, input_ele_type, False
def get_output_element_type_from_node(node: fx.Node, index: int | None = None) -> Type:
"""Return the element type for a node's output.
Handles Tensor, SymInt, SymFloat, SymBool, and plain Python scalar meta-values.
int64 and float64 are narrowed to int32 and float32.
"""
val = node.meta["val"]
if index is not None:
val = val[index]
if isinstance(val, torch.Tensor):
dtype = val.dtype
elif isinstance(val, (float, torch.SymFloat)):
dtype = torch.float32
elif isinstance(val, (int, torch.SymInt)):
dtype = torch.int32
elif isinstance(val, (bool, torch.SymBool)):
dtype = torch.bool
else:
dtype = val.dtype # fall back to original behaviour
dtype = _NARROW_TORCH_DTYPE.get(dtype, dtype)
return TORCH_TO_COREAI_DTYPE[dtype]()
def get_unnarrowed_output_element_type_from_node(
node: fx.Node, index: int | None = None
) -> Type:
"""Return the element type for a node's output, without int64/float64 narrowing.
Like :func:`get_output_element_type_from_node`, but skips the
``_NARROW_TORCH_DTYPE`` step. Intended for accumulator-style ops (e.g.
``sum``/``prod`` reductions) whose torch semantics require accumulating at
the full promoted width (int64) to avoid overflowing early -- narrowing
the accumulator *before* the op runs silently changes its numeric result,
unlike narrowing a plain value cast, which is lossless-by-convention for
values already known to fit (or that the model owner accepts truncating).
coreai's own IR supports int64 (``si64``) as a first-class type, so
producing it here is not a runtime limitation.
"""
val = node.meta["val"]
if index is not None:
val = val[index]
if isinstance(val, torch.Tensor):
dtype = val.dtype
elif isinstance(val, (float, torch.SymFloat)):
dtype = torch.float32
elif isinstance(val, (int, torch.SymInt)):
dtype = torch.int32
elif isinstance(val, (bool, torch.SymBool)):
dtype = torch.bool
else:
dtype = val.dtype # fall back to original behaviour
return TORCH_TO_COREAI_DTYPE[dtype]()
@dataclass
class _StackedIndexInfo:
"""Stacked indices and permutations for gather_nd/scatter_nd.
The three permutation fields are None when no base transposition is needed.
Attributes:
result_permutation: Permutation to reorder gather_nd output to match PyTorch's expected layout.
inverse_result_permutation: Inverse of result_permutation; used for index_put scatter updates.
base_inverse_permutation: Permutation to restore base to its original axis order after scatter_nd.
"""
base: Value
stacked_indices: Value
result_permutation: Value | None
inverse_result_permutation: Value | None
base_inverse_permutation: Value | None
def _are_indices_contiguous(indices: list[Value | None]) -> bool:
"""Return True if the non-None entries in indices form a contiguous span with no gaps."""
positions = [i for i, idx in enumerate(indices) if idx is not None]
return len(positions) <= 1 or positions[-1] - positions[0] + 1 == len(positions)
def _stack_indices(index_tensors: list[Value], loc: Location) -> Value:
"""Unsqueeze each index tensor along a new trailing dim, then concat to form [..., num_indices]."""
if not index_tensors:
raise ValueError("Cannot stack empty list of indices")
rank = index_tensors[0].type.rank
return coreai.concat(
rank,
[coreai.expand_dims(idx, [rank], loc=loc) for idx in index_tensors],
loc=loc,
)
def _invert_perm(perm: list[int]) -> list[int]:
"""Return the inverse permutation of perm (i.e. inv[perm[i]] == i)."""
inv = [0] * len(perm)
for i, p in enumerate(perm):
inv[p] = i
return inv
def to_uint32_perm(
perm: Value | list[int] | tuple[int, ...],
rank: int,
) -> Value:
"""Resolve negative indices and return a uint32 permutation for TransposeOp."""
if isinstance(perm, Value):
elem = RankedTensorType(perm.type).element_type
if isinstance(elem, IntegerType) and elem.is_unsigned:
return perm
# Resolve negative indices: (perm + rank) % rank turns e.g. -1 → rank-1.
rank_val = coreai.constant([rank], dtype=np.int32)
resolved = coreai.broadcasting_modulo(
coreai.broadcasting_add(perm, rank_val), rank_val
)
return coreai.cast(resolved, np.uint32)
resolved = [p if p >= 0 else p + rank for p in perm]
return coreai.constant(resolved, dtype=np.uint32)
def _transpose_to_front_and_stack(
base: Value,
indices: list[Value | None],
loc: Location,
require_transpose: bool,
) -> _StackedIndexInfo:
"""Move indexed dimensions to the front of base, then stack the index tensors.
Example (no result permutation needed):
base=[3,4,5,6], indices=[None, idx1, None, idx2] (indexed dims: 1, 3)
perm=[1,3,0,2] -> transposed_base=[4,6,3,5]
base_inverse_perm=[2,0,3,1] (restores original order after scatter_nd)
Example (result permutation needed — contiguous indices not starting at dim 0):
base=[3,4,5,6], indices=[None, None, idx2, idx3] (indexed dims: 2, 3)
gather_nd output: [broadcast, d0, d1]
PyTorch expects: [d0, d1, broadcast]
result_perm=[1,2,0], inverse_result_perm=[2,0,1]
"""
non_none_indices = [idx for idx in indices if idx is not None]
indexed_dims = [i for i, idx in enumerate(indices) if idx is not None]
if not non_none_indices:
raise ValueError("Cannot transpose with no non-None indices")
if not require_transpose:
return _StackedIndexInfo(
base=base,
stacked_indices=_stack_indices(non_none_indices, loc),
result_permutation=None,
inverse_result_permutation=None,
base_inverse_permutation=None,
)
non_indexed_dims = [i for i in range(len(indices)) if i not in indexed_dims]
remaining_dims = list(range(len(indices), base.type.rank))
perm = indexed_dims + non_indexed_dims + remaining_dims
perm_val = to_uint32_perm(perm, base.type.rank)
transposed_base = coreai.transpose(base, perm_val, loc=loc)
base_inv_perm = to_uint32_perm(_invert_perm(perm), base.type.rank)
# For contiguous indices not starting at dim 0, gather_nd places the broadcast
# dims first but PyTorch expects them at the first indexed position.
if _are_indices_contiguous(indices) and indexed_dims[0] > 0:
B = non_none_indices[0].type.rank # broadcast rank
num_before = sum(1 for d in non_indexed_dims if d < indexed_dims[0])
N = len(non_indexed_dims)
result_perm = (
list(range(B, B + num_before)) # non_indexed before
+ list(range(B)) # broadcast
+ list(range(B + num_before, B + N)) # non_indexed after
+ list(range(B + N, B + N + len(remaining_dims)))
)
return _StackedIndexInfo(
base=transposed_base,
stacked_indices=_stack_indices(non_none_indices, loc),
result_permutation=to_uint32_perm(result_perm, len(result_perm)),
inverse_result_permutation=to_uint32_perm(
_invert_perm(result_perm), len(result_perm)
),
base_inverse_permutation=base_inv_perm,
)
return _StackedIndexInfo(
base=transposed_base,
stacked_indices=_stack_indices(non_none_indices, loc),
result_permutation=None,
inverse_result_permutation=None,
base_inverse_permutation=base_inv_perm,
)
def process_expanded_indices(
base: Value,
indices: list[Value | None],
loc: Location,
) -> _StackedIndexInfo:
"""Broadcast already-expanded indices to a common shape, then transpose and stack.
Unlike process_indices_with_transpose, indices are Core AI Values (not FX nodes) and
may have dynamic shapes (e.g. from boolean mask expansion via non_zero).
Dynamic-shape indices are assumed to already match and are passed through without
broadcasting.
"""
non_none_indices = [idx for idx in indices if idx is not None]
if not non_none_indices:
raise ValueError("Index operation requires at least one non-None index tensor")
# Align ranks by prepending leading dims to lower-rank indices.
max_rank = max(idx.type.rank for idx in non_none_indices)
aligned = [
coreai.expand_dims(idx, list(range(max_rank - idx.type.rank)), loc=loc)
if idx.type.rank < max_rank
else idx
for idx in non_none_indices
]
# For static shapes, broadcast to the common shape; dynamic shapes already match.
if not any(dim < 0 for dim in aligned[0].type.shape):
broadcast_shape = coreai.constant(
list(np.broadcast_shapes(*[idx.type.shape for idx in aligned])), loc=loc
)
aligned = [
coreai.broadcast_to(idx, broadcast_shape, loc=loc) for idx in aligned
]
# Reattach None slots.
it = iter(aligned)
broadcasted_indices = [next(it) if idx is not None else None for idx in indices]
contiguous = _are_indices_contiguous(broadcasted_indices)
first_indexed_dim = next(
i for i, idx in enumerate(broadcasted_indices) if idx is not None
)
if contiguous and first_indexed_dim > 0:
broadcasted_indices = _fill_leading_nones_with_ranges(
base, broadcasted_indices, loc
)
require_transpose = False
else:
require_transpose = not (contiguous and first_indexed_dim == 0)
return _transpose_to_front_and_stack(
base, broadcasted_indices, loc, require_transpose
)
def expand_boolean_indices(
base: Value,
values_map: dict[str, Value],
indices_arg: list | tuple,
loc: Location,
) -> list[Value | None]:
"""Convert indices to int32 Values (or None), expanding boolean masks via nonzero.
Example: base=[10,20], indices=[bool_mask(shape=[10,20])]
nonzero(mask) -> [N,2]; extract columns -> [idx0[N], idx1[N]]
"""
base_shape = base.type.shape
expanded: list[Value | None] = []
INT32_MAX = 2**31 - 1
for idx_node in indices_arg:
if idx_node is None:
expanded.append(None)
continue
assert isinstance(idx_node, fx.Node), f"Expected fx.Node, got {type(idx_node)}"
idx_val = values_map[idx_node.name]
# Integer index: ensure int32.
if idx_node.meta["val"].dtype != torch.bool:
if idx_val.type.element_type != IntegerType.get_signed(32):
idx_val = coreai.cast(idx_val, IntegerType.get_signed(32), loc=loc)
expanded.append(idx_val)
continue
# Boolean mask: validate each dimension against base, then extract columns via nonzero.
idx_shape = idx_node.meta["val"].shape
base_offset = len(expanded)
for d, size in enumerate(idx_shape):
dim = base_offset + d
if dim >= len(base_shape):
raise ValueError(
f"Boolean index at position {base_offset} has {len(idx_shape)} dimensions, "
f"but base tensor only has {len(base_shape)} dimensions"
)
if (
base_shape[dim] >= 0
and isinstance(size, int)
and base_shape[dim] != size
):
raise ValueError(
f"Boolean mask shape {idx_shape} does not match base shape "
f"{base_shape} at dim {dim}: expected {base_shape[dim]}, got {size}"
)
# nonzero returns [num_true, num_dims]; slice column d -> [num_true, 1] -> [num_true]
nz = coreai.non_zero(idx_val, loc=loc)
column = coreai.slice_(
nz,
coreai.constant([0, d], loc=loc),
coreai.constant([INT32_MAX, d + 1], loc=loc),
coreai.constant([1, 1], loc=loc),
loc=loc,
)
expanded.append(
coreai.shrink_dims(column, coreai.constant([1], loc=loc), loc=loc)
)
return expanded
def _fill_leading_nones_with_ranges(
base: Value,
indices: Sequence[Value | None],
loc: Location,
) -> list[Value | None]:
"""Fill leading None index slots with range tensors so gather_nd/scatter_nd can
operate on the untransposed base.
For each leading None at position i, creates range(0, base.shape[i]) reshaped to
[dim_size, 1, 1, ...] so it broadcasts with the actual index tensors.
After filling, all indices are broadcast to a common shape.
"""
num_leading_nones = next((i for i, idx in enumerate(indices) if idx is not None), 0)
if num_leading_nones == 0:
return indices
non_none = [idx for idx in indices if idx is not None]
max_index_rank = max(idx.type.rank for idx in non_none)
indices = list(indices)
for i in range(num_leading_nones):
dim_size = base.type.shape[i]
if dim_size >= 0:
dim_range = coreai.constant(list(range(dim_size)), dtype=np.int32)
else:
dim_len_ui32 = coreai.slice_(
coreai.get_shape(base),
[i],
[i + 1],
[1],
)
dim_len = coreai.cast(
coreai.shrink_dims(dim_len_ui32, [0]),
np.int32,
)
dim_range = coreai.range_(
coreai.constant(0, dtype=np.int32),
dim_len,
coreai.constant(1, dtype=np.int32),
)
# Reshape to [dim_size, 1, 1, ...] for broadcasting.
num_trailing_ones = (num_leading_nones - i - 1) + max_index_rank
if num_trailing_ones > 0:
dim_range = coreai.reshape(dim_range, [-1] + [1] * num_trailing_ones)
indices[i] = dim_range
# Broadcast all indices (ranges + originals) to a common shape.
all_non_none = [idx for idx in indices if idx is not None]
target_rank = max(idx.type.rank for idx in all_non_none)
aligned = [
coreai.expand_dims(idx, list(range(target_rank - idx.type.rank)))
if idx.type.rank < target_rank
else idx
for idx in all_non_none
]
shapes = [tuple(idx.type.shape) for idx in aligned]
if not any(d < 0 for s in shapes for d in s):
bcast_shape: list[int] | Value = list(np.broadcast_shapes(*shapes))
else:
shape_tensors = [
coreai.cast(coreai.get_shape(idx), np.uint32) for idx in aligned
]
bcast_shape = shape_tensors[0]
for s in shape_tensors[1:]:
bcast_shape = coreai.broadcast_shapes(bcast_shape, s)
broadcasted = [coreai.broadcast_to(idx, bcast_shape) for idx in aligned]
it = iter(broadcasted)
return [next(it) if idx is not None else None for idx in indices]
def process_indices_with_transpose(
base: Value,
values_map: dict[str, Value],
indices_arg: list | tuple,
loc: Location,
) -> _StackedIndexInfo:
"""Cast FX-node indices to int32, broadcast to a common shape, then transpose and stack.
Example: base=[3,4,5,6], indices=[None, None, node1, node2]
broadcast shape (3,2); transpose base -> [5,6,3,4]; inverse perm [2,3,0,1]
"""
assert isinstance(indices_arg, (list, tuple)), (
f"Expected list/tuple of indices, got {type(indices_arg)}"
)
# Cast each FX node to an int32 Value; keep None slots.
indices: list[Value | None] = [
None
if idx_node is None
else coreai.cast(values_map[idx_node.name], IntegerType.get_signed(32), loc=loc)
for idx_node in indices_arg
]
non_none_indices = [idx for idx in indices if idx is not None]
if not non_none_indices:
raise ValueError("Index operation requires at least one non-None index tensor")
# Check contiguity early so we can skip the pre-broadcast when
# _fill_leading_nones_with_ranges will handle broadcasting for us.
contiguous = _are_indices_contiguous(indices)
first_indexed_dim = next(i for i, idx in enumerate(indices) if idx is not None)
if contiguous and first_indexed_dim > 0:
# Defer broadcasting to _fill_leading_nones_with_ranges which will
# expand all indices (ranges + originals) to the full target rank and
# broadcast in one step. This avoids an intermediate broadcast that
# collapses shape information (e.g. 1024x1 → 1024x1024) followed by
# a reshape to re-add leading 1-dims.
broadcasted_indices = _fill_leading_nones_with_ranges(base, list(indices), loc)
return _transpose_to_front_and_stack(
base, broadcasted_indices, loc, require_transpose=False
)
# Align ranks then broadcast all indices to the common shape.
# Dynamic dims (negative values) are propagated manually since
# np.broadcast_shapes rejects them.
def _broadcast_shapes_with_dynamic(*shapes: tuple[int, ...]) -> list[int]:
max_rank = max(len(s) for s in shapes)
padded = [(1,) * (max_rank - len(s)) + tuple(s) for s in shapes]
result: list[int] = []
for dims in zip(*padded):
if any(d < 0 for d in dims):
result.append(-1)
else:
result.append(int(np.broadcast_shapes(*[(d,) for d in dims])[0]))
return result
broadcast_shape = _broadcast_shapes_with_dynamic(
*[tuple(idx.type.shape) for idx in non_none_indices]
)
target_rank = len(broadcast_shape)
# Use static list for known shapes; use runtime broadcast_shapes for dynamic dims.
# (coreai.constant([-1]) would produce UINT32_MAX after si32→ui32 cast.)
if not any(d < 0 for d in broadcast_shape):
shape_arg: list[int] | Value = broadcast_shape
else:
# Compute broadcast shape at runtime via coreai.broadcast_shapes.
shape_tensors = [coreai.get_shape(idx, loc=loc) for idx in non_none_indices]
shape_arg = shape_tensors[0]
for s in shape_tensors[1:]:
shape_arg = coreai.broadcast_shapes(shape_arg, s, loc=loc)
broadcasted = [
coreai.broadcast_to(
coreai.expand_dims(idx, list(range(target_rank - idx.type.rank)), loc=loc)
if idx.type.rank < target_rank
else idx,
shape_arg,
loc=loc,
)
for idx in non_none_indices
]
# Reattach None slots.
it = iter(broadcasted)
broadcasted_indices = [next(it) if idx is not None else None for idx in indices]
require_transpose = not (contiguous and first_indexed_dim == 0)
return _transpose_to_front_and_stack(
base, broadcasted_indices, loc, require_transpose
)
def get_invoke_from_graph(
values_map: dict[str, Value], node: fx.Node, loc: Location, graph_op: coreai.GraphOp
) -> list[OpResult]:
"""Return the results of a coreai.invoke call targeting graph_op."""
operands = [
get_operand(values_map, node, i, loc)
for i, arg in enumerate(node.args)
if arg is not None
]
result = coreai.invoke(
results=[output.type for output in graph_op.outputs],
callee=graph_op.symbol_name,
operands=operands,
loc=loc,
)
return list(result)
def resolve_slice_arg(
raw: Any, default_val: int, values_map: dict[str, Value]
) -> int | Value:
"""Resolve a raw slice argument (start, end, or stride) from node.args to a static int or dynamic IR Value."""
if raw is None:
return default_val
if isinstance(raw, fx.Node):
return values_map[raw.name]
if isinstance(raw, torch.SymInt):
raise ValueError(
f"Symbolic SymInt slice argument is not supported: {raw!r}. "
"Use fx.Node references (e.g. results of aten.sym_size.int)."
)
val = int(raw)
SLICE_INT32_MAX: int = 2**31 - 1
# ATen uses INT64_MAX (~9.2e18) to mean "slice to end". Core AI indices are
# si32, so values above INT32_MAX overflow to negative (e.g. INT64_MAX → -1),
# causing coreai.slice_ to compute a wrong output shape. Clamp to INT32_MAX.
return min(val, SLICE_INT32_MAX)
def build_slice_index_array(
rank: int, dim: int, default_val: int, value: int | Value
) -> list[int] | Value:
"""Build a rank-length 1-D index array with default_val everywhere except at dim."""
if not isinstance(value, Value):
result = [default_val] * rank
result[dim] = value
return coreai.constant(result)
val_1d = coreai.reshape(value, [1]) if value.type.rank == 0 else value
parts: list[Value] = []
if dim > 0:
parts.append([default_val] * dim)
parts.append(val_1d)
if dim < rank - 1:
parts.append([default_val] * (rank - 1 - dim))
return coreai.concat(0, parts) if len(parts) > 1 else parts[0]
def _is_float_in_float16_range(val: float) -> bool:
"""Return True if val can be represented as float16 without precision loss."""
casted_val: float = torch.tensor(val, dtype=torch.float16).item()
eps = torch.finfo(torch.float16).eps
return math.isclose(val, casted_val, rel_tol=eps, abs_tol=eps)