mplang-nightly 0.1.dev146__py3-none-any.whl → 0.1.dev148__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
mplang/backend/base.py CHANGED
@@ -12,20 +12,21 @@
12
12
  # See the License for the specific language governing permissions and
13
13
  # limitations under the License.
14
14
 
15
- """Backend kernel registry & per-participant runtime (explicit op->kernel binding).
15
+ """Backend kernel registry: mapping kernel_id -> implementation.
16
16
 
17
- This version decouples *kernel implementation registration* from *operation binding*.
17
+ This module provides a lightweight registry for backend kernel implementations.
18
+ It does not track or decide which kernel handles a given semantic operation;
19
+ that policy (op -> kernel_id) is managed externally by each ``RuntimeContext``.
18
20
 
19
- Concepts:
20
- * kernel_id: unique identifier of a concrete backend implementation.
21
- * op_type: semantic operation name carried by ``PFunction.fn_type``.
22
- * bind_op(op_type, kernel_id): performed by higher layer (see ``backend.context``)
23
- to select which implementation handles an op. Runtime dispatch is now a 2-step:
24
- pfunc.fn_type -> active kernel_id -> KernelSpec.fn
21
+ Exposed primitives:
22
+ * ``@kernel_def(kernel_id)``: decorator to register a kernel implementation.
23
+ * ``get_kernel_spec(kernel_id)``: look up a previously registered kernel.
24
+ * ``cur_kctx()`` / ``KernelContext``: execution context available only
25
+ inside a kernel body (rank, world_size, per-backend state pockets, and a
26
+ runtime-wide cache shared by kernels of the same runtime instance).
25
27
 
26
- The previous implicit "import == register+bind" coupling is removed. Kernel
27
- modules only call ``@kernel_def(kernel_id)``. Default bindings are established
28
- centrally (lazy) the first time a runtime executes a kernel.
28
+ No global op binding table exists here; callers resolve an op to a kernel_id
29
+ before invoking the kernel function.
29
30
  """
30
31
 
31
32
  from __future__ import annotations
@@ -38,12 +39,10 @@ from typing import Any
38
39
  __all__ = [
39
40
  "KernelContext",
40
41
  "KernelSpec",
41
- "bind_op",
42
42
  "cur_kctx",
43
- "get_kernel_for_op",
43
+ "get_kernel_spec",
44
+ "kernel_exists",
44
45
  "list_kernels",
45
- "list_ops",
46
- "unbind_op",
47
46
  ]
48
47
 
49
48
 
@@ -116,9 +115,6 @@ class KernelSpec:
116
115
  # All registered kernel implementations: kernel_id -> spec
117
116
  _KERNELS: dict[str, KernelSpec] = {}
118
117
 
119
- # Active op bindings: op_type -> kernel_id
120
- _BINDINGS: dict[str, str] = {}
121
-
122
118
 
123
119
  def kernel_def(kernel_id: str, /, **meta: Any) -> Callable[[KernelFn], KernelFn]:
124
120
  """Decorator to register a concrete kernel implementation.
@@ -136,34 +132,11 @@ def kernel_def(kernel_id: str, /, **meta: Any) -> Callable[[KernelFn], KernelFn]
136
132
  return _decorator
137
133
 
138
134
 
139
- def bind_op(op_type: str, kernel_id: str, *, force: bool = True) -> None:
140
- """Bind an op_type to a registered kernel implementation.
141
-
142
- Args:
143
- op_type: Semantic operation name.
144
- kernel_id: Previously registered kernel identifier.
145
- force: If False and op_type already bound, keep existing binding.
146
- If True (default), overwrite.
147
- """
148
- if kernel_id not in _KERNELS:
135
+ def get_kernel_spec(kernel_id: str) -> KernelSpec:
136
+ """Return KernelSpec for a registered kernel_id (no op binding lookup)."""
137
+ spec = _KERNELS.get(kernel_id)
138
+ if spec is None:
149
139
  raise KeyError(f"kernel_id {kernel_id} not registered")
150
- if not force and op_type in _BINDINGS:
151
- return
152
- _BINDINGS[op_type] = kernel_id
153
-
154
-
155
- def unbind_op(op_type: str) -> None:
156
- _BINDINGS.pop(op_type, None)
157
-
158
-
159
- def get_kernel_for_op(op_type: str) -> KernelSpec:
160
- kid = _BINDINGS.get(op_type)
161
- if kid is None:
162
- # Tests expect NotImplementedError for unsupported operations
163
- raise NotImplementedError(f"no backend kernel registered for op {op_type}")
164
- spec = _KERNELS.get(kid)
165
- if spec is None: # inconsistent state
166
- raise RuntimeError(f"active kernel_id {kid} missing spec")
167
140
  return spec
168
141
 
169
142
 
@@ -171,5 +144,6 @@ def list_kernels() -> list[str]:
171
144
  return sorted(_KERNELS.keys())
172
145
 
173
146
 
174
- def list_ops() -> list[str]:
175
- return sorted(_BINDINGS.keys())
147
+ def kernel_exists(kernel_id: str) -> bool:
148
+ """Return True if a kernel_id has been registered."""
149
+ return kernel_id in _KERNELS
mplang/backend/context.py CHANGED
@@ -15,11 +15,10 @@
15
15
  from __future__ import annotations
16
16
 
17
17
  from collections.abc import Mapping
18
- from dataclasses import dataclass, field
19
18
  from typing import Any
20
19
 
21
20
  from mplang.backend import base
22
- from mplang.backend.base import KernelContext, bind_op, get_kernel_for_op
21
+ from mplang.backend.base import KernelContext, get_kernel_spec, kernel_exists
23
22
  from mplang.core.dtype import UINT8, DType
24
23
  from mplang.core.pfunc import PFunction
25
24
  from mplang.core.table import TableLike, TableType
@@ -100,30 +99,57 @@ _DEFAULT_BINDINGS: dict[str, str] = {
100
99
  # --- RuntimeContext ---
101
100
 
102
101
 
103
- @dataclass
104
102
  class RuntimeContext:
105
- rank: int
106
- world_size: int
107
- bindings: Mapping[str, str] | None = None # optional overrides
108
- state: dict[str, dict[str, Any]] = field(default_factory=dict)
109
- cache: dict[str, Any] = field(default_factory=dict)
110
- stats: dict[str, Any] = field(default_factory=dict)
111
-
112
- def __post_init__(self) -> None:
103
+ """Per-runtime execution context with isolated op->kernel bindings.
104
+
105
+ Parameters
106
+ ----------
107
+ rank : int
108
+ Local rank of this participant.
109
+ world_size : int
110
+ Total number of participants.
111
+ initial_bindings : Mapping[str, str] | None, optional
112
+ Optional partial overrides applied on top of the default binding table
113
+ during construction (override semantics, not replace). After
114
+ initialization, all (re)binding must go through ``bind_op`` /
115
+ ``rebind_op``.
116
+ state / cache / stats : dict, optional
117
+ Mutable pockets reused across kernel invocations. If omitted, new
118
+ dictionaries are created.
119
+ """
120
+
121
+ __slots__ = ("_ibindings", "cache", "rank", "state", "stats", "world_size")
122
+
123
+ def __init__(
124
+ self,
125
+ rank: int,
126
+ world_size: int,
127
+ initial_bindings: Mapping[str, str] | None = None,
128
+ *,
129
+ state: dict[str, dict[str, Any]] | None = None,
130
+ cache: dict[str, Any] | None = None,
131
+ stats: dict[str, Any] | None = None,
132
+ ) -> None:
113
133
  _ensure_impl_imported()
114
- if self.bindings is not None:
115
- for op, kid in self.bindings.items():
116
- bind_op(op, kid)
117
- else:
118
- for op, kid in _DEFAULT_BINDINGS.items():
119
- bind_op(op, kid)
120
- # Initialize stats pocket
134
+ self.rank = rank
135
+ self.world_size = world_size
136
+ # Merge defaults with user overrides (override semantics)
137
+ self._ibindings: dict[str, str] = {
138
+ **_DEFAULT_BINDINGS,
139
+ **(initial_bindings or {}),
140
+ }
141
+ self.state = state if state is not None else {}
142
+ self.cache = cache if cache is not None else {}
143
+ self.stats = stats if stats is not None else {}
121
144
  self.stats.setdefault("op_calls", {})
122
145
 
123
146
  def run_kernel(self, pfunc: PFunction, arg_list: list[Any]) -> list[Any]:
124
147
  fn_type = pfunc.fn_type
125
- spec = get_kernel_for_op(fn_type)
126
- fn = spec.fn
148
+ kid = self._ibindings.get(fn_type)
149
+ if kid is None:
150
+ raise NotImplementedError(f"no backend kernel registered for op {fn_type}")
151
+ spec = get_kernel_spec(kid)
152
+ fn = spec.fn # kernel implementation
127
153
  if len(arg_list) != len(pfunc.ins_info):
128
154
  raise ValueError(
129
155
  f"kernel {fn_type} arg count mismatch: got {len(arg_list)}, expect {len(pfunc.ins_info)}"
@@ -186,17 +212,32 @@ class RuntimeContext:
186
212
 
187
213
  # ---- explicit (re)binding API ----
188
214
  def bind_op(self, op_type: str, kernel_id: str, *, force: bool = False) -> None:
189
- """Bind an operation to a kernel at runtime.
215
+ """Bind an operation to a kernel for THIS context only.
190
216
 
191
- force=False (default) preserves any existing binding to avoid accidental
192
- silent overrides. Use ``rebind_op`` or ``force=True`` to intentionally
193
- change a binding.
217
+ force=False (default) keeps existing binding (no silent override).
194
218
  """
195
- base.bind_op(op_type, kernel_id, force=force)
219
+ if not kernel_exists(kernel_id):
220
+ raise KeyError(f"kernel_id {kernel_id} not registered")
221
+ if not force and op_type in self._ibindings:
222
+ return
223
+ self._ibindings[op_type] = kernel_id
196
224
 
197
225
  def rebind_op(self, op_type: str, kernel_id: str) -> None:
198
226
  """Force rebind an operation to a different kernel (shorthand)."""
199
- base.bind_op(op_type, kernel_id, force=True)
227
+ self.bind_op(op_type, kernel_id, force=True)
228
+
229
+ # Introspection helpers
230
+ def list_bound_ops(self) -> list[str]: # pragma: no cover - convenience
231
+ return sorted(self._ibindings.keys())
232
+
233
+ def get_binding(self, op_type: str) -> str | None: # pragma: no cover
234
+ return self._ibindings.get(op_type)
235
+
236
+ def __repr__(self) -> str: # pragma: no cover - debug aid
237
+ return (
238
+ f"RuntimeContext(rank={self.rank}, world_size={self.world_size}, "
239
+ f"bound_ops={len(self._ibindings)})"
240
+ )
200
241
 
201
242
 
202
243
  def _validate_table_arg(
@@ -196,6 +196,28 @@ class EvalSemantic:
196
196
  "uniform_cond: predicate is not uniform across parties"
197
197
  )
198
198
 
199
+ # ------------------------------ While helpers ------------------------------
200
+ def _check_while_predicate(self, cond_result: list[Any]) -> Any:
201
+ """Validate while_loop predicate evaluation result.
202
+
203
+ Ensures the condition function returns exactly one value and that value
204
+ is non-None. Returns the boolean predicate value for convenience.
205
+
206
+ Raises:
207
+ AssertionError: If condition function returns != 1 value.
208
+ RuntimeError: If the single predicate value is None.
209
+ """
210
+ assert len(cond_result) == 1, (
211
+ f"Condition function must return a single value, got {cond_result}"
212
+ )
213
+ cond_value = cond_result[0]
214
+ if cond_value is None:
215
+ raise RuntimeError(
216
+ "while_loop condition produced None on rank "
217
+ f"{self.rank}; ensure the predicate yields a boolean for every party."
218
+ )
219
+ return cond_value
220
+
199
221
 
200
222
  class RecursiveEvaluator(EvalSemantic, ExprVisitor):
201
223
  """Recursive visitor-based evaluator."""
@@ -307,12 +329,8 @@ class RecursiveEvaluator(EvalSemantic, ExprVisitor):
307
329
  cond_env = dict(zip(expr.cond_fn.params, state, strict=True))
308
330
  cond_evaluator = self._fork(cond_env)
309
331
  cond_result = expr.cond_fn.body.accept(cond_evaluator)
310
-
311
- assert len(cond_result) == 1, (
312
- f"Condition function must return a single value, got {cond_result}"
313
- )
314
-
315
- if not cond_result[0]:
332
+ cond_value = self._check_while_predicate(cond_result)
333
+ if not cond_value:
316
334
  break
317
335
 
318
336
  # Call body function with same arguments
@@ -445,8 +463,8 @@ class IterativeEvaluator(EvalSemantic):
445
463
  cond_vals = self._iter_eval_graph(
446
464
  node.cond_fn.body, {**env, **cond_env}
447
465
  )
448
- assert len(cond_vals) == 1
449
- if not bool(cond_vals[0]):
466
+ cond_val = self._check_while_predicate(cond_vals)
467
+ if not bool(cond_val):
450
468
  break
451
469
  body_env = dict(zip(node.body_fn.params, state, strict=True))
452
470
  new_state = self._iter_eval_graph(
mplang/core/primitive.py CHANGED
@@ -483,6 +483,20 @@ def uniform_cond(
483
483
  if pred_ty.dtype != BOOL:
484
484
  raise TypeError(f"uniform_cond predicate must be boolean, got {pred_ty.dtype}")
485
485
 
486
+ # Static pmask rule:
487
+ # If predicate has a static pmask (not None), it must equal the current trace
488
+ # context mask. Otherwise some parties would execute a branch without a
489
+ # defined predicate value (unsafe). To run on a subset either:
490
+ # 1. Trace the entire uniform_cond under a subset TraceContext (ctx.fork(mask=...))
491
+ # 2. Broadcast / lift predicate to full mask (e.g. pshfl_s)
492
+ # Pred pmask None => dynamic: defer to runtime uniformity (if verify_uniform=True).
493
+ pred_pmask = pred_ty.pmask
494
+ if pred_pmask is not None and pred_pmask != cur_tracer.mask:
495
+ raise ValueError(
496
+ "uniform_cond predicate static pmask mismatch: predicate pmask="
497
+ f"{pred_pmask} trace mask={cur_tracer.mask}. Trace under a subset "
498
+ "context (ctx.fork(mask=...)) or broadcast predicate (pshfl_s) to all parties."
499
+ )
486
500
  # Step 1: Trace both branches in separate contexts
487
501
  then_tracer = cur_tracer.fork()
488
502
  then_tfn = trace(then_tracer, then_fn, *args)
@@ -706,6 +720,22 @@ def while_loop(
706
720
  f"Condition function must return a boolean scalar, got dtype {cond_out_var.mptype.dtype}"
707
721
  )
708
722
 
723
+ # Static pmask rule:
724
+ # If the predicate's pmask is statically known it must match the trace context
725
+ # mask. Otherwise some parties in this context would lack a boolean to drive
726
+ # control flow (previously could lead to hang via None). To restrict to a subset:
727
+ # 1. Trace the entire while_loop under a subset context (ctx.fork(mask=submask)), or
728
+ # 2. Broadcast predicate to full mask (e.g. pshfl_s) before while_loop.
729
+ # Dynamic predicates (pmask=None) are allowed; runtime guard (evaluator) raises
730
+ # if any participating party observes None.
731
+ pred_pmask = cond_out_var.mptype.pmask
732
+ if pred_pmask is not None and pred_pmask != cur_tracer.mask:
733
+ raise ValueError(
734
+ "while_loop predicate static pmask mismatch: predicate pmask="
735
+ f"{pred_pmask} trace mask={cur_tracer.mask}. Trace under subset context "
736
+ "or broadcast predicate to all parties."
737
+ )
738
+
709
739
  # Validate body returns same number of leaves and same dtype/shape per leaf
710
740
  if len(body_tfn.out_vars) != len(cond_tfn.in_vars):
711
741
  raise ValueError(
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mplang-nightly
3
- Version: 0.1.dev146
3
+ Version: 0.1.dev148
4
4
  Summary: Multi-Party Programming Language
5
5
  Author-email: SecretFlow Team <secretflow-contact@service.alipay.com>
6
6
  License: Apache License
@@ -4,9 +4,9 @@ mplang/device.py,sha256=Iz_YFKkrbTFKtTQdGqkQZfc0NQH9dIxXP7-fUkIQOa4,12568
4
4
  mplang/analysis/__init__.py,sha256=CTHFvRsi-nFngojqjn08UaR3RY9i7CJ7T2UdR95kCrk,1056
5
5
  mplang/analysis/diagram.py,sha256=ffwgD12gL1_KH1uJ_EYkjmIlDrfxYJJkWj-wHl09_Xk,19520
6
6
  mplang/backend/__init__.py,sha256=2WE4cmW96Xkzyq2yRRYNww4kZ5o6u6NbPV0BxqZG698,581
7
- mplang/backend/base.py,sha256=Rp4Ze1aF5dypdMOskXnQWE-rM5nc4vkdDogEoxQp7FU,5712
7
+ mplang/backend/base.py,sha256=eizxj16sWkUvBvXWS0Zl-S9uuqalJmNUzB1xLhBg8S8,4920
8
8
  mplang/backend/builtin.py,sha256=Mk1uUO2Vpw3meqZ0B7B0hG-wndea6cmFv2Uk1vM_uTg,7052
9
- mplang/backend/context.py,sha256=e22JzsHydi1DLkjzOEYwGBaAoVHyf8aEFYH_SuN7oR4,9351
9
+ mplang/backend/context.py,sha256=fVJ0w0cw15JEqJO048dncWg7DGNWqbHSUjq42Jsyvos,10952
10
10
  mplang/backend/crypto.py,sha256=H_s5HI7lUP7g0xz-a9qMbSn6dhJStUilKbn3-7SIh0I,3812
11
11
  mplang/backend/phe.py,sha256=uNqmrbDAbd97TWS_O6D5sopastHy6J20R7knFE4M4uc,65247
12
12
  mplang/backend/spu.py,sha256=QT1q5uv-5P_nBGtTvtA_yI2h3h3zIqNSnvzGT7Shua4,9307
@@ -24,13 +24,13 @@ mplang/core/mpir.py,sha256=V6S9RqegaI0yojhLkHla5nGBi27ASoxlrEs1k4tGubM,37980
24
24
  mplang/core/mpobject.py,sha256=0pHSd7SrAFTScCFcB9ziDztElYQn-oIZOKBx47B3QX0,3732
25
25
  mplang/core/mptype.py,sha256=09LbMyJp68W0IkbD0s9YLeVssPg3Rl-rcwjTaCfidIQ,15243
26
26
  mplang/core/pfunc.py,sha256=PAr8qRhVveWO5HOI0TgdsWjpi4PFi2iEyuTlr9UVKSY,5106
27
- mplang/core/primitive.py,sha256=PON1EvE8n5hgz1FiKkza7PMWyv9N8Fwjwj8tQag0_LE,38764
27
+ mplang/core/primitive.py,sha256=C1HMbqmkAvLbdgXiHrWPTQ2v2t1uwC_vsGCtI0TEqHY,40574
28
28
  mplang/core/table.py,sha256=BqTBZn7Tfwce4vzl3XYhaX5hVmKagVq9-YoERDta6d8,5892
29
29
  mplang/core/tensor.py,sha256=86u6DogSZMoL0w5XjtTmQm2PhA_VjwybN1b6U4Zzphg,2361
30
30
  mplang/core/tracer.py,sha256=dVMfUeCMmPz4o6tLXewGMW1Kpy5gpZORvr9w4MhwDtM,14288
31
31
  mplang/core/expr/__init__.py,sha256=qwiSTUOcanFJLyK8HZ13_L1ZDrybqpPXIlTHAyeumE8,1988
32
32
  mplang/core/expr/ast.py,sha256=KE46KTtlH9RA2V_EzWVKCKolsycgTmt7SotUrOc8Qxs,20923
33
- mplang/core/expr/evaluator.py,sha256=3rtfHVajmCUtkanzgiCWkepRRiTKehPcDF2i5EbcitI,20789
33
+ mplang/core/expr/evaluator.py,sha256=OYmxkr4Lf2qMHnHK-aca-dfMsAAzGRVWuXrxNk_M_3U,21675
34
34
  mplang/core/expr/printer.py,sha256=VblKGnO0OUfzH7EBkszwRNxQUB8QyyC7BlJWJEUv9so,9546
35
35
  mplang/core/expr/transformer.py,sha256=TyL-8FjrVvDq_C9X7kAuKkiqt2XdZM-okjzVQj0A33s,4893
36
36
  mplang/core/expr/utils.py,sha256=VDTJ_-CsdHtVy9wDaGa7XdFxQ7o5lYYaeqcgsAhkbNI,2625
@@ -70,8 +70,8 @@ mplang/utils/crypto.py,sha256=rvPomBFtznRHc3RPi6Aip9lsU8zW2oxBqGv1K3vn7Rs,1052
70
70
  mplang/utils/func_utils.py,sha256=vCJcZmu0bEbqhOQKdpttV2_MBllIcPSN0b8U4WjNGGo,5164
71
71
  mplang/utils/spu_utils.py,sha256=S3L9RBkBe2AvSuMSQQ12cBY5Y1NPthubvErSX_7nj1A,4158
72
72
  mplang/utils/table_utils.py,sha256=aC-IZOKkSmFkpr3NZchLM0Wt0GOn-rg_xHBHREWBwAU,2202
73
- mplang_nightly-0.1.dev146.dist-info/METADATA,sha256=NUBg21yZ_atn4uNJ1SLljPt8ZwTuKhjDnuOMBXnlqPE,16547
74
- mplang_nightly-0.1.dev146.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
75
- mplang_nightly-0.1.dev146.dist-info/entry_points.txt,sha256=mG1oJT-GAjQR834a62_QIWb7litzWPPyVnwFqm-rWuY,55
76
- mplang_nightly-0.1.dev146.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
77
- mplang_nightly-0.1.dev146.dist-info/RECORD,,
73
+ mplang_nightly-0.1.dev148.dist-info/METADATA,sha256=3hkF4x8KZwg7PaGyfuAiDvp_qH9T1bhWS41rYWwl2Zs,16547
74
+ mplang_nightly-0.1.dev148.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
75
+ mplang_nightly-0.1.dev148.dist-info/entry_points.txt,sha256=mG1oJT-GAjQR834a62_QIWb7litzWPPyVnwFqm-rWuY,55
76
+ mplang_nightly-0.1.dev148.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
77
+ mplang_nightly-0.1.dev148.dist-info/RECORD,,