tramdag.nodes¶
tramdag.nodes ¶
The node model: one TRAM regression per variable, alone or in a flow.
Node bundles a variable's intercept (transform parameters), monotone
transform and shift modules, and fits itself; CausalFlowDAG holds one per
node and the DAG lives in which parents each node reads. scores.py, the
read-outs and the tests read kind, parents, shifts, intercept,
ut, net_input and theta_shift by name.
Node ¶
Bases: NodeFitMixin, Module
One TRAM regression of a variable on its parents, alone or in a flow.
It is an intercept plus additive shift terms. The intercept produces the
transform parameters \(\vartheta\). The shift terms add up on the latent
scale. The node-kind maths lives in the five methods log_prob,
sample, abduct, marginal_theta and encode, in the module
function encode and in the score derivative of scores. The
rest of the package reads kind or the schema entry to check, convert
or display values.
The node builds one module per shift term in formula order, because the
draws of one seeded stream are pinned to it. Each shift names its own key: the
parent, "a+b" for a joint CS, the treatment for a VC. The
intercept_module of the first term picks the intercept slot: the free
theta_0, one joint net, or one net per parent summed in coefficient space.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The node's column name. |
required |
node_spec
|
NodeSpec
|
Specification of the node. |
required |
schema
|
dict[str, str | int]
|
The parent schema, |
required |
seed
|
int | None
|
If given, seeds the weight initialization from |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
history |
dict
|
The fit history, see |
calibrated |
Tensor
|
Boolean buffer, set by the first fit's calibration and kept in the checkpoint. It is a buffer, not a Python bool, so the flag rides in the state dict and a loaded node does not recalibrate on its next fit. |
meta |
dict
|
The provenance that |
Source code in src/tramdag/nodes.py
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 | |
encode ¶
encode(values)
Encode this node's values for use as a parent feature.
A continuous parent stays raw, shape (n, 1); an ordinal parent is
one-hot encoded, shape (n, levels).
Source code in src/tramdag/nodes.py
264 265 266 267 268 269 270 | |
features ¶
features(values)
Encode this node's parents out of a raw tensor dict.
Source code in src/tramdag/nodes.py
272 273 274 | |
tensorize ¶
tensorize(df, cols=None)
DataFrame columns -> one (n,) tensor each, in the node's dtype.
cols=None takes the node's own column and its parents. Ordinal
columns, own or parent, are checked to hold level indices.
Raises:
| Type | Description |
|---|---|
KeyError
|
If the frame lacks one of the columns. |
ValueError
|
If an ordinal column is not a level index. |
Source code in src/tramdag/nodes.py
276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | |
calibrate ¶
calibrate(train_df, *, marginal_init=False)
Take the data-dependent state from the training rows, once.
Every term calibrates itself: the intercept term maps the node's
train range_q/1 - range_q quantiles (a transform option, set in
transform_kwargs, default 5%/95%; 0.0 is the min/max) onto the
transform's pre-scaled domain, and every term with an input_transform=
freezes its statistics (minmax lo/hi, standardize mean/std, a
callable's frozen train columns).
The first fit or fit_classical calls this when it has not run
yet; a loaded node is already calibrated, and later fits on other rows
reuse this state. Data on a new scale needs a new node.
marginal_init additionally starts a simple intercept at the
column's marginal: a Bernstein intercept at the Bernstein
approximation of \(\operatorname{logit} \hat F(y)\), an ordinal one at
the marginal class log-odds; spline/affine intercepts and intercepts
with parents are untouched. The start rides on this method's guard, so
a second fit (the next phase of a schedule) continues training
instead of discarding the intercept it just trained.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_df
|
DataFrame
|
Training rows with the node's column and its parents' columns. |
required |
marginal_init
|
bool
|
Also set the calibrated start, by default |
False
|
Returns:
| Type | Description |
|---|---|
Node
|
|
Source code in src/tramdag/nodes.py
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 | |
log_prob ¶
log_prob(theta, shift, x)
log p(x | pa) from the transform parameters and the shift.
Source code in src/tramdag/nodes.py
343 344 345 346 347 348 | |
sample ¶
sample(theta, shift, u)
Push the latent u forward to an observed value.
Source code in src/tramdag/nodes.py
350 351 352 353 354 | |
abduct ¶
abduct(theta, shift, x, generator=None)
Recover the latent: exact (continuous) or truncated-sampled (ordinal).
Source code in src/tramdag/nodes.py
356 357 358 359 360 361 | |
marginal_theta ¶
marginal_theta(column)
Give the node's marginal-start \(\vartheta\), or None when there is none.
Ordinal: the empirical class log-odds. Continuous: the transform's own
marginal start over the same column (None for spline/affine,
nothing to set). Only a free intercept applies it.
Source code in src/tramdag/nodes.py
363 364 365 366 367 368 369 370 371 372 373 | |
net_input ¶
net_input(feats, parents, key)
Concatenate parent features for one term's network.
key names the term ("@I" for the intercept, the shift key
otherwise); a term with an input_transform gets its continuous
parent columns transformed with the statistics frozen at
calibration. Every network input goes through here, training and
the read-outs (varying_coef, intercept_contributions) alike,
so the model seen at inference is the model that was fitted. Linear
shifts and the VC treatment column are not network inputs and never
pass through.
Source code in src/tramdag/nodes.py
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 | |
theta_shift ¶
theta_shift(feats, n)
Compute the transform parameters and the total shift of the node.
The shifts add in order, plain shifts first and VC last. The stable
sort keeps the pinned order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
feats
|
dict[str, Tensor]
|
Encoded parent features keyed by parent name, plus the terms' side columns (a centered VC's propensities, frozen from the training frame, injected live by the flow at query time). |
required |
n
|
int
|
Batch size. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Tensor, Tensor]
|
The transform parameters, shape |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If a centered VC term is evaluated without its propensity
column in |
Source code in src/tramdag/nodes.py
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 | |
ls_coefficients ¶
ls_coefficients()
Give the LS weights as {parent: array}; empty without LS.
Source code in src/tramdag/nodes.py
430 431 432 433 434 435 436 | |
parameter_groups ¶
parameter_groups()
Give every parameter of the node once, by its kind.
An optimizer factory builds its parameter groups from this, for
example weight decay on "networks" only.
Returns:
| Type | Description |
|---|---|
dict[str, list[Parameter]]
|
|
Source code in src/tramdag/nodes.py
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 | |
warm_start ¶
warm_start(train_df)
Start each VC \(\beta_0\) at the classical linear treatment effect.
An all-LS twin of the node, a simple intercept plus one LS
term per parent, fits classically on train_df. Each VC
\(\beta_0\) takes the twin's coefficient of its treatment. A binary
ordinal treatment takes the level-1-against-0 contrast w[1] - w[0],
a continuous one its weight w[0]. Call it before fit; the twin
ignores a centering column. The twin starts from seed 0, so the result
does not depend on torch's global RNG.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_df
|
DataFrame
|
Training rows: the node's column and its parents' columns. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
The twin's |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the node has no |
Source code in src/tramdag/nodes.py
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 | |
save ¶
save(path)
Write the node, its history and its provenance to a checkpoint.
The file holds the node's name, spec, parent schema and weights, its
training history, and a meta block with the tramdag version,
the save time and the device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Target file. Parent directories are created when missing. |
required |
Source code in src/tramdag/nodes.py
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 | |
load
classmethod
¶
load(path, device='cpu')
Restore a node from a checkpoint written by save.
The node's history and meta are refilled.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path
|
Checkpoint file. |
required |
device
|
str
|
Torch device to load onto, by default |
'cpu'
|
Returns:
| Type | Description |
|---|---|
Node
|
The restored node, in eval mode. |
Source code in src/tramdag/nodes.py
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 | |
side_columns ¶
side_columns()
Name the frame columns the node's terms need beyond the parents.
Source code in src/tramdag/fitting.py
389 390 391 392 | |
row_log_prob ¶
row_log_prob(values)
Give log p(x | pa) per row of already tensorized columns.
values holds the node's column, its parents' columns and its side
columns, each shape (n,).
Source code in src/tramdag/fitting.py
414 415 416 417 418 419 420 421 422 423 | |
nll ¶
nll(df)
Give the node's mean negative log-likelihood over the rows of df.
df holds the node's column, its parents' columns and its side
columns (a centered VC's propensity).
Source code in src/tramdag/fitting.py
425 426 427 428 429 430 431 432 433 | |
fit ¶
fit(
train_df,
*,
epochs,
learning_rate=None,
batch_size=512,
validation_data=None,
validation_split=None,
verbose=0,
seed=None,
marginal_init=False,
optimizer=None,
callbacks=None
)
Fit the node by maximum likelihood with one minibatch loop, Adam by default.
The loss is the node's mean NLL plus its own VC penalties. The
loop keeps the final weights, and a second fit call continues
the training. The loop computes the validation NLL and prints the
progress; learning-rate schedules, early stopping and best-weight
restoration are the caller's, through optimizer and
callbacks; callbacks ships EarlyStopping.
The VC penalty never enters history["train"], and a VC
term is re-centered after the loop.
node.history accumulates across fits: "train" and "val"
hold one mean NLL per epoch, "val_epoch" the train epoch each
validation entry belongs to, "lr" the optimizer's rates per epoch
as {group index: lr}. "best_epoch" is the best epoch that an
EarlyStopping of the last fit found, counted like "val_epoch";
a fit without one removes it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_df
|
DataFrame
|
Training rows: the node's column, its parents' columns and its side columns. Other columns are ignored. |
required |
epochs
|
int
|
Number of passes over the data. Required; there is no default. |
required |
learning_rate
|
float
|
Adam step size of the default optimizer. The default (None) is
1e-2. Exclusive with |
None
|
batch_size
|
int
|
Rows per gradient step, by default 512. |
512
|
validation_data
|
DataFrame | None
|
Validation rows, with the same columns as |
None
|
validation_split
|
float | None
|
Keras' rule: the LAST fraction of |
None
|
verbose
|
int
|
0 (default) is silent. |
0
|
seed
|
int | None
|
Seeds the minibatch shuffling with a private generator, by
default None (torch's global RNG). |
None
|
marginal_init
|
bool
|
Start a simple intercept at its column's marginal, by default
|
False
|
optimizer
|
Optimizer | callable | None
|
A torch optimizer over |
None
|
callbacks
|
Callback | callable | list | None
|
One entry or a list, by default None. A
|
None
|
Returns:
| Type | Description |
|---|---|
Node
|
|
Notes
fit validates the frames before it calibrates, so a malformed frame
cannot half-mutate the node. A batch of one row is skipped: batch norm
needs two rows and one row gives no gradient.
history["val_epoch"] holds the train epoch of each validation
entry. history accumulates across fit calls, so an unvalidated
fit would otherwise shift every later validation entry away from its
own epoch.
Every callback runs at each epoch end, so a stop does not skip a
monitoring callback. The learning rate is read after the callbacks, so
a scheduler's decision for this epoch shows. on_fit_end runs before
the VC re-centering, so weights that a callback restores (such as
EarlyStopping) still take part in it.
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
KeyError
|
If a frame lacks a column the node reads. |
Source code in src/tramdag/fitting.py
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 | |
fit_classical ¶
fit_classical(train_df, *, max_iter=5000, history_size=50)
Fit a simple intercept with LS terms the classical way.
The fit uses full batches, float64, and L-BFGS with a strong-Wolfe
line search, then Newton steps on the exact Hessian. There are no
minibatches, no schedule and no early stopping, so the fit is
deterministic; the report says whether it reached the
maximum-likelihood estimate. Any other term raises.
docs/fitting.md says why.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_df
|
DataFrame
|
Training rows: the node's column and its parents' columns. |
required |
max_iter
|
int
|
Upper limit on L-BFGS iterations and Newton steps together, by default 5000. |
5000
|
history_size
|
int
|
L-BFGS memory, by default 50. |
50
|
Returns:
| Type | Description |
|---|---|
dict
|
A convergence report: |
Warns:
| Type | Description |
|---|---|
UserWarning
|
If the report is not |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a term is not classical: anything but the simple intercept and
|
KeyError
|
If the frame lacks a column the node reads. |
Notes
L-BFGS stops when one iteration lowers the NLL by less than 1e-9. On an ill-conditioned NLL, for example a parent on a large raw scale next to a rare level, this happens short of the optimum. Newton steps on the exact Hessian then finish the fit. The coefficients are read while the node is float64. The cast back to float32 loses about 1e-7 relative.
float64 is a transient compute mode. The node is upcast for the fit,
and self.double() converts the parameters and the range buffers of
the transform in one call. Afterwards the node returns to float32, so
the stored model and save/load stay float32. Double precision
is what lets the line search resolve the optimum cleanly.
stop_reason is what ended the run: "tolerance" when L-BFGS and
the Newton steps stopped on their own, "max_iter" when the
iteration budget ran out, and "max_eval" when torch's evaluation
budget (max_iter * 5 // 4 closure calls, line searches included)
ran out first. n_iter counts the L-BFGS iterations and the Newton
steps. tolerance_grad is 0, so the gradient never ends the run.
Only a "tolerance" stop of L-BFGS gets the Newton steps.
The Newton steps stop when the decrement is at most
DECREMENT_TOL (1e-9), or when no step lowers the NLL. The decrement
is the decrease of the mean NLL that a Newton step still expects. It
does not depend on the scale of the parents, which the gradient norm
does. A Bernstein NLL converges only linearly in its weakly curved
tail coefficients, so this can take many steps. A spline NLL
is only piecewise smooth: at a kink its Hessian is indefinite, no step
lowers the NLL, and the decrement is above the bound.
converged is stop_reason == "tolerance": a stall short of the
optimum is not converged, because the Newton steps continue from it
until they stop on their own or spend the budget.
The Newton step skips the eigenvalues of the Hessian at float64 noise
level. So it does not move along a direction with zero curvature,
such as the one that the one-hot of an ordinal parent shares with the
cutpoints. Compare the contrasts w[k] - w[0] with other software.
Source code in src/tramdag/fitting.py
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 | |
encode ¶
encode(values, entry)
Encode one column as a parent feature.
entry is a schema entry: "continuous" stays raw, shape (n, 1);
a level count one-hot encodes, shape (n, levels).
Source code in src/tramdag/nodes.py
49 50 51 52 53 54 55 56 57 58 | |
schema_entry ¶
schema_entry(node_spec)
Give a node's schema entry: "continuous" or its level count.
Source code in src/tramdag/nodes.py
61 62 63 | |
check_columns ¶
check_columns(df, cols)
Name the columns df lacks, before any tensor op would.
Source code in src/tramdag/nodes.py
66 67 68 69 70 71 72 73 | |
check_level_values ¶
check_level_values(name, values, levels)
Reject ordinal values that are not level indices of their node.
bincount, the cutpoint likelihood and the one-hot parent
encoding all take the values as 0..levels-1; a 1-based or
non-integer value would silently be truncated instead of failing.
Source code in src/tramdag/nodes.py
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | |
tensorize ¶
tensorize(df, cols, levels, dtype, device)
DataFrame columns -> one (n,) tensor each, in dtype on device.
A column named in levels is checked to hold level indices first,
any other column to hold finite values.
Source code in src/tramdag/nodes.py
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | |
write_checkpoint ¶
write_checkpoint(path, payload, device)
Save payload plus a meta block with torch.save.
meta holds the tramdag version, the save time and the device.
Raises:
| Type | Description |
|---|---|
ValueError
|
If the spec does not pickle (a callable |
Source code in src/tramdag/nodes.py
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 | |
load_weights ¶
load_weights(module, state_dict)
Load a checkpoint's state dict into a freshly built module.
A callable input transform's frozen train columns take the checkpoint's shape first; their buffer is empty until calibration.
Source code in src/tramdag/nodes.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | |
seeded ¶
seeded(seed, name)
Draw the block's random numbers from a stream keyed on (seed, name).
The block runs in torch.random.fork_rng, so torch's global RNG state
is the same after the block as before it. Without a seed the block draws
from torch's global stream.
Source code in src/tramdag/nodes.py
163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |