Metadata-Version: 2.1
Name: hyso
Version: 0.2.0
Summary: HYSo: PyTorch model engineering, training, evidence analysis and explicit export
Home-page: https://github.com/huseyin-dgn/hyso
Author: Huseyin Dogan
License: MIT
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: Microsoft :: Windows
Requires-Python: <3.13,>=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: THIRD_PARTY_NOTICES.md
Requires-Dist: torch<2.6,>=2.5.1
Requires-Dist: torchvision<0.21,>=0.20.1
Requires-Dist: numpy
Requires-Dist: matplotlib
Requires-Dist: seaborn
Requires-Dist: scikit-learn
Requires-Dist: tqdm
Requires-Dist: torchsummary
Provides-Extra: deployment
Requires-Dist: onnx==1.20.0; extra == "deployment"
Requires-Dist: onnxruntime==1.23.2; extra == "deployment"
Provides-Extra: deployment-cpu
Requires-Dist: onnx==1.20.0; extra == "deployment-cpu"
Requires-Dist: onnxruntime==1.23.2; extra == "deployment-cpu"
Provides-Extra: deployment-gpu
Requires-Dist: onnx==1.20.0; extra == "deployment-gpu"
Requires-Dist: onnxruntime-gpu==1.23.2; (platform_system == "Windows" or platform_system == "Linux") and extra == "deployment-gpu"
Provides-Extra: tensorrt
Requires-Dist: onnx==1.20.0; extra == "tensorrt"
Requires-Dist: tensorrt-cu12==10.13.3.9; (platform_system == "Windows" or platform_system == "Linux") and extra == "tensorrt"
Provides-Extra: onnx-dynamo
Requires-Dist: onnx==1.20.0; extra == "onnx-dynamo"
Requires-Dist: onnxscript==0.5.6; extra == "onnx-dynamo"
Provides-Extra: precision
Requires-Dist: onnx==1.20.0; extra == "precision"
Requires-Dist: onnxruntime==1.23.2; extra == "precision"

# HYSo

HYSo is a Python-first PyTorch CNN engineering, training, evaluation, benchmarking and performance analysis framework.

The [central offline user guide](hyso/data/user-guide.html) contains Türkçe,
English, Deutsch and Español in one HTML file, with local search and stable topic
links. It is included in the wheel: run `hyso-guide --open`, or
`hyso-guide --language de --topic analysis.p23` to print a direct topic link.
The guide reader needs neither Torch imports nor a server or internet connection.

Use the Python API or the installed `hyso` terminal interface. The web product
has been retired; no browser, HTTP server or frontend dependency is required.
Start with the [Python engineering workflow](docs/guides/python-first-workflow.md)
and [runnable CPU example](examples/models/python_first.py).

For explicit local PNG/JPEG datasets, see the [file-backed classification guide](docs/guides/file-image-classification.md)
and [short CPU training/evaluation example](examples/models/image_classification.py).

## Installation and imports

The release dependency profile is Python 3.10–3.12, Torch 2.5.1 and torchvision
0.20.1. Actual release checks cover Windows x64/Python 3.10; other combinations
are not certified. Choose the CPU or CUDA distribution explicitly in a new environment:

```console
python -m venv .venv
.venv\Scripts\python -m pip install torch==2.5.1 torchvision==0.20.1 --index-url https://download.pytorch.org/whl/cpu
.venv\Scripts\python -m pip install dist/hyso-0.2.0-py3-none-any.whl
```

For CUDA 12.1, use a separate environment and the `cu121` index in the
[installation and dependency guide](docs/guides/first-release.md). Developer
acceptance runners are not part of normal installation. For source development
only: `python -m pip install -e .`. After installing a built distribution, run
`python -m hyso --help` from outside the checkout. Wheel/sdist use the commercial
allowlist; repository examples and other guides are source-checkout files, while
the central offline guide is installed as package data. Historical CPU acceptance and its exact limits are recorded in the
[acceptance guide](docs/guides/python-first-acceptance-and-limits.md#cpu-beta-installation).
Optional `hyso[deployment-cpu]` supplies ONNX/ONNX Runtime for the explicit
export API. Choose `deployment-gpu` in a separate environment; never combine the
CPU and GPU ONNX Runtime distributions. TensorRT is experimental and unvalidated.
See [model export](docs/guides/model-export.md), [release notes](RELEASE_NOTES.md)
and [changelog](CHANGELOG.md) for scope and compatibility.

## Terminal interface

```console
hyso --help
python -m hyso --help
hyso models list
hyso analysis list --json
hyso analysis plan --features P01 P02 P11
```

Command groups: `models`, `train`, `analysis`, `experiments`, `compare`, `advisor`,
`reports`, `export`. Training and analysis default to dry-run. Execution requires explicit
authorization and separate permissions for training, CUDA, camera, sensors and
long runs. Retained reports and comparisons never start new measurements.
See the [CLI guide](docs/guides/cli.md) and [working offline examples](examples/cli/README.md)
for source/factory contracts, exit codes, JSON output and no-clobber exports.

The development source checkout's M3 adds configurable ResNet, PreActResNet, WideResNet, ResNeXt and DenseNet
families, residual blocks and SimAM/Triplet/Selective Kernel attention. See
[model architectures](docs/guides/model-architectures.md) and
[CPU model examples](examples/models/README.md) for exact topology, Builder JSON
and state_dict boundaries. `hyso models show resnet` describes its parameters.
M3/M4 development modules remain excluded from commercial wheel/sdist profiles.

```python
from hyso import ModularCNN, Trainer, BenchmarkRunner, ExperimentManager
from hyso import performance, analysis, advisor
from hyso.models import ConvNormAct, ResidualBlock, SEBlock, CBAMBlock
```

Existing deep imports remain valid and reference the same objects. Legacy
`hyso.models.__all__` deliberately keeps its five-name published wildcard contract;
newer components are available through explicit named imports.

## Build and train a tiny CPU example

Synthetic data demonstrates API usage, not model quality. Supply compatible
finite train/validation loaders and real labels/splits in your application.

```python
import torch
from torch.utils.data import DataLoader, TensorDataset
from hyso import ModularCNN, Trainer

torch.manual_seed(0)
model = ModularCNN(input_channels=1, num_classes=2, widths=(4,),
                   repeats=(1,), strides=(1,), norm=None).to("cpu")
inputs = torch.randn(4, 1, 8, 8)
targets = torch.tensor([0, 1, 0, 1])
loader = DataLoader(TensorDataset(inputs, targets), batch_size=2, shuffle=False)
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
trainer = Trainer(model, optimizer=optimizer, loss_fn=torch.nn.CrossEntropyLoss(),
                  device="cpu", amp=False)
history = trainer.fit(loader, epochs=1)
assert len(history["train_loss"]) == 1
```

Move the model **before** optimizer creation; Trainer does not move it. Model
outputs are logits; history accuracy is a percentage. Use `evaluation_model`
when EMA is enabled. Legacy EBO/CEMO/CNNSENormalWithFit training APIs remain valid.
`save_last_to`/`resume_from` requires the documented ModularCNN or selected Graph
profile, exact model_config and compatible loaders. Two-input/single-output resume uses
explicit names and `hyso.training.NamedTensorDataset`; see the
[CPU Graph workflow and resume examples](docs/guides/python-first-workflow.md#graph-training-and-saved-results).
Raw Graphs also support two explicitly weighted classification losses, including
one- or two-input automatic v2 resume and separate head evaluation on CPU fp32.
The combined two-input/two-head workflow uses explicit names throughout. See the
[multi-head examples](docs/guides/python-first-workflow.md#multi-head-workflow).

## TrainingConfig: separate requested and applied settings

TrainingConfig v1 prepares the existing Trainer; it does not add another training
engine. Model architecture, Dataset and DataLoader objects stay outside its JSON.
The following synthetic train/validation split is only a CPU usage example:

```python
from hyso import TrainingConfig, ModelBuilder

config = TrainingConfig(epochs=1, batch_size=2, optimizer="sgd",
                        learning_rate=0.01, validation=True,
                        scheduler="step", scheduler_params={"step_size": 1, "gamma": 0.9})
training_inputs = torch.randn(8, 1, 8, 8)
training_targets = torch.tensor([0, 1, 0, 1, 0, 1, 0, 1])
train_batches, val_batches = config.make_loaders(
    TensorDataset(training_inputs[:4], training_targets[:4]),
    TensorDataset(training_inputs[4:], training_targets[4:]))
configured_model = ModelBuilder((1, 8, 8), 2).add(
    "conv_norm_act", in_channels=1, out_channels=4, norm=None).build()
session = config.prepare(configured_model, train_batches, val_batches)
print(session.settings()["effective"])
training_result = session.fit()  # Exactly one native Trainer.fit call.
print(training_result.history["val_acc"])  # Percent; not a quality claim.
# config.to_json("training.json")
# config = TrainingConfig.from_json("training.json")
```

`settings()` separates requested, resolved and effective settings, including native
LR values. The v1 profile supports standard SGD/Adam/AdamW; StepLR, cosine,
OneCycle and validation-loss plateau; fp32/fp64 or explicit CUDA amp_fp16;
accumulation, clipping, EMA and validation-dependent early stopping. Default
weight decay is explicitly **0**; OneCycle can change LR at construction and that
change is reported. No implicit device movement, dtype cast or seed is applied.
CPU AMP is rejected. CUDA paths delegate to Trainer and were not exercised here.

Loss/accuracy come from Trainer.history; observer epoch intervals and total fit
wall time are UX timings, not P19/GPU evidence. Automatic save/resume is callback-free:
ModularCNN uses v1 and supported GraphTensorOutput uses v2. BuiltClassifier is
unsupported for that path and checkpoint-mode epoch timings are unavailable. Use
`training_result.log_to(run)` to explicitly record history in an already-started
ExperimentManager training run; manage run lifecycle and `manager.close()` yourself.
See [training configuration](docs/guides/training-config.md) for exact scope.

## Explicit performance analysis and result reading

This three-sample CPU example checks usage only: it does not establish tail
latency, independent statistical evidence or full P01?P35 acceptance.

```python
from hyso import BenchmarkRunner, performance

result = BenchmarkRunner(trainer.evaluation_model, device="cpu",
                         example_input=inputs[:1], warmup_iterations=1,
                         measure_iterations=3, repeats=1).run()
data = result.to_dict()
latency = performance.analyze_latency(result, quantiles=(0.5,))
print(data["configuration"]["measure_iterations"])
print(latency.to_dict()["feature_ids"])
# Explicit optional exports:
# result.to_json("benchmark.json")
# result.to_csv("benchmark-summary.csv")
# result.to_samples_csv("benchmark-samples.csv")
```

CUDA, streaming and long runs require explicit calls and their prerequisites.
Read missing/unsupported metric statuses and reasons; do not replace them with zero.

## Select analyses without executing them

```python
from hyso.analysis import ModelContext, FeaturePlanRequest, plan_features

plan = plan_features(FeaturePlanRequest(
    mode="selected", models=(ModelContext(model_id="my-cnn", input_contract=True),),
    features=("P01", "P11")))
assert plan.execution_authorized is False
assert [item.feature_id for item in plan.features] == ["P01", "P11"]
```

Single/selected/automatic/full planning reports prerequisites; it never executes
or authorizes workloads. The common executor adds explicit selection/preflight
and authorization around the existing producers:

```python
analysis_plan = analysis.plan_analysis(
    ModelContext(model_id="my-cnn", input_contract=True), profile="basic")
analysis_dry_run = analysis.preflight_analysis(
    analysis_plan, (analysis.LiveCPUModel("my-cnn", model, inputs[:1]),))
print(analysis_dry_run.to_dict())  # No forward, training or factory import.
# After reviewing support, reasons, workload counts and resource estimates:
# analysis_result = analysis.execute_analysis(
#     analysis_dry_run, authorized_features=("P01", "P02", "P10", "P11"),
#     explicit_authorization=True)
# index = analysis_result.to_evidence_index()
```

Profiles: basic, inference, training, memory, comparison, full. They select IDs,
not permissions. Trusted CPU execution supports P01, P02, P10 and P11; the existing
Windows Job route supports P02/P11. P10 is one process RSS/HWM snapshot with no
model forward or model-only peak claim. The separate `native` mode connects
P01–P35 through typed operation sources and explicit native resource policies.
Dependencies remain visible as separate selections.
Default P01 requests 1000 measured samples to retain the native tail policy;
a smaller requested budget is never silently increased. A valid but insufficient
capture remains MISSING_PREREQUISITE, with raw samples retained.
See [selective analysis](docs/guides/selective-analysis.md) for exact statuses,
trust/resource limits and report integration. The acceptance runner remains a
separate advanced tool; full selection does not execute or certify all 35 features.
Typed sources, retained CUDA artifacts, training episodes and runnable examples
are documented in the [native executor guide](docs/guides/native-analysis-executor.md).

## Experiments, reports and help

Compare two **existing** reports without running missing tests. Reports must have
records associated with model IDs A/B (or use your own matching IDs):

```python
from hyso import analysis

def compare_saved_models(report_a_path, report_b_path):
    source_a = analysis.ModelComparisonSource(
        "A", analysis.UnifiedAnalysisReport.from_json(report_a_path))
    source_b = analysis.ModelComparisonSource(
        "B", analysis.UnifiedAnalysisReport.from_json(report_b_path))
    return analysis.compare_models(source_a, source_b,
        features=("P01", "P02", "P10", "P11", "P26"), include_structure=True)

# comparison = compare_saved_models("model-a-report.json", "model-b-report.json")
# comparison.to_json("comparison.json")
# comparison.to_markdown("comparison-tr.md", language="tr")
# comparison.to_markdown("comparison-en.md", language="en")
```

Differences are B minus A, with native metric directions and separate quality
percentage points. Missing/ambiguous records or incompatible conditions yield no
numerical difference. General performance comparison requires the existing
producer comparison metadata; ordinary Stage-5 captures may remain insufficient.
Caller labels never repair missing native proof. P26 bound structure comparisons
can expose parameter counts and registered logical sizes separately from P11.
P10 remains process-wide RSS; it is not model-exclusive RAM or P09 VRAM.
No overall winner, statistical superiority or acceptance PASS is inferred.
See [two-model comparison](docs/guides/two-model-comparison.md) for scope and examples.

`ExperimentManager(root_dir)` stores experiments, metrics and artifacts; it does
not schedule training. Use a dedicated non-synced local directory outside OneDrive
and call `close()` in a try/finally block. `EvidenceIndex` and `UnifiedAnalysisReport`
aggregate existing evidence. `advisor.advise(report)` interprets a compatible report
without running a model. Advisor display JSON/Markdown supports English and Turkish.

Review related architecture, training, analysis and comparison runs in one experiment:

```python
def review_experiment(store_dir, experiment_id):
    manager = ExperimentManager(store_dir)
    try:
        history = manager.get_experiment_history(experiment_id)
        details = [manager.get_run_details(run["id"]) for run in history["runs"]]
        return history, details
    finally:
        manager.close()
```

`create_workflow_run()` stores ModelBuilder architectures, TrainingConfig settings,
explicit model/dataset/device/precision/protocol context and existing analysis or
comparison tracking configuration. `run.record_result()` retains an existing result
and input artifact links. `open_result()` checks registered bytes before reading it.
Full result artifacts require schema2 through the existing explicit offline migration.
See [experiment history integration](docs/guides/experiment-workflow.md) for recording,
filtering, reopening, artifact availability and recovery.

Export retained results with shared Turkish/English explanations and embedded charts:

```python
def export_saved_results(output_dir, *saved_results):
    from pathlib import Path
    from hyso.reporting import create_report
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    report = create_report(*saved_results, language="tr", level="technical")
    report.to_json(output_dir / "report.json")
    report.to_markdown(output_dir / "report.md")
    report.to_html(output_dir / "report.html")
    return report
```

Explanation levels are `beginner`, `technical` and `expert`. HTML includes
portable SVG charts when retained numerical data is available. Training,
UnifiedAnalysisReport, model comparison and Advisor results share the presentation
contract. Experiment histories use `report_experiment(manager, experiment_id)`.
See [result reporting](docs/guides/result-reporting.md) and the
[executable reporting examples](examples/README.md).

Explain retained performance evidence with manual, evidence-linked recommendations:

```python
def explain_performance(saved_analysis_path, output_dir):
    from pathlib import Path
    from hyso.analysis import UnifiedAnalysisReport
    from hyso.advisor import recommend
    from hyso.reporting import create_report
    source = UnifiedAnalysisReport.from_json(saved_analysis_path)
    advice = recommend(source)
    output_dir = Path(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    advice.to_json(output_dir / "recommendations.json")
    report = create_report(source, advice, language="tr", level="technical")
    report.to_markdown(output_dir / "advisor.md")
    report.to_html(output_dir / "advisor.html")
    return advice
```

`recommend` also accepts `ModelComparisonResult`, or `EvidenceIndex` with an
explicit `AnalysisContext`. Six areas cover inference, training, memory, model
architecture, deployment and data pipeline. Cards explain the condition, evidence,
manual change/review, rationale, risks, steps and remeasurement. Existing Advisor
rules decide eligibility; coverage prompts never claim a measured bottleneck.
No configuration changes or workloads run. Gain estimates, global winners and
benefit rankings remain unestablished. See the [Performance Advisor guide](docs/guides/performance-advisor.md)
and [executable examples](examples/advisor/README.md).

Use `help(Trainer)`, `help(Trainer.fit)`, `help(TrainingConfig)`, `help(ModularCNN)` and `help(BenchmarkRunner)`
for parameters and return values. `py.typed` enables inline typing discovery;
annotations remain incremental and heterogeneous metadata may use Any. Actual IDE
behavior depends on its selected interpreter. See the [Python API map](docs/guides/python-api.md).

## Implemented versus planned

Model Registry/Builder v1 now exposes a closed catalog of existing components and
a validated linear classifier chain (plus an unchanged ModularCNN profile):

```python
from hyso import ModelRegistry, ModelBuilder

registry = ModelRegistry()
print([spec.name for spec in registry.list("attention")])
print(registry.get("conv_norm_act").to_dict()["parameters"])
builder = (ModelBuilder(input_shape=(1, 8, 8), num_classes=2)
           .add("conv_norm_act", in_channels=1, out_channels=8, norm=None)
           .add("residual", in_channels=8, out_channels=8, norm=None,
                attention={"name": "eca", "params": {"channels": 8}}))
built_model = builder.build()  # Fresh CPU weights; no training or benchmark.
rebuilt = ModelBuilder.from_config(builder.to_config()).build()
# builder.to_json("architecture.json")  # Architecture only; no weights/code.
# rebuilt = ModelBuilder.from_json("architecture.json").build()
```

See the [Registry/Builder guide](docs/guides/model-registry-builder.md) for the
whitelist, parameter/shape contracts, limits and checkpoint compatibility.

Implemented: ELO/CBAM, CEMO/SE, ModularCNN, ECA/Coordinate Attention, Trainer,
checkpoint v1, BenchmarkRunner, measurement APIs, pairwise comparisons,
ExperimentManager, evidence reports and read-only Advisor interpretation.
Explicit ONNX, TorchScript and `torch.export` conversion, ONNX FP16/INT8,
calibration, cohort validation and deployment comparison are available through
`hyso.export`. Analyzer and Advisor preserve the caller's source code, architecture
and weights; explicit ModelBuilder, Trainer and Export calls have their own contracts.

GraphModelBuilder implements validated schema3 DAGs, named inputs/outputs,
branches, skip connections and fusion. The CLI includes the explicit export group.
For single-Tensor training/evaluation/benchmarking, explicitly select a graph
output with `hyso.models.output.GraphTensorOutput`; parameters and autograd are
shared with the original graph. Use `task="multiclass"` or `task="binary"` for
classification training guards. Multi-input dataset/loss orchestration and
regression/embedding training are outside that adapter's supported profile.

`hyso.model_checks` provides explicit bounded CPU smoke/gradient/strict state_dict
checks on isolated weights. Its allocation-free preflight is separate from
execution. `hyso.architecture_comparison.compare_architectures` compares multiple
architecture descriptions; optional exact CPU parameter counting is explicit.
The existing binary `analysis.compare_models` evidence API is unchanged.
See the [component reference](docs/guides/component-engineering-reference.md).

Not implemented: arbitrary model plugins, graphical UI,
OpenVINO/TFLite/CoreML/Edge deployment adapters. TensorRT code is retained as an
experimental, unvalidated optional backend; E03/E04 and dependent native acceptance
remain BLOCKED/NOT_TESTED. Native C++ and AOTInductor are outside the first release.
See the [architecture roadmap](docs/roadmap/hyso-architecture-roadmap-v1.md) and
[performance backlog](docs/roadmap/hyso-performance-backlog-v1.1.md); dated rows are
historical and should be read alongside current code and reports.

## Accepted scope

[Final Model A/B acceptance](docs/reports/p01-p35-final-acceptance-20261112.md)
records 35/35 PASS each within declared scopes. This entry-point work does not
rerun or change it. Model A combines preserved evidence; P30 uses a separate
trained image adapter; P23 Basic excludes extended saved-activation lifetime and
production CUDA saved-activation hooks remain disabled. Acceptance is not a
universal model/hardware/backend/version guarantee.

License: [MIT](LICENSE).

## First release support scope

All 35 analyses are retained. See the [CPU/CUDA support matrix](docs/guides/release-support.md). P23 CPU memory/saved-activation remain supported; CUDA saved-activation is unsupported and blocked by `BLOCKED_B4_UNRESOLVED`. P31 CPU stability and historical 7200-second records remain; new CUDA long runs are deferred. **FULL CUDA ACCEPTANCE is not established.** Normal CUDA training and independent GPU features remain.
