TSRDA / PASTIS /main_method /README.md
Dhruv1000's picture
Add root README; point moved PASTIS links at PASTIS/
c621db6 verified
|
Raw History Blame Contribute Delete
65.1 kB

Unified supervisor notebook — 17 October 2026

One notebook: scratch pretraining through the historical 60.44% recipe · Download · Run guide and checks

Fill in only PASTIS_ROOT. Run All installs a private environment, pretrains our encoder from random initialization, saves and uses its checkpoint for all downstream training, downloads/freezes TESSERA, fits every readout and evaluates raw PASTIS. No old T-SRDA fine-tuned component is downloaded. Both historical 58.63 and 60.44 recipes are explained and evaluated in the same file. Full scratch training can take multiple days; the new measured score is not guaranteed to equal the historical 60.4429%. Real PASTIS was unavailable during preparation, so the validation scope is documented explicitly.

From-scratch architecture and checkpoint flow


October 12 current results

Publication update — 12 October 2026. Best observed Test mIoU: 60.4429%; its validation mIoU: 65.8657%. Primary highest-validation-selected method: 66.3467% validation / 59.9973% test.

The new improvement comes from spatial statistics of frozen optical temporal features, not further encoder fine-tuning. The 60.4429% method adds a 5×5 local feature mean and standard deviation to every 256D pixel vector, fits a training-only 768D shrinkage-covariance Gaussian classifier, and blends it with the preceding 59.0010% ensemble. The validation-selected method instead performs three rounds of feature-affinity probability diffusion. The difference in selection status is retained throughout this release.

Current detailed release report · All 63 context experiments · Per-class scores and uncertainty · Current inference guide

Method Validation mIoU % Test mIoU % Interpretation
Historical foundation ensemble 64.1505 58.6346 Historical validation-selected control
Quadratic readout, eta 0.05 64.4319 58.4853 Rejected: lower test score
Covariance shrinkage 0.03 64.3801 58.5651 Rejected: lower test score
5×5 neighborhood mean 65.3036 59.0010 Parent spatial baseline
Entropy-weighted diverse ensemble 64.6969 58.4377 Rejected: lower test score
Three-pass feature-affinity diffusion 66.3467 59.9973 Primary highest-validation selection
Mean of affinity and moments branches 66.2347 60.4334 Tested validation-promoted alternative
5×5 feature mean + standard deviation 65.8657 60.4429 Best observed test shortlist result
Summer-crop conditional specialist 65.6879 59.2033 Tested validation-promoted alternative

The supervised STCLN configuration remains 76 ordered training entries (72 unique, fold 1), 76 ordered validation entries (71 unique, fold 2), seed 3407, and two fixed 32×32 crops per entry: [0:32,0:32] and [32:64,32:64]. Duplicates remain included. There are 99,345 scored training pixel entries and 93,361 scored validation pixel entries, ten Sentinel-2 bands and twenty output columns. Metrics score ground-truth classes 1–18, excluding ground-truth 0/19. Full test evaluation uses 482 fold-4 native 128×128 patches and 3,961,114 scored pixels.

This matches the downloaded reference's supervised dataset configuration, not every experimental resource or evaluation choice. TESSERA is externally pretrained/distilled and uses acquisition-calendar inputs; its geographic pretraining overlap is uncertified. Seed 3407 does not imply an identical optimization trajectory or upstream pretraining seed. Context is restricted to each original 32×32 crop during fitting/validation and spans full 128×128 patches at test time. Repeated inspection of the same test fold makes these exploratory results. Best observed test performance must not be presented as a pristine validation-selected benchmark.


Preserved previous report

The following report documents the historical system through October 11; it is retained for provenance.

Main method — frozen satellite representation transfer

Updated 11 October 2026. 64.1505% validation / 58.6346% Test mIoU. Improvement over the immediately preceding incumbent: +8.3883 percentage points.

This folder now leads with the highest validation-selected measured system. Older configuration folders and the original pretrained checkpoint remain intact. The earlier spatial–temporal system is still a component of the final ensemble.

Detailed current architecture

Comparison scope: supervised sample lists, duplicates, folds, crop coordinates and local numerical seed match the downloaded STCLN code. This is an external-pretraining + acquisition-calendar track, not an identical-pretraining-budget STCLN comparison. External pretraining geographic disjointness is not certified. Checkpoint-specific normalization, temporal padding, selection criteria, ensemble size and confusion-matrix conventions also differ. Repeated test inspection makes the project exploratory; validation-frozen promotion in this round does not erase that history.

Complete notebook

Full pretraining, fine-tuning and ensemble notebook includes all original pretraining/fine-tuning code, automatic frozen TESSERA download, new classifier fitting and fresh raw-data inference. Its default Run All starts original pretraining from scratch and carries the newly saved checkpoint through downstream training; only the PASTIS path is edited. Notebook guide.

The original checkpoint uses atrous spatial encoding with Temporal Spatial-Reduction Dual-Attention, which replaced the DaViT/Swin-style temporal encoder. We retain the true implementation, not a substituted Swin architecture. TESSERA upstream teacher pretraining is external; its released student code and our downstream procedure are included.

Results and selection

Configuration Validation mIoU Test mIoU Status
Original SAM optimizer network 50.0067% 47.5001% Historical single-network baseline
Spatial network + cluster readout + old/new temporal CNNs 52.5640% 49.4555% Historical validation-selected reference
Reference + Gaussian readout + structured self-supervised branch 53.3274% 50.2463% Incumbent before foundation transfer
Frozen pretrained optical encoder + Gaussian readout alone 63.1343% 57.1841% New standalone branch
50% incumbent + 50% pretrained optical branch 64.1505% 58.6346% New validation-selected recommendation
50% incumbent + missing-radar fused pretrained branch 61.1794% 57.1967% Tested alternative
Matched random optical encoder alone 35.0747% — Rejected on validation
Matched random fused encoder alone 26.7142% — Rejected by promotion gate

Final test pixel accuracy is 84.8792%, macro F1 70.9305%, Cohen’s kappa 0.814272 over 3,961,114 valid pixels. The validation–test gap is 5.5159 points; validation is fixed cropped geometry and test is full patches, so this does not directly quantify domain shift on identical pixels. Seventeen of eighteen classes improve; Sorghum declines.

From the supplied checkpoint to the final system

  1. Original supplied pretraining. We retained the supplied T-SRDA spatial–temporal checkpoint. The historical source reconstructs masked Sentinel-2 time-series observations using the original fold-5 self-supervised pool; its temporal blocks and spatial head are described in the historical implementation below. This release does not rerun or alter that supplied checkpoint. Details recovered from code must not be mistaken for independently verified knowledge of every step used to create a supplied file.
  2. Supervised adaptation of that network. The encoder feeds an Atrous Spatial Pyramid Pooling / spatial segmentation head. Experiments explored learning rates, losses, Exponential Moving Average, Sharpness-Aware Minimization and decoder changes on the same labeled lists. The selected SAM-optimizer network scores 47.5001% test.
  3. Training-derived cluster classifier. Frozen intermediate spatial–temporal features are compared with several cluster representative vectors per class using cosine similarity and a temperature. Its probabilities complement the network's own head.
  4. Independent temporal CNNs. Each pixel's ten-band sequence passes through a projection, residual depthwise temporal convolutions at dilations 1/2/4/8, masked temporal pooling and an eighteen-class head. Two separately optimized CNNs complement the spatial network. The original four-component reference reaches 49.4555% test.
  5. Gaussian classifier and structured self-supervised branch. A shared-covariance Gaussian classifier reads frozen original-network features; a separately retained branch adapts the original network with short structured masked-reconstruction self-supervision. Validation-selected probability averaging reaches 50.2463% test. These additions do not explain the later eight-point gain by themselves.
  6. External foundation representation. We load the released TESSERA v2 Small student, already pretrained/distilled by its authors. We use its optical backbone before radar fusion, freeze every parameter and extract a 256-dimensional vector for each pixel. We do zero encoder fine-tuning epochs.
  7. Fit a new Gaussian classifier. Only the original 99,345 foreground training pixel entries fit feature mean, standard deviation, class means and shared covariance. Validation selects shrinkage 0.1, softmax temperature 4 and a 50% ensemble weight.
  8. Freeze the recipe, then evaluate test. Promotion was frozen at 2026-10-10 20:58:31.639862 UTC; the test job started at 20:58:32.115879 UTC. Independently reconstructed confusion matrices and every raw test label agree.

Exact frozen optical architecture

The full released student has 7,112,322 parameters; the optical branch has 3,227,905. Each pixel is encoded independently in this branch; there is no new spatial decoder or neighborhood operation. The original ensemble supplies complementary spatial context.

Per-pixel input: T real observations × 10 optical bands + acquisition day of year
  → band MLP: Linear(10,256) → ReLU → Linear(256,256)
  → add sinusoidal raw day-of-year encoding
  → 4 post-LayerNorm Transformer encoder layers
       width 256, 4 attention heads, feed-forward 256→1024→256, ReLU
       Q/K normalization disabled; evaluation dropout disabled
  → Linear(256,1), softmax over time, weighted attention pooling
  → 256-dimensional optical representation (before Sentinel-1 fusion)
  → train-only standardization → shared-covariance Gaussian scores
  → temperature-4 softmax over classes 1–18 → 20-column probabilities

Input adapter: why the details matter

foundation_transfer.prepare() reverses the historical loader normalization to recover raw reflectance, then maps PASTIS [B02,B03,B04,B05,B06,B07,B08,B8A,B11,B12] to the checkpoint order [B04,B02,B03,B08,B8A,B05,B06,B07,B11,B12], index map [2,0,1,6,7,3,4,5,8,9]. It applies the checkpoint's supplied ten-band means and standard deviations.

Actual acquisition dates become raw integer day of year. The index-zero first acquisition is retained; trailing loader padding is removed. All real observations are kept. Selected observations and their dates are repeated to reach the next multiple of eight, e.g. 43→48. This is the documented inference adapter, not additional satellite data. The unsuccessful fused alternative uses an official-style constant zero missing-radar token; no radar images were added.

Gaussian classifier mathematics

For training feature vector f, compute z=(f−mean)/max(std,0.01). Estimate eighteen class means μc and the pooled within-class covariance Σ from foreground training entries. Use uniform class priors. The selected covariance is Σs=0.9Σ+0.1 mean(eigenvalues(Σ)) I, with eigenvalue floor 1e−6.

Each class score is zᵀΣs⁻¹μc − 0.5 μcᵀΣs⁻¹μc. Divide scores by 4 and softmax. This is shrinkage Linear Discriminant Analysis, equivalently Gaussian class distributions with shared covariance. It is not Quadratic Discriminant Analysis or an optimizer-trained neural head.

Original fitting used float16 cached features converted to float32. Test classification used fresh float32 features produced by mixed-precision inference. The portable entry point preserves this distinction.

Complete probability recipe

P_final = 0.50 P_incumbent + 0.50 P_TESSERA_optical_Gaussian
P_incumbent = 0.65 P_reference + 0.25 P_original_Gaussian + 0.10 P_structured_SSL
P_reference = 0.28125 P_SAM_optimizer + 0.28125 P_cosine_class_clusters
            + 0.1875 P_old_temporal_CNN + 0.25 P_new_temporal_CNN

These are nested probability averages, not logit averages. Preserve the nesting to reproduce floating-point arithmetic. SAM means Sharpness-Aware Minimization, not Segment Anything. Class clusters are several training-derived representative feature vectors per crop class, not extra semantic classes.

Dataset configuration

Item Verified configuration
Local fine-tuning / fitting seed 3407; not a claim of identical RNG trajectories or external pretraining seed
Training 76 ordered entries, 72 unique, fold 1; upstream duplicates retained
Validation 76 ordered entries, 71 unique, fold 2; upstream duplicates retained
Training / validation crops Two fixed 32×32 windows: [0:32,0:32] and [32:64,32:64]; 152 crop entries per full pass
Classifier fit 99,345 foreground training pixel entries, including duplicated entries
Test 482 unique fold-4 patches, native 128×128, batch 1
Bands / labels 10 Sentinel-2 bands; 20 output columns; score classes 1–18, ignore ground truth 0 and 19
Test-time augmentation None in this scored recipe
Original self-supervised pool 496 fold-5 patches; external TESSERA has its own different pretraining data

See fresh STCLN audit and fixed ordered IDs.

Code map

File / function Purpose
code/foundation_transfer.py:prepare Band/date/padding adapter, without changing supervised samples or spatial crops
code/foundation_transfer.py:optical_features Frozen optical inference, chunks of 512 pixels, CUDA FP16
code/foundation_transfer.py:fit Refit the validation-frozen shared-covariance Gaussian classifier from training caches
code/foundation_transfer.py:predict Gaussian scores and calibrated eighteen-class probabilities
code/foundation_transfer.py:extract Fresh train/validation/test optical inference with original ordered crops
code/foundation_transfer.py:evaluate_cached Replay the exact complete final probability recipe and compare its confusion matrix
code/notebook_ensemble.py:CompleteEnsemble Fresh raw-data predictions from all eight component files, with exact nested probability arithmetic
code/notebook_ensemble.py:evaluate Full fixed-crop validation or full-patch fold-4 evaluation; incomplete smoke runs are marked explicitly
code/original_pretraining_source/ Recovered original pretraining/configuration/dataset/atrous-SRDA sources
code/foundation_transfer.py:verify SHA-256 verification of released encoder/readout
code/tessera_student.py Pinned upstream optical/radar Transformer definitions and checkpoint loader
code/evaluate.py Fresh original four-component reference evaluation; it intentionally still reports the historical reference
code/model.py, temporal_srda.py Original spatial–temporal architecture and segmentation head
code/temporal_cnn.py Original/new temporal CNN and attention control definitions
code/training_feature_clusters.py Collect frozen features, cluster-based predictions and metrics
code/dataset.py, config.py PASTIS paths, exact lists, crops, collation and labels
../ablations/10_plateau_breakthrough/workspace/*.py Preserved original research drivers, queue logic, statistical/spatial/query ablations and independent audit

Reproduction

From the repository root, with PyTorch, NumPy and the existing requirements installed:

export PASTIS_ROOT=/path/to/PASTIS
python main_method/code/foundation_transfer.py verify
python main_method/code/foundation_transfer.py evaluate-cached --check-raw-labels --output /tmp/tsrda-replay
python main_method/code/foundation_transfer.py extract --split val --output /tmp/tessera-val
python main_method/code/foundation_transfer.py extract --split train --output /tmp/tessera-train
python main_method/code/foundation_transfer.py fit --features /tmp/tessera-train/features.npy --labels /tmp/tessera-train/labels.npy --output /tmp/tessera-refit
python main_method/code/foundation_transfer.py extract --split test --output /tmp/tessera-test

evaluate-cached reconstructs the complete 58.6346% system from released probability arrays; it does not regenerate all component predictions. extract performs fresh optical-branch inference and reports its standalone score, not the full ensemble. fit uses the already selected settings and does not tune on test. The complete notebook now generates an explicit component-path manifest and supports fresh inference for all branches using code/notebook_ensemble.py; cached incumbent arrays are not required for that route. Run python main_method/code/notebook_ensemble.py --paths /path/to/ensemble_component_paths.json --split test --output /tmp/tsrda-fresh-test after downloading components and generating the manifest in the notebook. The preserved historical research drivers remain alternative execution records. Those historical drivers record original VM paths and dependency imports; they are execution records, not a turnkey relocated queue. This distinction prevents a cached replay from being misrepresented as fresh end-to-end inference.

Checkpoint directory: 32X32_tessera_transfer_seed3407. Provenance, selection and hashes: configuration directory. All old shared checkpoints remain available.

How to read the animation

Step-by-step representation transfer

This is a schematic explanation of data flow, fitting and validation selection, not recorded optimizer training or an animation of observed predictions. The encoder stays frozen throughout.

Runtime and verification

The recorded transfer pilot took 300.34 seconds (~5.01 minutes) for its queue using cached incumbent probabilities, excluding model download, implementation and independent audit. This is not the cost of reproducing all historical component training or uncached full ensemble inference. GPU smoke test: 512 pixels in 0.277 seconds, peak allocated 0.252 GB for that small test only.

The independent audit checked every raw fold-4 annotation, identical confusion matrices, source/protected hashes, train-only feature normalization, exact ordered sample lists and frozen-before-test promotion. The best test score was selected by validation ranking within the final transfer pilot.

Supporting research and attribution

The bundled upstream model card states that the paper's reported student benchmarks use a different teacher release; they are not expected scores for this checkpoint. Our PASTIS scores are measured locally. The external model card declares CC0; original authors and provenance are retained.

Historical original-checkpoint fine-tuning implementation

The following preserved explanation describes the 8 October system (49.4555% test). Its “final” and “recommended” wording is historical; the current result above supersedes it. It remains useful for understanding every component retained in the incumbent.


Main method — from pretrained checkpoint to final crop mapping

An implementation-level explanation of pretraining, supervised fine-tuning, SAM refinement, feature-cluster classification, independent temporal CNNs, and final inference.

The final recommended result is 52.5640% validation mIoU and 49.4555% Test mIoU. The highest observed test alternative reaches 49.5298%, with lower validation. Both use seed-3407 components, the same labeled patch lists, and two fixed 32×32 training/validation crops.

How to understand the method: your supplied checkpoint initializes the spatial–temporal encoder. We fine-tune that encoder inside a supervised segmentation model, continue its optimization with SAM = Sharpness-Aware Minimization, fit a classifier on its frozen earlier features, and train small temporal CNNs separately. The final system averages their class probabilities. SAM is an optimizer, not Segment Anything. The added CNNs are independent predictors, not layers inserted into the pretrained backbone.

Configuration Validation mIoU Test mIoU Interpretation
32X32_recommended_validation_seed3407 52.5640% 49.4555% Recommended using validation selection
32X32_highest_observed_test_seed3407 51.8368% 49.5298% Separately retained highest observed test alternative

This guide explains the winning lineage, rather than suggesting that every research experiment contributed to it. FINAL_REPORT.md retains the complete experiment history, per-class results, benchmark audit, and unsuccessful alternatives.

Navigate the explanation

  1. Detailed architecture and animated walkthrough
  2. The data contract and tensor shapes
  3. Stage 1 — original self-supervised pretraining
  4. Stage 2 — transfer to supervised segmentation
  5. Inside the spatial–temporal encoder
  6. Inside the supervised pooling, heads and refinement
  7. Losses, augmentations and ordinary fine-tuning
  8. Stage 3 — low-LR continuation and SAM
  9. Stage 4 — training-feature cluster readout
  10. Stage 5 — independent temporal CNNs
  11. Stage 6 — final probability fusion and evaluation
  12. Results, ownership and code map
  13. Benchmark interpretation and reproducibility
  14. Files and executable commands

Detailed architecture and animated walkthrough

The architecture sheet shows checkpoint transfer, tensor shapes, the spatial and temporal encoder, the supervised heads, boundary-gated refinement, the SAM update, separately trained predictors, and exact inference weights.

Detailed checkpoint-to-final-model architecture

Open the full-resolution PNG · Download the scalable SVG

The 72-second, twenty-scene animated walkthrough follows a training input through pretraining, checkpoint loading, fixed cropping, augmentations, forward propagation, loss computation, backpropagation, the two SAM passes, feature-cluster fitting, CNN training, and test inference. The moving highlights explain the order of operations.

In-depth animation of the actual fine-tuning procedure

Animation scope: this is a code-drawn explanation, not a screen recording, measured attention visualization, or simulated learning curve. Its reported scores are historical measurements. It does not claim we reran training to create the GIF. Read the scene-by-scene transcript or view the complete static storyboard.

The data contract and tensor shapes

PASTIS provides a time series of Sentinel-2 images for each geographic patch. A pixel represents the same location across observations. Crop identification depends on both surrounding spatial context and how spectral measurements change through time.

Quantity Meaning / implemented shape
B Number of patches in a batch; 2 during supervised training
T Number of observations; variable across patches
C Ten spectral input bands
H,W 32×32 for fixed training/validation crops; 128×128 for test
Input x (B,T,10,H,W)
Positions pos (B,T) observation indices; padded positions are zero
Semantic target y (B,H,W); semantic annotation channel 0
Encoder output (B,H,W,T,256)
Pooled spatial feature map (B,256,H,W)
Main/refined semantic logits (B,20,H,W)
Boundary logits (B,1,H,W)
CNN logits (B,18,H,W); mapped to labels 1–18 during fusion

PASTISPatchDataset.__getitem__() loads S2_<patch_id>.npy, converts to float32, normalizes the ten bands, and loads TARGET_<patch_id>.npy[0] for supervised stages. It returns both observation positions and actual acquisition-day offsets. The winning model uses observation indices, not actual day offsets, because USE_INDEX_POSITIONS=True in config.py.

pad_collate() pads time series to the longest sequence in the batch. crop_ij() performs the spatial slicing. The supervised fixed windows are:

# Native input: 128×128; grid=4; each tile: 32×32
crop_ij(x, y, 0, 0, grid=4)  # rows0:32, columns0:32
crop_ij(x, y, 1, 1, grid=4)  # rows32:64, columns32:64

These are the first two diagonal tiles of the 4×4 grid, not the upper-left and lower-right corners of the full patch. The trainer performs one optimizer update per crop batch, giving 38 patch batches × 2 crops = 76 updates/epoch.

Stage Patch pool Geometry Batch / update schedule
Original SSL pretraining recipe 496 unique fold-5 patches All sixteen fixed32 tiles Batch4; 124 batches ×16 =1,984 updates/epoch
Supervised training Exact fold-1 list:76 entries /72 unique Two fixed32 diagonal tiles Batch2;76 updates/epoch
Validation Exact fold-2 list:76 entries /71 unique Same two fixed32 tiles No random training transforms
Test All482 unique fold-4 patches Full128×128 patch Batch1; no TTA

The repeated supervised IDs are preserved to retain the reference sample weighting. All four patch pools are disjoint. The final components use seed value 3407; seed42/1234 research models are not constituents of either released final configuration.

Stage 1 — original self-supervised pretraining

What we inherited

We started the successful fine-tuning track from your supplied checkpoints/pretrain/latest.utae.tar, an encoder-only artifact recording epoch99. The supplied full latest.tar also records seed3407 and training state. We preserved the original pretrained folder unchanged.

The description below is grounded in the original pretraining source, its configuration, and the reconstruction wrapper. It describes the available source recipe; checkpoint metadata alone does not certify every detail of the historical execution. We did not recreate the original100-epoch pretraining during this documentation update. A separate supplied checkpoint_99.tar was inspected, but no completed parallel comparison from that artifact contributes to this final result.

Task: reconstruct missing spectral information

The pretraining graph is UTAEPrediction(UTAE_ASPP(...)). Its encoder is shared in design with downstream segmentation; its output layers are specific to reconstruction.

In UTAEPrediction.forward():

  1. Copy the original normalized input to target.

  2. Calculate an NDVI-style indicator from normalized band indices6 and2:

    ndvi = (x[:, :, 6] - x[:, :, 2]) / (x[:, :, 2] + x[:, :, 6] + 1e-20)
    cluster = (ndvi > 0.2).float()
    frame_veg = cluster.mean(dim=[2, 3])
    
  3. Draw a spatial dropout mask, with nominal probability0.4. The same pixel mask is repeated across all ten channels.

  4. Exempt whole frames when frame_veg <= 0.9. Only frames above that threshold retain the random masking.

  5. Replace hidden values with a trainable scalar mask_token.

  6. Run the corrupted sequence through the spatial–temporal encoder.

  7. Use linear:256→10 to reconstruct spectral values at each pixel and time.

This ratio is computed on normalized inputs, so it should not be interpreted as a standard physical NDVI calculated from raw reflectance. The eligibility decision is per frame, not a per-pixel vegetation filter. A nominal40% mask therefore does not mean40% of all training values are hidden. Controlled pilot measurements found roughly3% effective masked coverage; the exact fraction varies by sample and masking draw.

The pretraining loop computes MSE only where the visibility mask is zero:

recon, recon2, target, visible_mask = network(xc, pos)
hidden = 1.0 - visible_mask
loss = ((recon - target).square() * hidden).sum() / (hidden.sum() + 1e-8)

Deep reconstruction supervision is optional and disabled in the supplied source configuration: DEEP_SUP=False. The wrapper constructs midlinear and returns recon2, but the historical configured objective does not add its MSE term. This distinguishes an available code path from an active loss.

The declared original schedule is100 epochs, AdamW LR1e-4, betas(0.9,0.95), weight decay0, FP16/GradScaler, and gradient clipping5. Historical records report approximately43 L4 hours; that is an archived runtime, not a new measurement.

Why there are two checkpoint forms

pretrain.py: main() saves:

  • latest.tar: full reconstruction wrapper, optimizer, scaler, RNG state, epoch and seed; useful for resuming pretraining.
  • latest.utae.tar: encoder weights and epoch; useful for transferring the representation to segmentation.

The reconstruction output heads and scalar mask token are not used by the final segmentation inference graph. The learned encoder weights are the transferable part.

Stage 2 — transfer to supervised segmentation

train_spatial_temporal.py: main() constructs the encoder and strictly loads the pretrained state. If given a full reconstruction checkpoint, it extracts keys beginning with utae. and removes that prefix:

encoder = UTAE_ASPP(n_channels=10, d_model=256, n_heads=8, ...)
state = checkpoint['model_state_dict']
# Full reconstruction state → encoder-only state when necessary.
encoder.load_state_dict(state, strict=True)
network = UTAEClassificationDual(encoder, d_model=256, num_classes=20)

At the initial supervised transfer, the encoder starts from pretraining and the supervised task layers are newly initialized. The encoder is not frozen in the winning training lineage. Both its spatial/temporal weights and the supervised layers adapt using labeled crop targets.

At a later continuation, --init_finetuned loads the entire selected supervised model_state_dict, overwriting the initially constructed encoder and task layers. The continuation keeps their learned weights while starting a new optimizer/schedule. It is therefore important to distinguish transferring a bare encoder from continuing an already fine-tuned segmentation model.

Inside the spatial–temporal encoder

Spatial representation: AtrousSpatialEncoder, ASPP, SEBlock

AtrousSpatialEncoder.forward() processes every acquisition as an image, using (B·T,10,H,W) as its input:

  1. A3×3 convolution maps10 bands to64 channels, followed by BatchNorm/ReLU.
  2. Another3×3 convolution uses dilation2, retaining64 channels and the same resolution.
  3. ASPP processes those features through three3×3 branches with dilation1/2/4 and a global-average-pooling branch. Each branch produces256 channels; concatenation and a1×1 projection combine them into256 channels.
  4. SEBlock learns channel weights from pooled features and multiplies them into the feature map.

No spatial downsampling occurs here. This preserves small-field and boundary detail, although receptive-field size and global pooling still affect the features. The spatial CNN is already part of your original encoder; it should not be confused with the independently trained temporal CNNs added later.

Temporal representation: UTAE_ASPP, TemporalSRDAEncoder, TemporalSRDABlock

UTAE_ASPP.forward() reshapes spatial features into (B·H·W,T,256), so each geographic pixel becomes a temporal feature sequence. PositionalEncoder.forward() generates sinusoidal embeddings from the supplied observation indices. Despite source comments mentioning days, actual winning inputs are index positions.

TemporalSRDAEncoder.forward() adds these embeddings before attention, pads T to a multiple of4, applies three blocks with R_schedule=[4,4,4], and trims its extra padding afterward.

Detailed temporal reduction and dual-attention block

Full-resolution block PNG · Scalable block SVG

Inside each TemporalSRDABlock.forward():

Operation Implemented purpose
norm_kv → pw Project256 channels to64 channels at each timestep
Temporal reshape Group four consecutive64-dimensional vectors into one256-dimensional token; obtainT/4 tokens
norm_first → first_sa Self-attention among the reduced tokens, then a residual addition
norm_q → q_proj Form queries at every original temporal position
kv_proj Form keys/values from the self-checked reduced tokens
Full-query/reduced-KV attention Each original timestep attends to the global reduced temporal sequence; eight heads
out_proj and residual Return the attention result to the full-length feature sequence
norm_mlp → fc1 → fc2 Expand256→1024, apply convolution-enhanced nonlinearity, project1024→256, add another residual

The MLP uses the exact parallel formula:

u = self.fc1(self.norm_mlp(x))
y = F.gelu(u) + self.dw(u.transpose(1, 2)).transpose(1, 2)
x = x + self.fc2(y)

The depthwise temporal convolution receives u, not GELU(u). A historical masking ablation changed this formula and was confounded; the final main model retains the original arithmetic.

The winning main encoder and STA preserve their historical attention-over-padding behavior. Later explicit-mask backbone variants were research ablations, not deployed replacements. Conversely, the temporal CNNs and feature-summary collector explicitly exclude padded observations where appropriate. Legacy windows, shifts, and T_PAD fields are accepted for constructor compatibility; they do not activate Swin-style windows.

UTAE_ASPP chunks long pixel sequences and uses activation checkpointing during training to manage GPU memory. Evaluation also chunks computation. This is distinct from saving a model checkpoint: activation checkpointing recomputes intermediate activations during backpropagation rather than storing all of them.

Inside the supervised pooling, heads and refinement

UTAEClassificationDual.forward() calls the encoder, aggregates time, and calculates three outputs:

sequence, _ = self.utae(x, pos)
feat = self.sta(sequence)
sem = self.sem_head(feat)
bnd = self.bnd_head(feat)
refined = self.refine(feat, sem, bnd)

STA.forward() learns one score per temporal feature vector, applies softmax over time, and takes a weighted sum. It converts (B,H,W,T,256) into (B,256,H,W). Two3×3 convolution layers form a residual spatial refinement, followed by a1×1 convolution.

SemanticDecoder.forward() maps256→128 with a3×3 convolution/BatchNorm/ReLU, then128→20 with a1×1 convolution. These are class logits, not probabilities yet.

BoundaryDecoder.forward() maps256→64→1 to predict a boundary logit at each pixel.

GatedRefinement.forward() uses that boundary prediction inside the final semantic calculation:

gate = torch.sigmoid(bnd_logits)
fused = torch.cat([feat * (1.0 + gate), sem_logits], dim=1)
refined_logits = sem_logits + self.fuse(fused)

The concatenated tensor has276 channels:256 feature channels plus20 semantic channels. A276→128→20 convolutional branch predicts a residual semantic correction.

The boundary branch has two roles: auxiliary boundary supervision during training and a learned gate in refined inference. It is not merely a discarded training head; however, there is no external boundary-snapping post-processing stage. The refined logits, rather than the initial semantic logits, produce the main network's deployed probabilities.

Losses, augmentations and ordinary fine-tuning

Exact supervised loss

The nested training_loss() in train_spatial_temporal.py computes:

loss = (
    CE(sem_logits, target) + 0.75 * Lovasz(sem_logits, target)
    + CE(refined_logits, target) + 0.75 * Lovasz(refined_logits, target)
    + 0.5 * BCEWithLogits(boundary_logits, boundary_target)
)

CE supervises pixel class identity; Lovász-Softmax encourages region overlap; BCE encourages local label-transition prediction. LovaszSoftmaxLoss.forward() masks ignored targets before calculating its sorted error surrogate.

The Exp3 correction explicitly selects targets1–18 before label-smoothed CE. Merely assigning zero class weights to0/19 was insufficient to express the intended ignored-pixel behavior with smoothing. Foreground classes use uniform weights; inverse-frequency weighting was an unsuccessful earlier experiment and is not deployed.

compute_boundary_target() constructs a morphological label gradient: compare local3×3 maximum/minimum class IDs; differing values mark a boundary. Its BCE term does not apply the CE/Lovász foreground mask, so its target semantics are not identical to the eighteen-class segmentation supervision.

Transformations and updates

The main training loop applies spatial dihedral transformations to both imagery and labels, temporal subsampling/frame dropout, and spectral gain/bias/noise perturbations. The corresponding functions are aug_dihedral(), aug_temporal_subsample(), aug_frame_dropout(), aug_spectral(); matching implementations remain in the spatial–temporal trainer.

build_param_groups() separates pretrained encoder parameters from new task layers and separates decay/no-decay groups. Biases and one-dimensional normalization parameters receive no weight decay. A typical fresh research fine-tune uses head LR1e-4, encoder multiplier0.5, weight decay0.02, label smoothing0.05, three-epoch warmup/cosine decay, FP16, and gradient clipping5. Continuation stages use lower LRs; these typical settings are not a claim that every experiment used one schedule.

ModelEMA.update() maintains an exponential moving average copy. validate() evaluates fixed32 crops with refined predictions. pack_checkpoint() records metrics/seed/epoch, and the training loop retains raw and EMA best states plus full resume state. The final SAM network uses selected raw weights, not an EMA or SWA averaged checkpoint.

Stage 3 — low-LR continuation and SAM

The original supplied encoder first passed through supervised fixed32 fine-tuning. The selected Exp3 checkpoint reached49.1003% validation /46.4743% test. A low-LR continuation reached49.3545% /46.7071%. The recorded initialization for SAM is the raw low-LR checkpoint with stored epoch17 at:

ablations/01_finetuning_checkpoint_history/finetune_v2/32X32_exp3_low_lr_refinement/model_best_raw.tar

The historical folder label is retained for provenance. It is not a new main-method version.

SAM then continued that complete fine-tuned model, using a fresh optimizer/schedule. It did not attach another encoder or replace the temporal blocks.

Exact two-pass update in our implementation

There is no separate class SAM in the portable trainer. The implementation is the args.research == 'sam' branch inside main():

# Conceptual transcription; actual code includes GradScaler and overflow handling.
loss = training_loss(x, pos, y, boundary)
loss.backward()
g_norm = norm_of_all_parameter_gradients()
offsets = [0.02 * p.grad / (g_norm + 1e-12) for p in parameters]
add_offsets_to_weights(offsets)
optimizer.zero_grad()

# BatchNorm modules temporarily use eval mode on the second pass.
second_loss = training_loss(x, pos, y, boundary)
second_loss.backward()
subtract_offsets_from_weights(offsets)
clip_grad_norm_(parameters, 5.0)
optimizer.step()  # second-pass gradient applied at restored weights

The actual code divides scaled gradients by the GradScaler scale when calculating the norm/offsets. It handles nonfinite first-pass gradients and restores perturbed parameters and BatchNorm modes in a finally block. BatchNorm evaluation on the second pass uses its running statistics; this implementation detail is part of the recorded run, not interchangeable with every SAM variant.

SAM's motivation is to seek parameters less sensitive to small weight perturbations. Its benefit is empirical rather than guaranteed. Training needs approximately two forward/backward passes per crop update. Once the checkpoint is saved, inference uses one ordinary network forward pass; no perturbation is performed.

Recorded SAM setting Value
Initialization Full selected low-LR Exp3 model
Head / encoder LR 1e-5 /5e-6
Perturbation radius 0.02
Epoch budget 20
Warmup / early stopping 0 /disabled (patience=0)
Selected state Raw epoch11; stored epoch index10
Validation /test mIoU 50.0067% /47.5001%

Its released file is sam_network_seed3407.tar. The replay command is preserved below.

Stage 4 — training-feature cluster readout

The prototype (three training-feature cluster centres per crop class) readout provides an alternative classification rule using the selected SAM encoder. It is not another full network and does not update that encoder.

Features and fitting

DepthCollector registers forward hooks on temporal blocks. begin() prepares valid-observation masks, hook() accumulates temporal summaries for each computational chunk, and end() assembles them back into pixel order. The selected readout uses block1, represented by depth index0:

Per-pixel block1 sequence: T×256
       ↓ exclude padded observations for summary statistics
Temporal mean256 + temporal standard deviation256
       ↓ concatenate
512-dimensional pixel descriptor
       ↓ training-fitted standardization, then L2 normalization
Descriptor used for feature-cluster similarity

train_normalizer() fits descriptor mean/std using training features; std has a0.05 floor. This descriptor normalization is separate from spectral-input normalization in the dataset.

make_prototypes() draws 32 pixels per supporting training patch per class, with replacement when there are fewer than32. It ignores repeated (patch,crop) occurrences for the memory bank; this deduplication does not alter the supervised training lists. It fits class-specific KMeans with n_clusters=3, n_init=3, seed3407, and L2-normalizes the resulting centres.

The bank has shape (18,3,512):54 numerical feature centres. Multiple centres accommodate variation within each class's feature distribution. They are not handpicked RGB examples or segmentation prompts. The readout's training source and complete validation search are in train_feature_clusters.py.

Prediction and first blend

probability() standardizes and normalizes each descriptor, calculates dot-product similarity to the centres, divides by temperature0.1, and combines the three similarities per class with logsumexp - log(3). Softmax produces eighteen foreground probabilities, inserted into channels1–18 of a twenty-channel tensor.

The fitted centres use training labels only. Validation selects the readout family and blend; test labels are not used to fit the centres. The chosen component is stored in training_feature_cluster_centres_seed3407.tar.

P_feature = 0.5 * P_SAM + 0.5 * P_clusters

This reached50.6988% validation /48.0370% test. The same representation can support different mistakes under a trained segmentation head and a cluster-similarity readout, explaining why the blend was worth testing. The observed gain is not proof of statistically significant improvement under every resampling or seed.

Stage 5 — independent temporal CNNs

Original temporal CNN

TemporalCNN.forward() treats each pixel as a ten-band time series. It does not explicitly access neighboring pixel locations. It is trained from scratch, not initialized with your spatial–temporal checkpoint.

Operation Shape / role
Flatten geographic pixels (B,T,10,H,W) → (B·H·W,T,10)
input:Linear(10,64) Project each observation to64 channels
Four residual temporal blocks LayerNorm; depthwise Conv1D kernel3 with dilation1/2/4/8; GELU; Linear64→64
Valid-observation mask Mask padded features after the projection and each residual block
Masked mean and maximum Two64-dimensional summaries; concatenate to128
head Linear128→64; GELU; Linear64→18

The residual update is z = (z + mix(GELU(conv(norm(z))))) * valid_mask, with transposes around Conv1D. valid_from_index_positions() recognizes positive positions and the initial valid zero position; this convention is specific to our index-position data and is not a general calendar-date mask.

This CNN has28,306 parameters. Its spatial independence creates a different inductive bias from the main encoder. It can contribute temporal evidence even when its standalone score is lower.

The recorded recipe uses100 epochs, AdamW LR1e-3/WD0.01, foreground CE smoothing0.05, three-epoch warmup/cosine with minimum LR ratio0.01, FP16, clipping1, existing augmentations, batch2, and76 crop updates/epoch. The original CNN alone scored42.6174% test. Its addition produced:

P_reference = 0.75 * P_feature + 0.25 * P_original_CNN

The reference combination scored51.7691% validation /49.2382% test.

New plain-CNN control

The new control has the same architecture as the original CNN, with a separate training run and distinct final weights. Both use seed value3407. The newer trainer resets Torch/Python RNGs after model construction; the older trainer consumes randomness differently. Same numerical seed therefore does not imply an identical sequence of minibatches/transforms or optimization trajectory. We have not isolated reseeding as the sole cause of the gain.

It was a matched control for the attention/Transformer research comparisons: does another independently optimized plain model help as much as an architectural modification? Its standalone result was46.1393% validation /42.6678% test. Its best standalone validation checkpoint was epoch87, and its separately selected addition weight was0.25.

train_temporal_cnn.py: train() handles the model construction, post-construction RNG reset, fixed crop/augmentation loop, CE, scheduled AdamW update, validation, and best/latest checkpoint saving. target_for() maps labels1–18 to0–17 and other labels to the CE ignore value. It preserves the same labeled sample schedule.

Attention-pooling alternative

AttentionCNN.forward() retains the input projection and convolution blocks but replaces mean pooling with a learned Linear(64,1) score followed by masked temporal softmax and weighted feature sum. Maximum pooling is retained. It adds65 parameters, for a total of28,371.

The attention alternative uses a0.1 addition weight and achieves the highest observed test score. It is not a Transformer decoder, not Segment Anything attention, and not evidence that every attention model outperforms its plain control. Its validation score is lower than the recommended configuration.

Stage 6 — final probability fusion and evaluation

evaluate.py: load_models() reads the configuration manifest, verifies checkpoint SHA-256 hashes by default, strictly loads the component states, and places them in evaluation mode. main() performs inference, shared-feature collection, probability fusion, argmax, and confusion-matrix accumulation.

Recommended configuration

The sequential blend is:

P_feature   = 0.5 * P_SAM + 0.5 * P_clusters
P_reference = 0.75 * P_feature + 0.25 * P_original_CNN
P_final     = 0.75 * P_reference + 0.25 * P_new_CNN
prediction  = P_final.argmax(dim=1)

Its expanded weights are:

Probability source Final weight Trained how?
SAM-refined spatial–temporal network 0.28125 Your pretrained encoder → supervised training → low-LR → SAM
Training-feature cluster readout 0.28125 Fit training-feature centres with the selected encoder frozen
Original temporal CNN 0.18750 Independent supervised training from scratch
New temporal CNN control 0.25000 Separate matched supervised training from scratch

There are three neural networks plus one shared-encoder readout, not four independent large encoders. The collector obtains the readout features during the main network's forward pass.

Highest observed test alternative

P_alternative = 0.9 * P_reference + 0.1 * P_attention_CNN

Expanded weights are0.3375 SAM +0.3375 clusters +0.225 original CNN +0.1 attention CNN. It replaces the new plain-CNN addition; it does not use all three CNNs at once.

We average softmax class probabilities, not logits or checkpoint weights. The eighteen-class CNN/readout probabilities occupy channels1–18; their channels0/19 are zero. Main-network probabilities keep all twenty channels. That mapping is a deliberate part of the recorded arithmetic.

Test scoring

Test uses482 full128×128 fold-4 patches with batch1. Training/validation uses32 crops; inference is not restricted to those windows because the model supports variable spatial dimensions.

The evaluator counts valid ground-truth pixels1–18 into a full20×20 confusion matrix. Predictions into0/19 on a valid crop pixel remain errors. metrics_cm() averages IoU across eighteen foreground classes and records macro-F1, pixel accuracy, kappa and per-class IoU. It does not discard those mistaken prediction columns.

No inference-time training, pseudo-label fitting, TTA, DenseCRF, morphology, connected-component filtering, or external boundary snapping contributes to the released result.

Results, ownership and code map

Observed progression

Stage What changed Validation mIoU Test mIoU
Fixed32 Exp3 Explicit invalid-target masking in label-smoothed CE 49.1003% 46.4743%
Low-LR continuation Further optimization of the supervised model 49.3545% 46.7071%
SAM network Two-pass sharpness-aware optimizer refinement 50.0067% 47.5001%
Add feature-cluster readout Earlier frozen features classified through class clusters 50.6988% 48.0370%
Add original temporal CNN Independent per-pixel spectral/time predictor 51.7691% 49.2382%
Add new CNN control Another separately trained predictor; validation-selected blend 52.5640% 49.4555%
Reference + attention CNN Alternative final addition; lower validation 51.8368% 49.5298%

The recommended system has test pixel accuracy81.0927%, macro-F162.3414%, and kappa0.7643. From the SAM network to the recommended final system, test mIoU increases by1.9554 percentage points. These are measured results for the recorded configurations, not promised gains on another run.

Which weights came from where?

Component Inherited original pretraining? Supervised gradient updates? Final inference role
Spatial encoder + T-SRDA blocks Yes Yes, through the winning continuation chain Main features and cluster-source features
Reconstruction heads / mask token Pretraining-task parameters Not in supervised inference graph None
STA + semantic/boundary/refinement heads Newly initialized at first supervised transfer Yes; retained through later continuation Refined main-network probabilities
SAM optimizer An update rule, not weights/layers Two-pass gradients for the main network No extra SAM inference operation
Feature-cluster centres Derived from fine-tuned pretrained features Fitted by KMeans; encoder frozen Alternative class probabilities
Original/new temporal CNNs No Yes, separately from scratch Complementary temporal probabilities
Attention-pooling CNN No Yes, separately from scratch Alternative final predictor

Function-by-function reading guide

File / symbol What to look for
config.py Exact IDs, seed, class names, crop coordinates, encoder dimensions; do not infer research trainer arguments solely from legacy defaults
dataset.py: PASTISPatchDataset, pad_collate, crop_ij Files → normalized observations/labels → batch padding → fixed crops
Original pretrain.py: main Sixteen crop updates; masked MSE; pretraining resume/encoder export
model.py: UTAEPrediction.forward NDVI-style frame gate, scalar mask token and reconstruction
AtrousSpatialEncoder, ASPP, SEBlock Per-acquisition spatial processing at full resolution
UTAE_ASPP.forward, PositionalEncoder.forward Spatial-to-temporal reshape, supplied-position embedding, chunking/checkpointing
temporal_srda.py: TemporalSRDABlock.forward Reduced KV self-attention, full-query dual attention and parallel convolution MLP
TemporalSRDAEncoder.forward Three blocks and internal temporal padding
model.py: STA.forward Learned temporal pooling and residual spatial refinement
SemanticDecoder, BoundaryDecoder, GatedRefinement Class logits, boundary logits, boundary-gated residual correction
UTAEClassificationDual.forward Complete supervised forward graph and returned dictionary
compute_boundary_target Local max/min gradient on label IDs
losses.py: LovaszSoftmaxLoss.forward Ignored-target handling and overlap-loss calculation
train_spatial_temporal.py: build_param_groups, training_loss Encoder/head LRs and combined supervised objectives
main, SAM branch Temporary weight offsets, second pass, restoration, clipping and update
ModelEMA.update, validate, pack_checkpoint Averaged copy, fixed-window validation and selected checkpoint metadata
train_feature_clusters.py: extract_cache, train_normalizer, make_prototypes, fit_readouts Training descriptors, standardization, balanced cluster fitting and validation search
training_feature_clusters.py: DepthCollector, probability Shared forward hooks and deployed similarity-based classification
temporal_cnn.py: TemporalCNN.forward, AttentionCNN.forward Independent temporal feature pipelines and alternative pooling
train_temporal_cnn.py: target_for, train, validate Label remapping, matched100-epoch training, best/latest states
evaluate.py: load_models, main; metrics_cm in readout module Integrity checks, exact probability fusion, full-patch predictions and corrected metrics

Benchmark interpretation and reproducibility

The downloaded STCLN code matches our exact training/validation ID lists, duplicate multiplicities, folds, crop coordinates, numerical fine-tuning seed and batch geometry. However, the final score is an ensemble result, whereas the main SAM network alone scores47.5001% test.

Matching sampling does not establish identical complete benchmarking. Documented differences include our all-fold normalization versus the inspected reference's fold-selected normalization, padded-position behavior, validation-mIoU versus accuracy checkpoint selection, and confusion-matrix handling. Original paper score/variant provenance also remains qualified. We therefore do not present this README as proof of a fully controlled STCLN paper ranking. See the benchmark audit and full report.

Although test labels did not train the networks or fit cluster centres, test performance was repeatedly inspected during research. The highest observed test alternative should not replace validation-based selection as an unbiased final-selection claim.

The original pretrained folder, final checkpoints, configurations, earlier reports, and training logs remain intact. This update changes documentation and explanatory visuals only. Existing verification.json records strict checkpoint loading, hashes and CPU arithmetic equivalence; it is not a fresh GPU evaluation or training rerun. Further backbone/decoder, contrastive, consistency, distillation, structured-mask pretraining and TTA experiments are recorded in ablations, not silently included in this inference graph.

The figures are reproducible from docs/visual_sources/build_finetuning_visuals.py, using Pillow and DejaVu Sans fonts. No generated imagery is used to claim actual field predictions or measured model attention.

Files

  • code/: portable final evaluation, temporal CNN training, feature-cluster readout training, spatial–temporal training source, core model/data/loss code and prototype (three training-feature cluster centres per crop class) inference.
  • checkpoints/shared/: all five component files, shared across the two configurations. No network access is needed after downloading them.
  • configurations/: exact probability weights, SHA-256 hashes, validation selections and original test confusion matrices.
  • Full report: all results and benchmark qualifications.
  • Complete original training logs/resume states: retained separately to avoid confusing ablations with final inference components.

Evaluate

From repository root, after installing the matching PyTorch/CUDA runtime and requirements.txt:

PASTIS_ROOT=/path/to/PASTIS python main_method/code/evaluate.py --configuration recommended_validation --split val
PASTIS_ROOT=/path/to/PASTIS python main_method/code/evaluate.py --configuration recommended_validation --split test
PASTIS_ROOT=/path/to/PASTIS python main_method/code/evaluate.py --configuration highest_observed_test --split test

Evaluation uses batch2 and the fixed crops for validation; batch1 and full128 patches for test. It retains all prediction columns in the confusion matrix and scores eighteen foreground classes. --configuration both computes both final systems in one pass, sharing encoder/feature-cluster/old-CNN computation. There is no TTA or post-processing. Original all-fold normalization and index-position behavior are intentionally preserved; see the benchmark caveats rather than describing these as identical preprocessing to STCLN.

Replay temporal training

PASTIS_ROOT=/path/to/PASTIS python main_method/code/train_temporal_cnn.py --kind cnn_control --seed 3407 --epochs 100
PASTIS_ROOT=/path/to/PASTIS python main_method/code/train_temporal_cnn.py --kind attention --seed 3407 --epochs 100

Outputs are written to main_method/runs/; original completed runs are retained under ablations/. The spatial–temporal source code/train_spatial_temporal.py retains the original fine-tuning recipe and flags. Its historical multi-stage initialization commands and every intermediate checkpoint are retained in the ablation/archive records; do not treat a fresh single command as a claim to reproduce the entire multi-stage research history.

The organized inference implementation preserves the scored tensor arithmetic and extracted modules. Packaging checks and their actual scope are recorded in verification.json; do not infer a GPU rerun unless it is recorded there.

The source for fitting the prototype (three training-feature cluster centres per crop class) readout is code/train_feature_clusters.py. Its feature extraction and full validation search preserve the historical implementation; outputs are written under main_method/runs/feature_cluster_readouts/. The original cached features and all fitted readouts remain in the corresponding ablation folder.

Replay the recorded SAM refinement

The original winning SAM run starts from the validation-selected low-LR Exp3 checkpoint, which is included in the archive. From repository root:

PASTIS_ROOT=/path/to/PASTIS python main_method/code/train_spatial_temporal.py \
  --pretrain_pth checkpoints/pretrain/latest.utae.tar \
  --init_finetuned ablations/01_finetuning_checkpoint_history/finetune_v2/32X32_exp3_low_lr_refinement/model_best_raw.tar \
  --research sam --seed 3407 --tag 32X32_SAM_refinement \
  --out_dir main_method/runs/32X32_SAM_refinement \
  --epochs 20 --batch 2 --crop_size 32 --fixed_crops --mask_ce_invalid \
  --base_lr 1e-5 --encoder_lr_mult 0.5 --warmup_epochs 0 --patience 0 --resume none

Historical finetune_v2 inside this archived path is the exact original folder name, not a new main-method version label. The active trainer defaults now use descriptive 32X32_SAM_refinement naming, fixed32 geometry and main_method/runs/. These packaging defaults do not alter the recorded training arithmetic. The complete upstream Exp3/refinement logs and resume states remain in ablations.

The self-contained supervisor notebook now displays live epoch/batch progress bars, elapsed time and measured stage ETA throughout pretraining, fine-tuning and evaluation. Progress and usage guide.

Supervisor notebook setup now provisions a compatible training Python independently of the Jupyter kernel. Its first code block reads your PASTIS metadata and selected array headers, verifies every selected ID/file/fold, and calculates actual fold/sample/crop counts and supervised proportions before training. Setup uses standalone uv without system pip/ensurepip.

The supervisor notebook preserves hosted NVIDIA driver paths, supports a CPU-only dataset audit, and provides check_gpu() diagnostics. Neural training still requires CUDA.