-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathjit_function.py
More file actions
1553 lines (1281 loc) · 59.6 KB
/
jit_function.py
File metadata and controls
1553 lines (1281 loc) · 59.6 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
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2025 FlyDSL Project Contributors
import ctypes
import fcntl
import hashlib
import inspect
import os
import pickle
import pkgutil
import tempfile
import threading
import time
import types
from collections import namedtuple
from contextlib import contextmanager, nullcontext
from dataclasses import dataclass
from functools import lru_cache, partial
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set
from .._mlir import ir
from .._mlir.dialects import func
from .._mlir.passmanager import PassManager
from ..expr.typing import Constexpr, Stream
from ..utils import env, log
from .ast_rewriter import ASTRewriter
from .backends import compile_backend_name, get_backend
from .jit_argument import convert_to_jit_arguments, is_type_param_annotation
from .jit_executor import CompiledArtifact
from .kernel_function import (
CompilationContext,
FuncLocationTracker,
KernelFunction,
create_gpu_module,
get_gpu_module_body,
)
from .protocol import construct_from_ir_values, get_ir_types
EXTRA_SOURCE_DIRS: List[str] = []
CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "currsize", "disk_size"])
class FileLock:
"""fcntl-based file lock supporting shared and exclusive modes."""
def __init__(self, path, *, exclusive=True, timeout=30):
self._path = str(path)
self._exclusive = exclusive
self._timeout = timeout
self._fd = None
def __enter__(self):
fd = os.open(self._path, os.O_RDWR | os.O_CREAT, 0o644)
self._fd = fd
op = fcntl.LOCK_EX if self._exclusive else fcntl.LOCK_SH
deadline = time.monotonic() + self._timeout
while True:
try:
fcntl.flock(fd, op | fcntl.LOCK_NB)
return self
except (OSError, BlockingIOError):
if time.monotonic() >= deadline:
try:
os.close(fd)
except OSError:
pass
self._fd = None
raise RuntimeError(
f"Timed out waiting for {'exclusive' if self._exclusive else 'shared'} "
f"lock on {self._path} after {self._timeout}s"
)
time.sleep(0.05)
def __exit__(self, *exc):
fd = self._fd
if fd is not None:
try:
fcntl.flock(fd, fcntl.LOCK_UN)
except OSError:
pass
try:
os.close(fd)
except OSError:
pass
self._fd = None
return False
def _create_mlir_context(*, load_dialects=True):
"""Create an ``ir.Context`` with multithreading disabled.
Disabling multithreading avoids LLVM global-state races when multiple
processes or threads compile concurrently through the same MLIR install.
"""
ctx = ir.Context()
ctx.enable_multithreading(False)
if load_dialects:
ctx.load_all_available_dialects()
return ctx
class FlyDSLCompileError(RuntimeError):
"""Raised when an MLIR pass pipeline fails.
``diagnostics`` carries the list of error-severity messages collected
during the failed ``pm.run()``.
"""
def __init__(self, message: str, diagnostics: Optional[List[str]] = None):
self.diagnostics = diagnostics or []
if self.diagnostics:
full = message + "\nMLIR diagnostics:\n" + "\n".join(f" - {d}" for d in self.diagnostics)
else:
full = message
super().__init__(full)
@contextmanager
def _mlir_diagnostics(ctx):
"""Collect MLIR error diagnostics emitted during a ``with`` block.
Yields a list that the caller can inspect after the block. Only
``ERROR`` severity messages are captured; non-error diagnostics are
left to the default handler (returns ``False``).
"""
diags: List[str] = []
def _handler(d):
if d.severity == ir.DiagnosticSeverity.ERROR:
diags.append(str(d))
return True
return False
handler = ctx.attach_diagnostic_handler(_handler)
try:
yield diags
finally:
if handler.attached:
handler.detach()
def _flydsl_key() -> str:
extra = list(EXTRA_SOURCE_DIRS)
env_extra = os.environ.get("FLYDSL_EXTRA_SOURCE_DIRS", "")
if env_extra:
extra.extend(d.strip() for d in env_extra.split(":") if d.strip())
return _flydsl_key_cached(_use_external_binary_codegen(), env.compile.llvm_dir, tuple(extra))
@lru_cache(maxsize=4)
def _flydsl_key_cached(use_external_binary: bool, llvm_dir: str, extra_source_dirs: tuple = ()) -> str:
"""Compute a hash fingerprint of the entire FlyDSL compiler toolchain.
Covers:
1. All Python source files under flydsl.compiler.*, flydsl.expr.*,
flydsl.runtime.*, flydsl.utils.*
2. Native shared libraries (_mlirDialectsFly*.so, libFly*.so, libfly_jit_runtime.so,
libmlir_rocm_runtime.so)
3. flydsl.__version__
Any change to compiler code, pass pipeline, runtime wrappers, or C++
bindings will produce a different key, invalidating stale disk caches.
"""
import flydsl
contents = []
flydsl_root = Path(flydsl.__file__).resolve().parent
# 1) Hash all Python source files in key sub-packages.
pkg_prefixes = [
(str(flydsl_root / "compiler"), "flydsl.compiler."),
(str(flydsl_root / "expr"), "flydsl.expr."),
(str(flydsl_root / "runtime"), "flydsl.runtime."),
(str(flydsl_root / "utils"), "flydsl.utils."),
]
for pkg_path, prefix in pkg_prefixes:
if not os.path.isdir(pkg_path):
continue
for lib in pkgutil.walk_packages([pkg_path], prefix=prefix):
try:
spec = lib.module_finder.find_spec(lib.name)
if spec and spec.origin and os.path.isfile(spec.origin):
with open(spec.origin, "rb") as f:
contents.append(hashlib.sha256(f.read()).hexdigest())
except Exception:
pass
p = flydsl_root / "__init__.py"
if p.is_file():
with open(p, "rb") as f:
contents.append(hashlib.sha256(f.read()).hexdigest())
# 2) Hash native shared libraries (C++ passes, runtime wrappers, bindings).
backend = get_backend()
mlir_libs_dir = flydsl_root / "_mlir" / "_mlir_libs"
if mlir_libs_dir.is_dir():
for pattern in backend.native_lib_patterns():
for so_file in sorted(mlir_libs_dir.glob(pattern)):
h = hashlib.sha256()
with open(so_file, "rb") as f:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
h.update(chunk)
contents.append(h.hexdigest())
# 3) Hash .py files in extra source directories (downstream fingerprint).
for src_dir in extra_source_dirs:
src_path = Path(src_dir)
if src_path.is_dir():
for py_file in sorted(src_path.rglob("*.py")):
with open(py_file, "rb") as f:
contents.append(hashlib.sha256(f.read()).hexdigest())
contents.append(f"external_binary_codegen={use_external_binary}")
if use_external_binary:
from .external_llvm import external_llvm_fingerprint
contents.append(external_llvm_fingerprint(llvm_dir or None))
key = f"flydsl:{flydsl.__version__}:{backend.hash()}-" + "-".join(contents)
log().debug(f"flydsl_key: {hashlib.sha256(key.encode()).hexdigest()[:16]}")
return key
def _use_external_binary_codegen() -> bool:
return bool(env.compile.llvm_dir.strip())
def _get_underlying_func(obj):
if isinstance(obj, KernelFunction):
return obj._func
if isinstance(obj, JitFunction):
return obj.func
if isinstance(obj, types.MethodType):
return obj.__func__
if isinstance(obj, types.FunctionType):
return obj
return None
def _get_func_source(func) -> str:
try:
return inspect.getsource(func)
except OSError:
return func.__code__.co_code.hex()
def _is_user_function(func, rootFile):
try:
funcFile = inspect.getfile(func)
except (TypeError, OSError):
return False
return os.path.dirname(os.path.abspath(funcFile)) == os.path.dirname(os.path.abspath(rootFile))
def _owner_class_from_func(func):
qualname = getattr(func, "__qualname__", "")
parts = qualname.split(".")[:-1]
if not parts or "<locals>" in parts:
return None
obj = func.__globals__.get(parts[0])
for part in parts[1:]:
obj = getattr(obj, part, None)
if obj is None:
return None
return obj if isinstance(obj, type) else None
def _collect_class_member_dependency_sources(
func,
rootFile,
owner_cls,
visited: Set[int],
) -> List[str]:
sources = []
for name in func.__code__.co_names:
try:
obj = getattr(owner_cls, name)
except AttributeError:
continue
underlying = _get_underlying_func(obj)
if underlying is None or id(underlying) in visited:
continue
if not _is_user_function(underlying, rootFile):
continue
visited.add(id(underlying))
sources.append(f"class:{owner_cls.__qualname__}.{name}:{_get_func_source(underlying)}")
sources.extend(_collect_dependency_sources(underlying, rootFile, visited, owner_cls=owner_cls))
return sources
def _collect_closure_scalar_vals(func, visited_ids: Optional[Set[int]] = None) -> List[str]:
"""Recursively collect scalar closure values from func and all callable deps in its closure.
This ensures that compile-time parameters captured by nested @kernel functions
(e.g. tile_m, tile_n, waves_per_eu inside a KernelFunction._func) are included
in the cache key even when the outer @jit launcher does not reference them directly.
"""
if visited_ids is None:
visited_ids = set()
if id(func) in visited_ids:
return []
visited_ids.add(id(func))
vals = []
if not (func.__code__.co_freevars and getattr(func, "__closure__", None)):
return vals
for name, cell in zip(func.__code__.co_freevars, func.__closure__):
try:
val = cell.cell_contents
except ValueError:
continue
if isinstance(val, (int, float, bool, str, type(None), tuple)):
vals.append(f"{name}={val!r}")
else:
# Recurse into callable deps (KernelFunction, JitFunction, plain functions)
underlying = _get_underlying_func(val)
if underlying is not None and id(underlying) not in visited_ids:
nested = _collect_closure_scalar_vals(underlying, visited_ids)
# Prefix with the closure var name to avoid collisions across nesting levels
vals.extend(f"via:{name}:{v}" for v in nested)
return vals
def _collect_dependency_sources(
func,
rootFile,
visited: Optional[Set[int]] = None,
owner_cls=None,
) -> List[str]:
if visited is None:
visited = set()
sources = []
# 1) Scan global name references (co_names → __globals__)
for name in func.__code__.co_names:
obj = func.__globals__.get(name)
underlying = _get_underlying_func(obj)
if underlying is None or id(underlying) in visited:
continue
if not _is_user_function(underlying, rootFile):
continue
visited.add(id(underlying))
sources.append(f"{name}:{_get_func_source(underlying)}")
sources.extend(_collect_dependency_sources(underlying, rootFile, visited))
# 2) Scan closure variables (co_freevars → __closure__) for callable
# dependencies. This catches @flyc.kernel functions defined in an
# enclosing scope and captured by the @flyc.jit launcher via closure.
if func.__code__.co_freevars and getattr(func, "__closure__", None):
for name, cell in zip(func.__code__.co_freevars, func.__closure__):
try:
val = cell.cell_contents
except ValueError:
continue
underlying = _get_underlying_func(val)
if underlying is None or id(underlying) in visited:
continue
visited.add(id(underlying))
sources.append(f"closure:{name}:{_get_func_source(underlying)}")
sources.extend(_collect_dependency_sources(underlying, rootFile, visited))
owner_cls = owner_cls or _owner_class_from_func(func)
if owner_cls is not None:
sources.extend(_collect_class_member_dependency_sources(func, rootFile, owner_cls, visited))
return sources
def _jit_function_cache_key(func: Callable, owner_cls=None) -> str:
parts = []
parts.append(_flydsl_key())
parts.append(_get_func_source(func))
try:
rootFile = inspect.getfile(func)
except (TypeError, OSError):
rootFile = ""
depSources = _collect_dependency_sources(func, rootFile, owner_cls=owner_cls)
depSources.sort()
parts.extend(depSources)
# Collect scalar closure values recursively — this covers compile-time parameters
# (tile_m, tile_n, waves_per_eu, etc.) captured directly by the @jit launcher OR
# indirectly via nested @kernel / helper functions, without requiring an explicit
# _cache_tag tuple in every kernel factory function.
all_closure_vals = sorted(_collect_closure_scalar_vals(func))
if all_closure_vals:
parts.append("closure_vals:" + ",".join(all_closure_vals))
combined = "\n".join(parts)
return hashlib.sha256(combined.encode()).hexdigest()[:32]
def _stage_label_from_fragment(fragment: str) -> str:
"""Make a stable, filename-friendly label from a pipeline fragment."""
import re as _re
base = fragment.strip()
if base.startswith("gpu.module(") and base.endswith(")"):
base = base[len("gpu.module(") : -1].strip()
base = base.split("{", 1)[0].strip()
base = _re.sub(r"[^0-9A-Za-z]+", "_", base).strip("_").lower()
return base or "stage"
def _dump_ir(stage: str, *, dump_dir: Path, asm: str) -> Path:
"""Write one compilation stage's MLIR assembly to a .mlir file."""
dump_dir.mkdir(parents=True, exist_ok=True)
out = dump_dir / f"{stage}.mlir"
out.write_text(asm, encoding="utf-8")
return out
def _extract_isa_text(mlir_asm: str) -> str:
"""Extract human-readable ISA from MLIR gpu.binary assembly attribute.
The ``gpu-module-to-binary{format=isa}`` pass embeds the ISA inside an MLIR
attribute like ``assembly = "..."`` with MLIR string escapes (``\\0A`` for
newline, ``\\09`` for tab, ``\\22`` for double-quote). This function
locates that string and un-escapes it so the output is a normal ``.s`` file.
"""
import re as _re
m = _re.search(r'assembly\s*=\s*"', mlir_asm)
if not m:
return mlir_asm
start = m.end()
# Walk forward to find the closing unescaped quote.
i = start
chars = []
while i < len(mlir_asm):
ch = mlir_asm[i]
if ch == '"':
break
if ch == "\\" and i + 1 < len(mlir_asm):
nxt = mlir_asm[i + 1]
if nxt == "\\":
chars.append("\\")
i += 2
continue
if nxt == '"':
chars.append('"')
i += 2
continue
# MLIR hex escape: \XX
if i + 3 <= len(mlir_asm):
hex_str = mlir_asm[i + 1 : i + 3]
try:
chars.append(chr(int(hex_str, 16)))
i += 3
continue
except ValueError:
pass
chars.append(ch)
i += 1
return "".join(chars)
def _dump_isa(*, dump_dir: Path, ctx: ir.Context, asm: str, verify: bool, stage_name: str = "15_final_isa"):
"""Best-effort dump of final GPU ISA/assembly (.s).
Runs ``gpu-module-to-binary{format=isa}`` on a *cloned* module so the
main compilation is not affected. The raw ISA text is extracted from the
MLIR ``assembly = "..."`` attribute and written as a clean ``.s`` file.
"""
try:
mod = ir.Module.parse(asm, context=ctx)
di_pass = (
"ensure-debug-info-scope-on-llvm-func{emission-kind=LineTablesOnly}," if env.debug.enable_debug_info else ""
)
pm = PassManager.parse(
f'builtin.module({di_pass}gpu-module-to-binary{{format=isa opts="{"-g" if env.debug.enable_debug_info else ""}" section= toolkit=}})',
context=ctx,
)
pm.enable_verifier(bool(verify))
pm.run(mod.operation)
raw_mlir = mod.operation.get_asm(enable_debug_info=False)
isa_text = _extract_isa_text(raw_mlir)
dump_dir.mkdir(parents=True, exist_ok=True)
out = dump_dir / f"{stage_name}.s"
out.write_text(isa_text, encoding="utf-8")
return out
except Exception as exc:
log().debug(f"[dump_isa] failed: {exc}")
return None
def _infer_kernel_names_from_asm(asm: str) -> list:
"""Extract gpu.func kernel names from MLIR assembly."""
names = []
for line in asm.splitlines():
if "gpu.func @" not in line or " kernel" not in line:
continue
try:
after = line.split("gpu.func @", 1)[1]
name = after.split("(", 1)[0].strip()
if name:
names.append(name)
except Exception:
pass
return names
def _sanitize_path_component(s: str) -> str:
import re as _re
s = str(s).strip()
return _re.sub(r"[^A-Za-z0-9_.-]+", "_", s) if s else "unknown"
def _extract_llvm_ir(module: ir.Module):
"""Extract LLVM IR text from the gpu.module inside *module* (must already be in LLVM dialect)."""
try:
from .._mlir._mlir_libs._mlirDialectsLLVM import translate_module_to_llvmir
for op in module.body.operations:
if op.operation.name == "gpu.module":
return translate_module_to_llvmir(op.operation)
return None
except Exception as exc:
log().debug(f"[extract_llvm_ir] failed: {exc}")
return None
@dataclass
class PipelineConfig:
"""Result of :func:`_pipeline_fragments_for_mode`."""
fragments: list
pre_binary: Optional[list]
binary_fragment: Optional[str]
llvm_opts: Optional[dict]
external: bool
def _pipeline_fragments_for_mode(backend) -> PipelineConfig:
"""Return pipeline configuration including optional external split."""
from .kernel_function import CompilationContext
hints = CompilationContext.get_compile_hints()
llvm_opts = hints.get("llvm_options")
if _use_external_binary_codegen():
pre_binary_fragments, binary_fragment = backend.external_binary_pipeline_fragments(compile_hints=hints)
return PipelineConfig(
fragments=[*pre_binary_fragments, binary_fragment],
pre_binary=pre_binary_fragments,
binary_fragment=binary_fragment,
llvm_opts=llvm_opts,
external=True,
)
fragments = backend.pipeline_fragments(compile_hints=hints)
return PipelineConfig(
fragments=fragments,
pre_binary=None,
binary_fragment=None,
llvm_opts=llvm_opts,
external=False,
)
def _format_link_lib_options(link_libs: list) -> str:
"""Format external bitcode paths for rocdl-attach-target.
The MLIR pass-pipeline option parser treats whitespace, commas, and braces
as structural syntax. Until FlyDSL grows proper MLIR option escaping here,
reject such paths loudly instead of producing a malformed pipeline.
"""
opts = []
for lib in link_libs:
path = os.fspath(lib)
bad_chars = sorted({ch for ch in path if ch.isspace() or ch in ",{}\"'"})
if not path or bad_chars:
chars = "empty path" if not path else f"unsupported character(s) {bad_chars!r}"
raise ValueError(
f"Cannot pass external bitcode path {path!r} to rocdl-attach-target: {chars}. "
"Use a path without whitespace, commas, braces, or quotes, or add MLIR pass-option escaping."
)
opts.append(f"l={path}")
return " ".join(opts)
def _run_pipeline(module: ir.Module, fragments: list, *, verifier: bool, print_after_all: bool) -> None:
"""Parse and run a comma-joined pass pipeline on *module*."""
pipeline = f"builtin.module({','.join(fragments)})"
pm = PassManager.parse(pipeline)
pm.enable_verifier(verifier)
pm.enable_ir_printing(print_after_all=print_after_all)
with _mlir_diagnostics(module.context) as diags:
try:
pm.run(module.operation)
except Exception as exc:
raise FlyDSLCompileError(str(exc), diagnostics=diags) from exc
class MlirCompiler:
@classmethod
def compile(
cls, module: ir.Module, *, arch: str = "", func_name: str = "", link_libs: Optional[list] = None
) -> ir.Module:
module.operation.verify()
backend = get_backend(arch=arch)
module = ir.Module.parse(module.operation.get_asm(enable_debug_info=env.debug.enable_debug_info))
cfg = _pipeline_fragments_for_mode(backend)
fragments = cfg.fragments
pre_binary_fragments = cfg.pre_binary
binary_fragment = cfg.binary_fragment
llvm_opts = cfg.llvm_opts
external_binary = cfg.external
if external_binary and link_libs:
raise RuntimeError(
"FLYDSL_COMPILE_LLVM_DIR external codegen does not support extern link_libs yet; "
"use embedded codegen for kernels that require #fly.explicit_module."
)
if link_libs:
link_opt = _format_link_lib_options(link_libs)
new_fragments = []
found_rocdl = False
for f in fragments:
if "rocdl-attach-target" in f:
if f.endswith("}"):
base = f[:-1].rstrip()
else:
base = f.rstrip()
new_fragments.append(f"{base} {link_opt}" + "}")
found_rocdl = True
else:
new_fragments.append(f)
if not found_rocdl:
raise RuntimeError("link_libs specified but no 'rocdl-attach-target' fragment found in pipeline")
fragments = new_fragments
from .llvm_options import llvm_options as _llvm_options
_llvm_ctx = _llvm_options(llvm_opts) if llvm_opts else nullcontext()
if env.debug.print_origin_ir:
log().info(f"Origin IR: \n{module}")
dump_enabled = env.debug.dump_ir
dump_dir = Path(env.debug.dump_dir).resolve()
with _llvm_ctx:
if dump_enabled:
asm = module.operation.get_asm(enable_debug_info=True)
kernel_names = _infer_kernel_names_from_asm(asm)
subdir = kernel_names[0] if len(kernel_names) == 1 else (func_name or "module")
dump_dir = dump_dir / _sanitize_path_component(subdir)
print(f"[flydsl.compile] FLYDSL_DUMP_IR=1 dir={dump_dir}")
out = _dump_ir("00_origin", dump_dir=dump_dir, asm=asm)
print(f"[flydsl.compile] dump 00_origin -> {out}")
asm_for_isa = None
llir = None
stage_num_base = 1
dump_fragments = pre_binary_fragments if external_binary else fragments
for idx, frag in enumerate(dump_fragments):
if frag.strip().startswith("gpu-module-to-binary"):
llir = _extract_llvm_ir(module)
stage_num = stage_num_base + idx
stage_name = f"{stage_num:02d}_{_stage_label_from_fragment(frag)}"
pm = PassManager.parse(f"builtin.module({frag})")
pm.enable_verifier(env.debug.enable_verifier)
with _mlir_diagnostics(module.context) as diags:
try:
pm.run(module.operation)
except Exception as exc:
raise FlyDSLCompileError(str(exc), diagnostics=diags) from exc
stage_asm = module.operation.get_asm(enable_debug_info=True)
out = _dump_ir(stage_name, dump_dir=dump_dir, asm=stage_asm)
print(f"[flydsl.compile] dump {stage_name} -> {out}")
if frag.strip() == "reconcile-unrealized-casts":
asm_for_isa = stage_asm
next_stage = stage_num_base + len(dump_fragments)
if external_binary:
from .external_llvm import run_external_binary_codegen
llir = _extract_llvm_ir(module)
stage_name = f"{next_stage:02d}_external_binary"
run_external_binary_codegen(
module,
binary_fragment,
llvm_options=llvm_opts,
work_dir=dump_dir,
stage_prefix=stage_name,
)
module.operation.verify()
print(f"[flydsl.compile] dump {stage_name}_input -> {dump_dir / f'{stage_name}_input.mlir'}")
print(
f"[flydsl.compile] dump {stage_name}_external_output -> "
f"{dump_dir / f'{stage_name}_external_output.mlir'}"
)
print(f"[flydsl.compile] dump {stage_name}_output -> {dump_dir / f'{stage_name}_output.mlir'}")
next_stage += 1
if llir is not None:
ll_name = f"{next_stage:02d}_llvm_ir"
(dump_dir / f"{ll_name}.ll").write_text(llir, encoding="utf-8")
print(f"[flydsl.compile] dump {ll_name} -> {dump_dir / f'{ll_name}.ll'}")
next_stage += 1
if asm_for_isa is not None:
if not external_binary:
isa_stage = f"{next_stage:02d}_final_isa"
isa_out = _dump_isa(
dump_dir=dump_dir,
ctx=module.context,
asm=asm_for_isa,
verify=env.debug.enable_verifier,
stage_name=isa_stage,
)
if isa_out is not None:
print(f"[flydsl.compile] dump {isa_stage} -> {isa_out}")
else:
print("[flydsl.compile] ISA dump skipped (external LLVM mode)")
else:
if external_binary:
from .external_llvm import run_external_binary_codegen
_run_pipeline(
module,
pre_binary_fragments,
verifier=env.debug.enable_verifier,
print_after_all=env.debug.print_after_all,
)
if env.debug.dump_asm:
raise RuntimeError(
"FLYDSL_DEBUG_DUMP_ASM is not supported with "
"FLYDSL_COMPILE_LLVM_DIR external codegen; use FLYDSL_DUMP_IR=1 "
"to inspect pre-binary/final MLIR, or run external LLVM tools directly for ISA dumps."
)
run_external_binary_codegen(
module,
binary_fragment,
llvm_options=llvm_opts,
)
module.operation.verify()
else:
_run_pipeline(
module,
fragments,
verifier=env.debug.enable_verifier,
print_after_all=env.debug.print_after_all,
)
return module
class JitCacheManager:
"""Directory-based cache manager with multi-process safety.
Cache directory structure:
{cache_root}/{func_name}_{manager_key}/
{cache_key}.pkl - serialized compiled kernel
{cache_key}.lock - per-key advisory lock file
All disk reads use shared (reader) locks; writes use exclusive locks
with atomic ``tempfile`` + ``os.rename`` to prevent partial reads.
"""
def __init__(self, cache_dir: Path):
self.cache_dir = cache_dir
self.memory_cache: Dict[str, Any] = {}
self._hits = 0
self._misses = 0
@staticmethod
def _safe_key(cache_key: str) -> str:
return hashlib.sha256(cache_key.encode()).hexdigest()[:16]
def _cache_file(self, cache_key: str) -> Path:
return self.cache_dir / f"{self._safe_key(cache_key)}.pkl"
def _lock_file(self, cache_key: str) -> Path:
return self.cache_dir / f"{self._safe_key(cache_key)}.lock"
@staticmethod
def _atomic_write(cache_file: Path, value: Any) -> None:
"""Write *value* atomically via tempfile + rename."""
cache_file.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=str(cache_file.parent), suffix=".tmp")
try:
with os.fdopen(fd, "wb") as f:
pickle.dump(value, f)
os.rename(tmp, str(cache_file))
except BaseException:
try:
os.unlink(tmp)
except OSError:
pass
raise
def get(self, cache_key: str) -> Optional[Any]:
if cache_key in self.memory_cache:
self._hits += 1
return self.memory_cache[cache_key]
cache_file = self._cache_file(cache_key)
if cache_file.exists():
lock_path = self._lock_file(cache_key)
try:
with FileLock(lock_path, exclusive=False, timeout=30):
if not cache_file.exists():
self._misses += 1
return None
with open(cache_file, "rb") as f:
value = pickle.load(f)
self.memory_cache[cache_key] = value
self._hits += 1
log().debug(f"Cache hit from disk: {cache_file.name}")
return value
except Exception as e:
log().warning(f"Failed to load cache {cache_file}: {e}")
self._misses += 1
return None
def set(self, cache_key: str, value: Any) -> None:
self.memory_cache[cache_key] = value
self.cache_dir.mkdir(parents=True, exist_ok=True)
cache_file = self._cache_file(cache_key)
lock_path = self._lock_file(cache_key)
try:
with FileLock(lock_path, exclusive=True, timeout=30):
if cache_file.exists():
log().debug(f"Cache already exists, skipping write: {cache_file.name}")
return
self._atomic_write(cache_file, value)
log().debug(f"Cache saved: {cache_file.name}")
except Exception as e:
log().warning(f"Failed to save cache {cache_file}: {e}")
@contextmanager
def compile_lock(self, cache_key: str):
"""Acquire an exclusive compile lock, re-check disk, yield (existing_or_None, writer_or_None).
If *existing* is not None, another process already wrote the artifact
and *writer* is None. Otherwise *writer* is a callable that performs
an atomic write under the already-held lock (no re-locking).
"""
self.cache_dir.mkdir(parents=True, exist_ok=True)
lock_path = self._lock_file(cache_key)
cache_file = self._cache_file(cache_key)
with FileLock(lock_path, exclusive=True, timeout=600):
# Re-check disk under exclusive lock.
if cache_file.exists():
try:
with open(cache_file, "rb") as f:
value = pickle.load(f)
self.memory_cache[cache_key] = value
self._hits += 1
yield (value, None)
return
except Exception:
# Corrupt cache — remove so writer can overwrite.
try:
cache_file.unlink()
except OSError:
pass
# Cache miss — provide a writer that writes under the already-held lock.
def _writer(value):
self._atomic_write(cache_file, value)
self.memory_cache[cache_key] = value
yield (None, _writer)
def load_all(self) -> int:
if not self.cache_dir.exists():
return 0
count = 0
for cache_file in sorted(self.cache_dir.glob("*.pkl")):
lock_path = cache_file.with_suffix(".lock")
try:
with FileLock(lock_path, exclusive=False, timeout=30):
with open(cache_file, "rb") as f:
pickle.load(f)
count += 1
except Exception:
pass
log().debug(f"Found {count} cached entries in {self.cache_dir}")
return count
def cache_info(self) -> CacheInfo:
disk_count = 0
if self.cache_dir.exists():
disk_count = sum(1 for _ in self.cache_dir.glob("*.pkl"))
return CacheInfo(
hits=self._hits,
misses=self._misses,
currsize=len(self.memory_cache),
disk_size=disk_count,
)
def __contains__(self, cache_key: str) -> bool:
return cache_key in self.memory_cache or self._cache_file(cache_key).exists()
def _resolve_jit_arg_type(arg, annotation):
"""Resolve the JitArgument type for an argument, using the same dispatch
logic as convert_to_jit_arguments. Returns the type (not an instance)."""
from .jit_argument import JitArgumentRegistry
if isinstance(arg, int) and annotation is Stream:
return Stream
if hasattr(arg, "__get_c_pointers__"):
return type(arg)
constructor, _ = JitArgumentRegistry.get(type(arg))
return constructor
def _build_call_state(sig, args_tuple, func_exe):
"""Build a CallState for fast repeated dispatch.
Resolves each parameter's JitArgument type using the same registry as
convert_to_jit_arguments, then asks it for a reusable slot specification.
This ensures a single source of truth for argument packing.
Returns a CallState, or None if any parameter can't be fast-pathed.
"""
slot_specs = []
has_user_stream = False
for i, (param_name, param) in enumerate(sig.parameters.items()):
annotation = param.annotation
if annotation is not inspect.Parameter.empty and Constexpr.is_constexpr_annotation(annotation):
continue
if annotation is not inspect.Parameter.empty and is_type_param_annotation(annotation):
continue
if getattr(annotation, "_is_stream_param", False):
has_user_stream = True
arg = args_tuple[i]
jit_arg_type = _resolve_jit_arg_type(arg, annotation)
if jit_arg_type is None or not hasattr(jit_arg_type, "_reusable_slot_spec"):
return None
spec = jit_arg_type._reusable_slot_spec(arg)
if spec is None:
return None
ctype, extract = spec
try:
extract(arg)
except (AttributeError, TypeError):
return None
slot_specs.append((i, ctype, extract))
# Auto-stream: append a zero-valued slot for the default (NULL) stream.
# When no user-declared stream parameter exists, the compiled kernel
# still expects a stream pointer as the last argument. A NULL pointer
# (value 0) selects the HIP default stream.
if not has_user_stream:
slot_specs.append((-1, ctypes.c_void_p, None))
return CallState(slot_specs, func_exe)
class CallState:
"""Pre-allocated state for fast kernel dispatch.
Built from JitArgument types' _reusable_slot_spec protocol — the same
types used by convert_to_jit_arguments for the full DLPack path.
Pre-allocates typed ctypes storage and a packed pointer array at init
time. On each call, only updates .value on existing storage objects —