Context API#
Context packages backend operations and the default dtype. Spaces,
operators, and functionals store a normalized context and use it for array
construction and conversion.
Validation policy is not part of a context: check_level belongs to the
bound object, so two objects on the same backend and dtype may validate at
different strictness. Use check_level="none", "cheap", "standard",
or "strict" on the object, or move the ambient default with
set_check_level / use_check_level. The exported spacecore.CheckLevel
literal is available for annotations. See Checking policy.
Context#
Backend operations plus the default dtype for new arrays. |
- class spacecore.Context(ops: BackendOps[DenseT] | type[BackendOps[DenseT]] | Context[DenseT], dtype: Any | None = None)[source]#
- class spacecore.Context(ops: str, dtype: Any | None = None)
Bases:
Generic[DenseT]Backend operations plus the default dtype for new arrays.
A context owns no arrays; it creates and converts them. It is frozen, and
check_levelis deliberately not part of it (seespacecore.contextual.ContextBound).- Parameters:
ops (BackendOps) – Backend operations, e.g.
spacecore.backend.NumpyOps.dtype (dtype-like or None, optional) – Dtype for
asarray()andassparse(); normalized byops.sanitize_dtype. It does not fix a space’s scalar field.
Examples
Create a NumPy context and convert a Python list to a backend array.
>>> import numpy as np >>> import spacecore as sc >>> ctx = sc.Context(sc.NumpyOps(), dtype=np.float64) >>> x = ctx.asarray([1.0, 2.0]) >>> x.dtype == np.dtype("float64") True
- __init__(ops: BackendOps[DenseT] | type[BackendOps[DenseT]] | Context[DenseT], dtype: Any | None = None) None[source]#
- __init__(ops: str, dtype: Any | None = None) None
Validate and normalize the context after dataclass initialization.
- Raises:
TypeError – If
opsis not aBackendOpsinstance.- Parameters:
ops (BackendOps[DenseT] | type[BackendOps[DenseT]] | Context[DenseT] | str)
dtype (Any | None)
- Return type:
None
- assert_dense(x)[source]#
Return
xif it is a dense array of this backend; raiseTypeErrorotherwise.- Parameters:
x (Any)
- Return type:
DenseT
- assert_sparse(x)[source]#
Return
xif it is a sparse array of this backend; raiseTypeErrorotherwise.- Parameters:
x (Any)
- Return type:
SparseArray
- asarray(x)[source]#
Convert
xto a dense backend array of dtypeself.dtype.Raises
TypeErrorrather than silently dropping an imaginary part.- Parameters:
x (Any)
- Return type:
DenseT
- assparse(x)[source]#
Convert
xto a sparse backend array of dtypeself.dtype.Raises
TypeErrorif the backend has no sparse support, or if the conversion would drop an imaginary part.- Parameters:
x (Any)
- Return type:
SparseArray
- convert(x)[source]#
Convert a dense or sparse backend array to this context; raise
NotImplementedErrorfor anything else.- Parameters:
x (Any)
- Return type:
ArrayLike
- same_math(other)[source]#
Return whether
otherhas equal backend ops and dtype.The first-tier gate of every context-bound
__eq__: it guarantees later value comparisons run on same-backend, same-dtype arrays. Not policy-configurable.- Parameters:
other (Any) – Object to compare against.
- Returns:
Truewhenotheris aContextwith equal ops and dtype.- Return type:
bool
Context helpers#
Return the currently active default SpaceCore context. |
|
Set the process-wide baseline SpaceCore context. |
|
Override the default context inside a |
|
Return the ambient default validation level applied to new bound objects. |
|
Set the ambient default validation level applied to new bound objects. |
|
Override the ambient validation level inside a |
|
Return the process-wide cap on check levels while a backend is tracing. |
|
Set the process-wide cap on check levels while a backend is tracing. |
|
Normalize a context specification through the process-wide state. |
|
Normalize backend operations through the process-wide state. |
|
Resolve the context assigned to a newly created object. |
|
Register a backend in the process-wide registry; registrations are never scoped. |
get_contextandset_contextmanage the global default context, anduse_contextoverrides it for a block, scoped to the current thread or async task.get_check_level/set_check_level/use_check_leveldo the same for the ambient validation level applied to newly constructed bound objects.get_traced_check_level/set_traced_check_levelcap every object’s level while a backend traces (jax.jit,jax.vmap,torch.compile); the default"none"turns checks off in traced code.
- spacecore.get_context()[source]#
Return the currently active default SpaceCore context.
Resolves the
use_context()override for this thread / task if one is installed, otherwise the process-wide baseline set byset_context().- Returns:
Active default context.
- Return type:
- spacecore.set_context(ctx=None, dtype=None)[source]#
Set the process-wide baseline SpaceCore context.
Visible to every thread and async task. A
use_context()override already in progress keeps winning until its block exits.- Parameters:
ctx (Context, BackendFamily, str, or None, optional) – Context or backend specification.
dtype (Any, optional) – Default dtype override.
- Return type:
None
- spacecore.use_context(ctx=None, dtype=None)[source]#
Override the default context inside a
withblock.The override lives in a
ContextVar: it is seen by the current thread and asyncio task only, and is undone on exit. Threads started inside the block see the baseline; run them undercontextvars.copy_context()to pass it on.- Parameters:
ctx (Context, BackendFamily, str, or None, optional) – Context, or a backend family name such as
"jax".Nonekeeps the active context and applies onlydtype.dtype (dtype-like, optional) – Dtype for the scoped context;
Nonekeeps the current one.
- Yields:
Context – The context in effect inside the block.
- spacecore.get_check_level()[source]#
Return the ambient default validation level applied to new bound objects.
- Returns:
The level that seeds a context-bound object constructed without an explicit
check_level: the scoped override installed for this thread or task if there is one, otherwise the process-wide baseline.- Return type:
CheckLevel
- spacecore.set_check_level(level)[source]#
Set the ambient default validation level applied to new bound objects.
check_levelis a property of the context-bound object (space, operator, functional), not of theContext. This sets the process-wide default that seeds a new object when it is constructed without an explicit level.- Parameters:
level ({"none", "cheap", "standard", "strict"} or None) – New process-wide baseline.
Nonerestores the built-in default.- Return type:
None
- spacecore.use_check_level(level)[source]#
Override the ambient validation level inside a
withblock (thread/task-scoped, likeuse_context()).- Parameters:
level ({"none", "cheap", "standard", "strict"} or None) – Level for the block;
Nonekeeps the ambient one.- Yields:
CheckLevel – The level in effect inside the block.
- spacecore.get_traced_check_level()[source]#
Return the process-wide cap on check levels while a backend is tracing.
- Returns:
The cap set by
set_traced_check_level();"none"by default.- Return type:
CheckLevel
- spacecore.set_traced_check_level(level)[source]#
Set the process-wide cap on check levels while a backend is tracing.
Inside
jax.jit,jax.vmaportorch.compilean object checks at the lower of its own level and this cap."cheap"keeps shape and dtype checks, which run once at trace time and cost nothing in the compiled program;"standard"and above compare values, which a tracer cannot do.- Parameters:
level ({"none", "cheap", "standard", "strict"} or None) – New cap.
Nonerestores the default,"none".- Return type:
None
- spacecore.normalize_context(ctx=None, dtype=None)[source]#
Normalize a context specification through the process-wide state.
- spacecore.normalize_ops(ops)[source]#
Normalize backend operations through the process-wide state.
- Parameters:
ops (str, BackendFamily, BackendOps, type of BackendOps, or Context) – Backend operations specification.
- Returns:
Normalized backend operations singleton.
- Return type:
- spacecore.resolve_context_priority(priority_ctx=None, *other_ctx)[source]#
Resolve the context assigned to a newly created object.
- spacecore.register_ops(ops)[source]#
Register a backend in the process-wide registry; registrations are never scoped.
- Parameters:
ops (type of BackendOps) – Backend class to register.
- Returns:
The registered class.
- Return type:
type of BackendOps
- Raises:
ContextConflictError – If the backend family is already registered.