# Samples What one example may read at its prediction time: rows, values, calculations, histories, graph neighborhoods, candidates and generated targets. [API reference index](README.md) ### `SampleSpec` *class* · `kumo.pytorch.api.SampleSpec` ```python class SampleSpec( entity: EntitySpec, entity_values: Mapping[str, EntityValue] = {}, dated_entity_values: Mapping[str, DatedEntityValue] = {}, events: Mapping[str, EventSpec] = {}, current_events: Mapping[str, EventSpec] = {}, neighborhoods: Mapping[str, NeighborhoodSpec] = {}, targets: Mapping[str, Aggregate | Compare | RowTarget | ExternalTarget] = {}, candidate_sets: Mapping[str, CandidateSetSpec] = {}, ) ``` Named raw data components belonging to one entity at one point in time. Values here are typed raw data, not encodings: how they reach a model is chosen in `BatchSpec`. Named calculations may refer to each other in any declaration order; unknown names and cycles are refused. A contract needs an anchor time when a table it reads has a clock or a value depends on time; see `DataLoaderSpec.requires_anchor_time`. **Parameters** - `entity`: the table each sample is about. - `entity_values`: named scalar values: fields, constants, aggregates, comparisons and calculations. - `events`: named historical event components. Several components can merge into one batch input; equal-time events then order by component name and primary key, or local occurrence identity for a keyless table. - `dated_entity_values`: repeated timestamped facts, as opposed to the single values in `entity_values`. - `current_events`: events kept apart from `events` so an objective can distinguish the event being predicted from its history. Each requires `TimeWindow(column=..., start=-1, stop=0)` and `limit=1`, selecting the event at the anchor's stored second; a historical window ending at zero still includes that event too. - `neighborhoods`: named graph neighborhoods around the entity. - `targets`: labels computed from future rows. Labels already known to the caller arrive on the request instead and are declared here with `ExternalTarget`. A computed target needs an explicit future window whose lower bound is at or after zero; that bound is excluded, so a target never reads an event at the anchor itself. Declaring a target never inserts it into an input. - `candidate_sets`: how to build the candidates a request supplies. ### `EntitySpec` *class* · `kumo.pytorch.api.EntitySpec` ```python class EntitySpec( table: str, *, entity_type: str | None = None, filters: tuple[RowFilter, ...] = (), available_from: str | None = None, ) ``` The table each sample is about, identified by its schema primary key. Requests identify entities by the table's primary key; there is no second lookup column. **Parameters** - `table`: the entity table; its schema primary key supplies identity. - `entity_type`: the name this entity carries downstream, e.g. the node type in a graph batch; defaults to `table`. - `filters`: eligibility conditions on the entity row. - `available_from`: column holding when the entity came into existence. A request anchored at or before it is refused rather than answered. ### `Rows` *class* · `kumo.pytorch.api.Rows` ```python class Rows( path: tuple[str, ...] = (), time: TimeWindow | None = None, filters: tuple[RowFilter, ...] = (), active: ActiveInterval | None = None, distinct: bool = True, ) ``` Rows reached by following relationships from the sample entity. When `time` is omitted, the destination table's declared clock is used with the historical window ending at the sample time. **Parameters** - `path`: relation names to follow in order; empty selects the entity row itself. A relation may be traversed in either direction. - `time`: the window relative to the anchor; its column must be a `timestamp` or `date32`. - `filters`: typed comparisons on destination columns. - `active`: restricts to rows whose validity interval contains the prediction time, which is a different question from when they occurred. - `distinct`: after traversal, keep one visit per destination row, identified by its primary key or its occurrence when keyless. Separate identical source rows remain separate; joins can revisit the same row. ### `TimeWindow` *class* · `kumo.pytorch.api.TimeWindow` ```python class TimeWindow(column: str, start: int | None = None, stop: int | None = 0) ``` A half-open time window relative to each sample's prediction time. `start` is exclusive and `stop` is inclusive. `None` means the bound is open, so `TimeWindow("at", stop=0)` means every row at or before the prediction time and `TimeWindow("at", start=0, stop=None)` means every row strictly after it. Bounds are offsets in seconds from the anchor. Historical context stops at or before zero; generated targets start at or after zero. The column, like every column compared with an anchor time, must be a `timestamp` or `date32`; `check` refuses any other type. ### `RowFilter` *class* · `kumo.pytorch.api.RowFilter` ```python class RowFilter(column: str, operation: FilterOperation, value: Any = None) ``` One explicit comparison applied to rows selected by a recipe. **Parameters** - `value`: the comparison operand; a sequence for `in`/`not_in` and unused by `is_null`/`not_null`. #### `RowFilter.matches` ```python RowFilter.matches(row: Mapping[str, Any], dtype: DType | None = None) -> bool ``` Whether `row` passes this filter; the row must hold the column. ### `ActiveInterval` *class* · `kumo.pytorch.api.ActiveInterval` ```python class ActiveInterval(start_column: str, end_column: str) ``` Columns describing an active interval. A row is eligible when its start is strictly before the anchor and its end is absent or strictly after it. Both columns must be `timestamp` or `date32`. DiskGraph refuses active intervals. ### `Field` *class* · `kumo.pytorch.api.Field` ```python class Field( column: str, path: tuple[str, ...] = (), selection: Selection = 'one', time_column: str | None = None, reference_time: ReferenceTime = 'sample', ) ``` A typed value read from a stored column. The DiskGraph engine doesn't support a joined field (nonempty `path`) yet; see the limitations page. **Parameters** - `column`: source column whose dtype comes from the table schema. - `path`: relations followed from the current row before reading; empty reads the current row. - `selection`: which row to use when `path` returns several: `"one"` expects at most one, `"all"` keeps every occurrence (not a valid calculation operand), `"latest"` takes the latest eligible row and needs a clock, inherited or given by `time_column`. - `time_column`: overrides the destination table's declared clock. - `reference_time`: whether the point-in-time lookup is as of the sample anchor (`"sample"`) or, for an event field, as of that event (`"event"`). ### `Constant` *class* · `kumo.pytorch.api.Constant` ```python class Constant(value: Scalar | None, dtype: DType) ``` An explicitly typed scalar, including a typed NULL. `Constant(value=None, dtype=...)` is a typed NULL. The value is validated against `dtype`, never converted. ### `Derived` *class* · `kumo.pytorch.api.Derived` ```python class Derived( operation: DerivedOperation | CalendarPart | MapValues, inputs: tuple[str, ...], *, dtype: DType | None = None, ) ``` Arithmetic over named values in the same entity or candidate group. Operations: `add`, `subtract`, `multiply` (Arrow numeric promotion, for example int64 plus float64 gives float64; decimal multiplication adds the operand scales); `divide` and `log1p` (`float64`); `abs` (same family); `sign` (`int64` -1, 0 or 1); and the configured `CalendarPart` and `MapValues`. Numerical operands exclude booleans. A missing operand gives a missing result; division by zero and `log1p(x)` for `x <= -1` give missing values. Integer and decimal results are checked against their type's range; floating results keep native rounding and overflow, including infinity. **Parameters** - `operation`: the fixed operation; not a user function. - `inputs`: value names, not columns. Prerequisites are evaluated first, regardless of declaration placement. Operand order is preserved. Operands must be scalar. - `dtype`: optional checked expectation, or a compatible widening: a wider integer, float32 to float64, or a larger decimal precision. ### `CalendarPart` *class* · `kumo.pytorch.api.CalendarPart` ```python class CalendarPart( part: Literal['year', 'month', 'day', 'weekday', 'hour', 'minute', 'second'], timezone: Literal['UTC'] = 'UTC', ) ``` Extract one UTC calendar component from a timestamp or date. Use it as `Derived(operation=CalendarPart(...), inputs=(name,))`. The result is `int64`. `date32` inputs accept date components only. ### `MapValues` *class* · `kumo.pytorch.api.MapValues` ```python class MapValues( groups: Mapping[Scalar, tuple[Scalar, ...]], unknown: Literal['error', 'null', 'fallback'] = 'error', fallback: Scalar | None = None, ) ``` Map disjoint sets of source values to explicitly supplied result values. Used as a `Derived` operation, which must declare the result `dtype`. Members are normalized to the operand type before overlap is checked, and must be finite and non-NULL. A NULL operand stays NULL rather than selecting a group or the fallback. **Parameters** - `groups`: result value to the source values that map to it. - `unknown`: policy for a value in no group: `"error"`, `"null"`, or `"fallback"` with a typed `fallback`. ### `EventTimeDelta` *class* · `kumo.pytorch.api.EventTimeDelta` ```python class EventTimeDelta( unit: Literal['seconds', 'minutes', 'hours', 'days'] = 'seconds', *, dtype: DType = DType(name='float64', unit=None, timezone=None, precision=None, scale=None), ) ``` Elapsed time from an event to its sample anchor, emitted as a number. The value is `(anchor time - event time)` in `unit`; it is not relative to the latest event. Nothing like it is emitted unless declared. **Parameters** - `unit`: unit of the emitted number. Row-window offsets stay in seconds regardless. #### `EventTimeDelta.seconds_per_unit` *property* Seconds in one `unit`. ### `Aggregate` *class* · `kumo.pytorch.api.Aggregate` ```python class Aggregate( source: RowSource, operation: SummaryOperation, column: str | None = None, *, dtype: DType | None = None, ) ``` Reduce a row source to one typed value. The same object is valid in `SampleSpec.entity_values` and `SampleSpec.targets`. Its placement determines whether it is context or supervision; the time window determines which rows are eligible. Operations and result types: `count` and `count_distinct` give `int64`; `sum` gives exact `int64` for signed and `uint64` for unsigned integers (a range error, never wraparound), `float64` for floats (native rounding and overflow kept); `mean`, `std_population`, `std_sample`, `var_population` and `var_sample` give `float64`; `min` and `max` (numerical, string, date, timestamp) and `mode` (any scalar) keep the column's type; `recency` gives `float64` seconds. NULL values are ignored. An empty row set gives zero for `count`, `count_distinct` and `sum`; a nonempty set whose values are all NULL gives a missing sum; other reductions without observations are missing. Population spreads divide by `n` and sample spreads by `n - 1`, so one observation gives population spread zero and a missing sample spread. `mode` breaks frequency ties by `(type name, repr(value))`. Raw float `count_distinct` and `mode` compare IEEE bit patterns, so positive and negative zero differ. DiskGraph refuses reductions over bytes and decimals. **Parameters** - `source`: the rows (or grouped rows) reduced. - `operation`: the reduction. - `column`: the column reduced; omitted only for `count`. - `dtype`: optional checked result type; omitted types follow the operation. ### `GroupBy` *class* · `kumo.pytorch.api.GroupBy` ```python class GroupBy( source: Rows | GroupBy, keys: tuple[str, ...], values: Mapping[str, Reduce], ) ``` Turn rows into one row per key with explicitly named aggregate values. A grouped result can be the source of another `GroupBy` or `Aggregate`. This is enough to express, for example, the mean of per-account transaction counts without adding a model-specific feature class. **Parameters** - `source`: rows to group, or another grouping to group again. - `keys`: columns whose distinct combinations define one group. - `values`: output name to the reduction producing it. ### `Reduce` *class* · `kumo.pytorch.api.Reduce` ```python class Reduce( operation: SummaryOperation, column: str | None = None, *, dtype: DType | None = None, ) ``` One aggregation performed inside each group of a `GroupBy`. Takes the same operations, result types and missing-value rules as `Aggregate`. **Parameters** - `column`: the column reduced; omitted only for `count`. - `dtype`: optional checked result type. ### `Compare` *class* · `kumo.pytorch.api.Compare` ```python class Compare( left: Aggregate, operation: ComparisonOperation, right: Scalar, *, dtype: DType = DType(name='bool', unit=None, timezone=None, precision=None, scale=None), ) ``` Compare an aggregate result with one compatible scalar value. The result is a typed boolean; a missing aggregate stays missing. ### `DatedEntityValue` *class* · `kumo.pytorch.api.DatedEntityValue` ```python class DatedEntityValue( rows: Rows, field: Field | Constant, first_per_value: bool = False, fields: Mapping[str, Field | Constant | Derived | EventTimeDelta] = {}, ) ``` One repeated, timestamped value associated with the entity. The DiskGraph engine doesn't support this yet; see the limitations page. **Parameters** - `rows`: the timed rows holding the occurrences. - `field`: the value of each occurrence. - `first_per_value`: keep only the earliest occurrence of each distinct value, turning a history into "when did this first become true". - `fields`: additional typed values per retained occurrence, such as an `EventTimeDelta` age; `OccurrencesOf` projects them onto token positions. ### `EventSpec` *class* · `kumo.pytorch.api.EventSpec` ```python class EventSpec( rows: Rows, fields: Mapping[str, Field | Constant | Derived | EventTimeDelta], limit: int | None = None, order: Literal['ascending', 'descending'] = 'ascending', ) ``` Rows and fields for one named chronological event component. Fields can be columns, constants, calculations over the event's own fields, or an explicit `EventTimeDelta`. Timestamps, calendar parts and ages are emitted only when declared as fields. **Parameters** - `rows`: the events' rows and window. - `fields`: named values per event. - `limit`: maximum events kept, applied *after* `order`, so `order="descending"` keeps the most recent and `"ascending"` the oldest. - `order`: chronological direction the events are sorted in. ### `CandidateSetSpec` *class* · `kumo.pytorch.api.CandidateSetSpec` ```python class CandidateSetSpec( entity: EntitySpec, values: Mapping[str, EntityValue] = {}, targets: Mapping[str, Aggregate | Compare | RowTarget | ExternalTarget] = {}, ) ``` Point-in-time values and optional generated targets for named candidates. Each candidate uses the primary request's time, and its values and targets follow the same typed sampling rules as the entity's. Candidate generation is the caller's. The DiskGraph engine doesn't support candidate sets yet; see the limitations page. **Parameters** - `entity`: what a candidate *is*; candidates are supplied per request, not selected here. #### `CandidateSetSpec.sample_spec` ```python CandidateSetSpec.sample_spec() -> SampleSpec ``` Use normal sample construction for each caller-supplied candidate. ### `NeighborhoodSpec` *class* · `kumo.pytorch.api.NeighborhoodSpec` ```python class NeighborhoodSpec(layers: tuple[GraphLayer, ...]) ``` Rows belonging to one sampled neighborhood around the entity. Layers expand in order from the entity. A row or edge reached more than once appears once per sample in the default relations topology. `Graph(topology="sampled")` instead retains native direction and hop counts. Node attributes are chosen in `BatchSpec` through a `Graph` representation, not here. ### `GraphLayer` *class* · `kumo.pytorch.api.GraphLayer` ```python class GraphLayer(samples: tuple[GraphSample, ...]) ``` Relationship traversals performed from one neighborhood frontier. ### `GraphSample` *class* · `kumo.pytorch.api.GraphSample` ```python class GraphSample( relation: str, fanout: int, direction: Literal['forward', 'reverse'] = 'forward', strategy: Literal['recent', 'uniform'] = 'recent', time_column: str | None = None, temporal: Literal['inherit', 'static'] = 'inherit', ) ``` One bounded relationship traversal used to select neighboring rows. Emitted edges keep the relation's left-to-right orientation whatever the traversal direction, self-relations included. **Parameters** - `fanout`: maximum neighbors kept per frontier row. - `direction`: which way to follow the relation; `"forward"` is left table to right as written in `RelationSpec`. - `relation`: the declared relation followed. - `strategy`: how to choose when more neighbors exist than `fanout`: `"recent"` (the default) keeps the most recent and needs a clock, even when `temporal="static"`; `"uniform"` draws evenly among the candidates. Which tied neighbors at the fanout limit are kept is unspecified (G-GRAPH-001). The DiskGraph engine supports `"recent"` only. - `time_column`: overrides the destination table's declared clock. - `temporal`: `"inherit"` filters by the resolved clock; `"static"` states that this traversal is deliberately unfiltered. ### `ExternalTarget` *class* · `kumo.pytorch.api.ExternalTarget` ```python class ExternalTarget(dtype: DType) ``` The type of a caller-supplied label; an absent label remains missing. Labels arrive on `SampleRequest.targets` or an anchor-table column. A supplied label cannot replace a generated target of the same name, and an external label alone does not make a contract temporal. ### `RowTarget` *class* · `kumo.pytorch.api.RowTarget` ```python class RowTarget( rows: Rows, fields: Mapping[str, Field | Constant | Derived | EventTimeDelta], selection: Literal['first', 'last'] = 'first', ) ``` Select one future row and expose configured fields as one target event. **Parameters** - `rows`: future rows; the window's lower bound is at or after zero and excluded. - `fields`: values exposed from the selected row. - `selection`: which row of the window to take, in chronological order. ### `SampleRequest` *class* · `kumo.pytorch.api.SampleRequest` ```python class SampleRequest( sample_id: str | int, entity_id: int, as_of_time: int | date | datetime, targets: tuple[TargetValue, ...] = (), split: str | None = None, metadata: Mapping[str, Any] = {}, candidates: Mapping[str, tuple[CandidateRequest, ...]] = {}, ) ``` One requested entity/time pair and any already-derived target values. **Parameters** - `entity_id`: primary-key value in the sample's declared entity table. - `sample_id`: identifies the sample in batch metadata. - `as_of_time`: the prediction time every window in the sample is relative to. Naive dates and datetimes are read as UTC. Required when the contract is temporal, refused when it is not. - `targets`: labels supplied by the caller rather than computed from rows. - `split`: free-form partition label carried through to the batch. - `metadata`: opaque values carried through untouched. - `candidates`: candidate-set name to the candidates to score for it. ### `CandidateRequest` *class* · `kumo.pytorch.api.CandidateRequest` ```python class CandidateRequest(entity_id: int, targets: tuple[TargetValue, ...] = ()) ``` One caller-chosen candidate and any label already known for it. **Parameters** - `entity_id`: primary-key value in the candidate's declared table. - `targets`: labels supplied by the caller, for candidates whose supervision is not derived from rows. ### `TargetValue` *class* · `kumo.pytorch.api.TargetValue` ```python class TargetValue(name: str, value: Any) ``` A target carried beside a sample and never inserted into its inputs. **Parameters** - `name`: an `ExternalTarget` declared in `SampleSpec.targets`. - `value`: the label, validated against the declared dtype. ### `BuiltSample` *class* · `kumo.pytorch.api.BuiltSample` ```python class BuiltSample( sample_id: str | int, history: EntityHistory, targets: tuple[TargetValue, ...], current_events: Mapping[str, tuple[Event, ...]] = {}, metadata: Mapping[str, Any] = {}, candidates: Mapping[str, tuple[BuiltSample, ...]] = {}, ) ``` The raw history consumed by model tokenizers plus separate targets. This is the engine boundary: whatever produced it, everything downstream sees only this. **Parameters** - `candidates`: one nested sample per candidate, built the same way.