SYNTOLOGY HomeExplorerAtlasCodeMethodologyAboutDevelopersFeedPricing
Paper · 2607.23284 · 2026

StageGuard: Physiologically Constrained Sleep Staging

Yihan Wang, Hao Wu, Dongmian Zou, Juntang Wang, Shixin Xu, Jiayu Gao

arXiv · PDF · Open in the Atlas

Code that ran

4 of 5 samples (functions and classes) lifted from this paper's linked repositories executed on a synthesized input in Syntology's jail (3 of them constructed an object rather than computing a result; 0 honoured the contract we drafted, 0 violated it and 3 have no contract verdict; 1 failure of our instrument; 1 no recorded run), measured 2026-11-23; bodies inline only under a permissive licence as GitHub detects it. Not a reproduction of the paper's results.

"Ran" means the function executed on a synthesized input and returned a value. It is not a reproduction of the paper's results. This record, dated, as JSON: /api/ran/2607.23284.json · badge: /api/ran/2607.23284.svg

Each repository's role is a label: a classifier's output recorded on the link, or, where no role is recorded, what the Papers with Code archive marked. The line under it names its basis. Neither says who wrote the code.

RepositoryRoleRan
Q9gJYx/StageGuard community
Papers with Code archive
4 ran · 1 no recorded run
FunctionStatusWhere it lives
ModalityConfig Ran
ran on a synthesized input · constructed an object; no result was computed
Q9gJYx/StageGuard/stageguard/wrapper.py
code served (permissive licence) · get_code("e78ca13806c08e70")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, ModalityConfig: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import numpy as np
from dataclasses import dataclass, field
from typing import List, Optional, Tuple

torch.manual_seed(0)

ARGS = {
    'stage_names': ['Wake', 'N1', 'N2', 'N3', 'REM'],
    'num_classes': 5,
    'rare_transitions': [(0, 3), (3, 0), (4, 1)],
    'lambda_trans': 1.0,
    'd_max': 30,
    'epsilon': 5.0,
    'gamma': 2.0,
    'k': 5,
    'd_min': [1, 2, 3, 4, 5],
    'sqi_method': 'spectral_entropy',
    'sqi_threshold': 0.5,
    'epoch_sec': 30.0,
    'dataset_name': 'test_dataset',
    'dataset_url': 'https://example.com/dataset',
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, torch, yaml — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type ModalityConfig — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a ModalityConfig output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
SemiMarkovDecoder Ran
ran on a synthesized input · constructed an object; no result was computed
Q9gJYx/StageGuard/stageguard/wrapper.py
code served (permissive licence) · get_code("ad86158698bf070a")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, SemiMarkovDecoder: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import numpy as np
from dataclasses import dataclass, field
from typing import List, Tuple, Optional

@dataclass
class ModalityConfig:
    """Configuration for a sleep-staging modality."""
    stage_names: List[str]
    num_classes: int
    rare_transitions: List[Tuple[int, int]]
    lambda_trans: float = 1.0
    d_max: int = 30
    epsilon: float = 5.0
    gamma: float = 2.0
    k: int = 5
    d_min: List[int] = field(default_factory=list)
    sqi_method: str = 'spectral_entropy'
    sqi_threshold: float = 0.5
    epoch_sec: float = 30.0
    dataset_name: Optional[str] = None
    dataset_url: Optional[str] = None

    def __post_init__(self) -> None:
        if self.num_classes != len(self.stage_names):
            raise ValueError(f'num_classes ({self.num_classes}) != len(stage_names) ({len(self.stage_names)})')
        if self.d_min and len(self.d_min) != self.num_classes:
            raise ValueError(f'len(d_min) ({len(self.d_min)}) != num_classes ({self.num_classes})')
        self.rare_transitions = [tuple(t) for t in self.rare_transitions]


# Create a minimal but valid ModalityConfig
config = ModalityConfig(
    stage_names=['wake', 'n1', 'n2', 'n3'],
    num_classes=4,
    rare_transitions=[(0, 3), (3, 0)],
    lambda_trans=1.0,
    d_max=30,
    epsilon=5.0,
    gamma=2.0,
    k=5,
    d_min=[1, 2, 3, 4],
    sqi_method='spectral_entropy',
    sqi_threshold=0.5,
    epoch_sec=30.0,
    dataset_name='test_dataset',
    dataset_url=None
)

ARGS = {
    'config': config
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
numpy, yaml — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type SemiMarkovDecoder — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a SemiMarkovDecoder output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
SoftTransitionPenalty Ran
ran on a synthesized input · constructed an object; no result was computed
Q9gJYx/StageGuard/stageguard/wrapper.py
code served (permissive licence) · get_code("734aa292ddd03c15")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned an instance of its own class, SoftTransitionPenalty: the run constructed the object and did not call it, so no result was computed. The image it ran in was not recorded. If your copy returns the same type on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
from typing import List, Tuple

torch.manual_seed(0)

# Define rare transitions: list of (from_state, to_state) tuples
# Using small state indices that fit within the number of classes
rare_transitions = [(0, 1), (2, 3), (1, 3)]

ARGS = {
    "rare_transitions": rare_transitions,
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type SoftTransitionPenalty — the run constructed an instance of its own class and did not call it; no shape is stated — the instrument coerces any output to an array; for a SoftTransitionPenalty output the recorded ndim 0 and dtype family float describe that coercion, not the output, and are not stated
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
stageguard_loss Ran
ran; the contract check could not run (RAISES, DEP_MISSING or TIMEOUT)
Q9gJYx/StageGuard/stageguard/wrapper.py
code served (permissive licence) · get_code("a8a75256223e217a")
How it ran

Ran in Syntology's sandbox on this synthesized input (drafted by a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API) and returned tuple, ndim 1, dtype family float; no output shape is stated. The image it ran in was not recorded. If your copy returns the same type and ndim on these inputs, it matched what we observed; nothing here checks that. It does NOT mean the output is correct: nothing has compared it to the paper.

import torch
import torch.nn as nn
import torch.nn.functional as F

torch.manual_seed(0)

# Create tiny test tensors
batch_size = 2
time_steps = 3
num_classes = 4

logits = torch.randn(batch_size, time_steps, num_classes)
targets = torch.randint(0, num_classes, (batch_size, time_steps))

# Define rare transitions - list of (source_class, target_class) tuples
rare_transitions = [(0, 2), (1, 3), (2, 0)]

# Define lambda_trans weight
lambda_trans = 0.5

ARGS = {
    'logits': logits,
    'targets': targets,
    'rare_transitions': rare_transitions,
    'lambda_trans': lambda_trans
}
Setup block drafted by
a language model, Claude Haiku 4.5, prompt python_fixture_v1, through the batch API
Imports
torch — import names as written, not package names to install; a name the repository itself provides is not a package
Returned
type tuple, ndim 1, dtype family float — a tuple output has no array shape of its own; none is stated
dtype family
int means an integer dtype; float means any other dtype the instrument saw, bool and complex included (fixture_check.py records only these two families)
Environment
image not recorded; re-verify against syntology-harvest-sandbox:v5-deps; not recorded for this sample: the harness installs a cuda-to-cpu shim (cuda_shim.py) before every sample and no run records whether a sample needed it; seed: none by the harness; any seed is in the setup block
StageGuardWrapper Not yet run
unverified (harvested, no recorded run)
Q9gJYx/StageGuard/stageguard/wrapper.py
code served (permissive licence) · get_code("e262bcb37712a609")
How it ran

no invocation recorded.

Also present in other papers' code

Of 5 samples lifted from this paper's linked repositories, 5 carry a function identity and 0 do not. Of the 5 distinct functions with an identity, 0 are also present in other papers whose code we hold (0 with at least one paper dated earlier, 0 the same month, 0 later) and 5 are only here among the 52,977 papers whose code Syntology holds (as of 2026-09-26).

Only here means: among the 52,977 papers whose code Syntology holds (51,887 with lifted samples, 1,090 through their assemblies only), as of 2026-09-26, no other paper's lifted samples or current assembly bricks contain an identical function body after normalisation.

Presence, not direction: an identical function body in two papers' repositories does not say who wrote it, which came from which, or that either paper's method rests on it. Matching is exact after normalisation, so a renamed or edited function is not matched. Dates are when papers appeared, not when code was written. Only .py files the harvester lifted are covered; notebooks are not read. A new-style arXiv id YYMM.NNNN dates a paper to the month 20YY-MM; otherwise Paper.year dates it to the year; otherwise it is undated. Dates are when the paper appeared, not when the code was written. Read 2026-11-23.

Repositories linked to this paper

Some links come from the archived Papers with Code dataset (CC BY-SA 4.0): attribution and licence.

Abstract

Automated sleep staging is increasingly used in large-scale studies and downstream scientific analyses to derive sleep-architecture endpoints, including total sleep time, REM latency, sleep efficiency, and bout-duration statistics. Deep learning models achieve epoch-level accuracy approaching inter-rater agreement, yet often produce hypnograms that violate physiological invariants, such as rare state transitions (e.g., direct Wake→REM) or excessively fragmented sequences. Such violations can bias downstream sleep metrics, regardless of overall accuracy. We propose StageGuard, a plug-and-play, backbone-agnostic structured-inference framework that wraps any neural sleep-staging backbone with physiology-informed priors. StageGuard combines (1) a differentiable soft transition penalty that discourages physiologically rare transitions during training, and (2) a semi-Markov constrained decoder with a duration-augmented state space that jointly enforces transition penalties and minimum bout durations at inference. Unlike hard-prohibition methods, it admits rare transitions when emission evidence is overwhelming, leaving informative pathological events recoverable rather than blocked. StageGuard is a reliability-enabling layer rather than a generative model of sleep; it constrains AI staging outputs to satisfy known physiological priors, ensuring downstream scientific analyses are more trustworthy. We quantify the validity gap using transition-violation rate (TVR) and fragmentation index (FI) and demonstrate that, across six backbones and four datasets, Stage-Guard reduces TVR to physiologically plausible levels and lowers FI by 56-62%, while maintaining or slightly improving classification accuracy. Crucially, improved constraint satisfaction translates into 59-79% lower error on derived sleep-architecture statistics that are not directly optimized by the method, and recovers the direction and effect size of expert-defined subgroup differences (OSA severity, age) more faithfully than the unconstrained baseline.

For agents

The same record, over MCP at https://syntology.ai/mcp:

get_harvested_code_for_paper("2607.23284")
get_code_for_paper("2607.23284")
have("2607.23284")

The run record, dated, one paper per request, free:

curl https://syntology.ai/api/ran/2607.23284.json

A badge for a README (the split and the date, never a ratio):

[![Syntology run record](https://syntology.ai/api/ran/2607.23284.svg)](https://syntology.ai/paper/2607.23284)

Connect an agent — have() is free.