ADAM October 2026 source release: PixelRow, INRFlow, Wan Video, Oasis player and field guide
Browse filesUpdate the September 5 source snapshot with current desktop workflows and plugins. Add clean default configuration, fresh screenshots, public architecture map, interactive guide, source ZIP, release notes and validation (322 passing tests across 33 isolated modules). Personal data, credentials, checkpoints, external trainer folders and build outputs are excluded.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+1
- ADAM-source-2026-10-01.zipAdded+3
- ADAM.spec+1
- README.md+591-394
- SHA256SUMS.txtAdded+1
- adam/assets.py+72-20
- adam/auto_training.pyAdded+109
- adam/cnn_reviewer.pyAdded+172
- adam/commands.py+1-1
- adam/config.py+3
- adam/dataset_registry.py+4-3
- adam/generations.py+334-14
- adam/intelligence.pyAdded+200
- adam/job_manager.py+18-3
- adam/model_plugins.py+3-1
- adam/model_plugins_builtin/ddpm/manifest.py+3-1
- adam/model_plugins_builtin/flow_matching/manifest.py+2
- adam/model_plugins_builtin/inrflow/__init__.pyAdded+2
- adam/model_plugins_builtin/inrflow/common.pyAdded+106
- adam/model_plugins_builtin/inrflow/generator.pyAdded+305
- adam/model_plugins_builtin/inrflow/manifest.pyAdded+394
- adam/model_plugins_builtin/inrflow/model.pyAdded+400
- adam/model_plugins_builtin/inrflow/trainer.pyAdded+523
- adam/model_plugins_builtin/oasis/manifest.py+24-9
- adam/model_plugins_builtin/pixelrow/__init__.pyAdded+2
- adam/model_plugins_builtin/pixelrow/common.pyAdded+86
- adam/model_plugins_builtin/pixelrow/generator.pyAdded+212
- adam/model_plugins_builtin/pixelrow/manifest.pyAdded+301
- adam/model_plugins_builtin/pixelrow/model.pyAdded+244
- adam/model_plugins_builtin/pixelrow/trainer.pyAdded+411
- adam/model_plugins_builtin/sdxl_lora/manifest.py+1-1
- adam/model_plugins_builtin/wan_video/__init__.pyAdded+1
- adam/model_plugins_builtin/wan_video/manifest.pyAdded+50
- adam/nova.py+2
- adam/oasis_dataset.py+94-15
- adam/oasis_player.pyAdded+112
- adam/ollama.py+56-7
- adam/orion.py+85
- adam/planner.py+254-21
- adam/progressive_training.pyAdded+103
- adam/recommendations.py+113-15
- adam/remote_access.py+25-4
- adam/remote_dashboard.py+22-13
- adam/remote_v1.py+53-35
- adam/tool_folders.py+5
- adam/tools/ddpm_adapter.py+244-28
- adam/tools/flow_adapter.py+119-4
- adam/tools/flow_generator.py+19
- adam/tools/lora_adapter.py+8-1
- adam/tools/lora_generator.py+115-16
35 unmodified lines36373835 unmodified linesassets/adam_atom.ico filter=lfs diff=lfs merge=lfs -textassets/adam_atom.png filter=lfs diff=lfs merge=lfs -textdocs/screenshots/command-center.png filter=lfs diff=lfs merge=lfs -text35 unmodified lines3637383935 unmodified linesassets/adam_atom.ico filter=lfs diff=lfs merge=lfs -textassets/adam_atom.png filter=lfs diff=lfs merge=lfs -textdocs/screenshots/command-center.png filter=lfs diff=lfs merge=lfs -textdocs/field-guide/adam-map.png filter=lfs diff=lfs merge=lfs -text
123version https://git-lfs.github.com/spec/v1oid sha256:f0e60f14332f6b6c5445871e81133162df75d98f3113f8c9c43d6b2dfd8a5d29size 17269303 unmodified lines4567893 unmodified lineshiddenimports = (collect_submodules("adam.tools")+ collect_submodules("transformers.models.dinov2")+ ["transformers", "torch", "PIL"])3 unmodified lines456789103 unmodified lineshiddenimports = (collect_submodules("adam.tools")+ collect_submodules("adam.model_plugins_builtin")+ collect_submodules("transformers.models.dinov2")+ ["transformers", "torch", "PIL"])
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394---license: mittags:- desktop-application- ai-tools- dataset-management- lora-training- windows---# ADAM — AI Development and Automation ManagerADAM is a local, safety-first desktop hub for orchestrating AI project tools.It includes registered dataset, DDPM, and SDXL LoRA workflows with backgroundplanning, approval gates, progress reporting, and persistent asset history.Dataset preparation, captioning, and preview placeholders remain clearly markedas demo tools. The connected Dataset Collector, DDPM trainer, and Local SDXLLoRA Trainer use real adapters and never fall back to simulated training.Existing program folders can be connected from **Settings → Tool folders**.ADAM stores only the path and scans for likely entry points; it does not copy ormodify the external project. Folder assignments can also be pasted into chat:```textDDPM Trainer: D:\AI\DDPMFlow Matching Trainer: D:\AI\FlowMatchImageGenerator```On a new computer, install `requirements.txt` in your chosen Python environmentbefore running `Launch ADAM.bat`. The launcher checks desktop dependencies anddoes not install packages automatically or depend on the developer's personaltrainer folders. Install each optional trainer's dependencies according to thattool's setup instructions before using its ADAM workflow.Remote access is disabled by default. Devices with an access token can browsedatasets, edit captions/review marks and submit work. Only enable it for trusteddevices. The desktop **Allow remote job controls and approval changes** settingalso permits remote confirmation, stopping and retrying jobs. A remote browsercan enable training auto-approval only after that desktop permission is granted;it can always turn auto-approval off. Saved token changes and disabled accesstake effect for new requests without restarting the server.Use private Tailscale access for connections beyond a trusted local network;the built-in HTTP listener does not provide transport encryption by itself.Phone URLs and QR codes contain the access token and should be treated ascredentials. Remote commands require JSON, have bounded request sizes andconnection counts, and reject cross-site browser submissions. These controlsdo not sandbox installed Python plugins or connected trainers: install onlycode you trust.Detection does not automatically authorize training. A real training adapterremains gated until its dataset, model name, run settings, and output locationare explicit.## Training agentsADAM's training lifecycle is divided into four explainable responsibilities:- **EVE** reviews dataset membership and leaves uncertain images for the user.- **ORION** reviews planned epochs, batch size, resolution, image exposures, andestimated optimizer steps. He can require approval but never silently changesthe requested settings. In the Model Creation Assistant, **ORION: apply astarting recipe** fills a conservative, editable draft from the image countand selected resolution before a plan is built.- **ATLAS** watches active training for non-finite loss, sustained critical GPUtemperature, critically low disk space, stalls, and large runtime overruns.Critical conditions pause the trainer process tree so the user can inspect it.- **NOVA** examines available post-training previews and samples for unreadablefiles and exact-looking duplicate collapse. Her report explicitly separatestechnical sample health from subjective or subject-quality review.ORION, ATLAS, and NOVA reports are stored with each durable job record and areshown in Current Plan, Active Job, and Jobs / History respectively. ATLAS'sdefault thresholds can be overridden in `config/settings.json` with the`atlas_*` settings defined in `adam/config.py`.Every new job passes through the shared preflight and ORION review before itsqueue state is chosen. Desktop plans, Remote prompts, and Remote training formsuse the same review. Remote training auto-approval still applies to ordinaryplans, but an ORION warning leaves the job awaiting explicit approval. Reviewinga plan does not change the requested training settings.## Real image collectionWhen a valid Dataset Collector folder is connected, the `dataset_collector`registry entry uses ADAM's real visible-browser adapter. After plan approval it:- opens Bing Images in a normal visible Chrome window;- waits when consent/CAPTCHA/human-verification text is detected;- resumes automatically after the user resolves the page;- downloads valid images at least 256×256;- removes exact duplicate downloads;- writes a matching `.txt` caption beside every image; and- records URLs, captions, sources, and dimensions in `metadata.csv`.No CAPTCHA or website restriction is bypassed. Closing Chrome or stopping thejob ends collection safely. A new timestamped dataset folder is used ratherthan overwriting an existing collection.ADAM keeps an incomplete DDPM request in conversation memory. A follow-up suchas `dataset folder Mario, model name Mario V2, epoch count 100, output D:\Runs`fills the pending fields and validates named datasets against the connectedcollector. It will not start if the dataset cannot be found.## Showcase videosThe **Showcase Video** workspace creates a finished MP4 directly from completedDDPM and Flow Matching models. Select and reorder the models, choose 12–24images per model, a 3-, 4-, or 5-second image duration, shared steps and aspectratio, provider-compatible samplers, seed, and 720p or 1080p output. ADAM runsthe image batches sequentially and then renders a request-list interface thattracks the active model, image number, trainer, steps, sampler, and aspect ratio.LoRA models are intentionally excluded from this streamlined workflow.When Ollama is reachable, messages that are not workflow commands receive ashort conversational answer. Ollama may explain or plan, but it still cannotbypass the registry or confirmation gates.## Web search in Chat ModeChat Mode can give local Ollama current web context without an API key. Enableit in **Settings → Planning model**, then ask naturally, for example:```textSearch the web for Dandy's World character ideas.What are the latest Ollama release notes?Look up a reference for a cyberpunk city character.```ADAM sends only that search query to Bing's public results feed, reads theresult titles and snippets,and passes up to five titles, snippets, and links to Ollama. It does not openthe result pages, download anything, or let web content run tools. Results areuntrusted reference material, so ADAM is instructed to cite the links and flaguncertainty. Disable the setting to keep Chat Mode fully local.When you explicitly ask ADAM to **read**, **open**, or **research** result links,it can read up to three public HTML/text pages and give Ollama short extracts.For example: `Search the web for Undertale character ideas and read the mostrelevant links.` Direct links can be read with `Read https://example.com/ andsummarize it.` Private/local addresses, non-web protocols, oversized pages,downloads, and more than three pages are blocked. This control can be disabledin Settings.Planning runs away from the interface thread, and conversational Ollama outputis streamed into the chat. ADAM validates training commands against a strictschema and each registered trainer's declared capabilities before offering ajob.In **Settings → Planning model**, **Chat response length** sets the maximumnumber of generated tokens for a Chat Mode reply. Higher values allow longerresearch summaries but use more time and GPU memory. The default is 1,024,which gives Qwen3 enough room to reason and still produce a visible response.ADAM stores friendly dataset/model names, paths, trainer types, epochs, andresume checkpoints in `data/assets.json`. Requests such as:```textFrom the Mario dataset, train it on a DDPM for 300 epochs.With the Mario dataset, train it on a LoRA for 100 epochs.Continue the Mario model from the DDPM for 50 epochs.```are resolved to real paths before approval. Continuation is offered only when acompatible checkpoint exists. New DDPM runs retain the latest resume checkpoint.## Run```powershellpython main.py```On Windows, you can also double-click `Launch ADAM.bat`.The app requires Python 3.10+ and PySide6. Optional integrations use `psutil`for system information and `pynvml` for NVIDIA GPU information.```powershellpython -m pip install -r requirements.txt```Try:- Click **Create a model…** in Trainer Mode for the guided Model Creation Assistant.- `Adam, train a LoRA of Hatsune Miku`- `Adam, collect a dataset of liminal spaces`- `Adam, generate previews`- `Adam, check GPU status`- `From the Mario dataset, train it on a DDPM for 300 epochs`- `With the Mario dataset, train it on a LoRA for 100 epochs`Training and large collection plans are never started until you approve theplan. All actions are recorded in `logs/adam.log`, while project artifacts liveunder `data/projects/`.The Model Creation Assistant can start from a built-in Character LoRA, StyleLoRA, DDPM, or Flow Matching preset. It can create a dataset or select aregistered one, recommends starting values, and saves personal presets. Theresult still goes through ADAM's normal validated planner and approval gate.Use **+ Add model** to build a multi-model training batch. Each wide model tabkeeps its own dataset, trainer, name, and settings; the minus button removes anunwanted model, and tabs can be dragged to change the run order. ADAM validatesall models, presents one combined approval plan, and runs them sequentially soonly one training workflow uses the GPU at a time. A failed step stops the batchbefore a later model starts.Before approval, ADAM adds checks for connected tools, dataset contents, theLoRA base model, and output-drive free space. Completed dataset and trainingjobs also include a suggested next step.### Model Batch BuilderUse **Create model batch…** to paste one requested subject per line. ADAM turnsthe list into editable model tabs, removes duplicate names, and lets the currenttrainer recipe be applied to any multi-selection of models. The batch is savedas a draft so it can be closed and resumed later.For a review-first workflow, choose **Collect missing datasets first**. Thisqueues only sequential dataset collection and leaves training in the saveddraft. After collection, reopen the draft, use **Find collected datasets**, andreview each dataset in Training Studio. **Exclude rejected** moves rejectedimages out of the training folder into a recoverable quarantine, and **Restoreexcluded** reverses it. **Keep all images** marks the whole selected dataset asaccepted in one action, after which individual bad images can still be rejected.Training remains locked until each model is explicitlymarked as reviewed and ready. If every linked dataset is acceptable as-is,**Approve all datasets** marks the entire batch ready after one confirmation;it does not inspect individual images or apply pending rejection decisions.Completed Flow Matching models can be selected in **Fine-tune**. ADAM uses thesaved Flow model folder as the continuation source, locks the continuation tothe model's original resolution, and writes the fine-tuned result to a newoutput folder. This continues the saved weights while starting a fresh optimizerand learning-rate schedule; it does not overwrite the original model.## Training StudioThe **Training Studio** turns completed work into a reviewable experiment loop:- **Datasets** provides an image gallery, keep/reject decisions, caption editing,exact duplicate detection, and visually similar duplicate candidates.- **Experiments** compares job settings and outcomes, opens outputs, marks apreferred model, and converts successful settings into reusable recipes.- **Checkpoint Lab** browses model checkpoints and output images, recordsconsistent prompt/seed evaluations, and sends preview requests through thenormal approval-aware planner.- **Recipes** preserves training starting points and can import or exportportable JSON recipe files.### EVE AI Dataset ReviewIn Training Studio → Datasets, **EVE AI Review…** performs a local reference-guided visual review. Add one or more good reference images and optional badreferences, then choose Keep and Reject confidence thresholds. EVE uses a smallDINOv2 vision model to divide the selected dataset into **Keep**, **Reject**, and**Uncertain** galleries with confidence scores. The model is downloaded once onfirst use and subsequent analysis stays local.Nothing is applied automatically. Inspect both sides, double-click images for afull view, and move selected results between the three groups before choosing**Apply EVE review**. EVE's decisions remain ordinary Training Studio reviewmarks: they can be manually changed, and rejected files are not moved until**Exclude rejected** is selected. The latest proposal is also saved under`data/eve_reviews/` for auditing. Use **Select all in current group** (orCtrl/Shift selection) to move many images at once; EVE transfers only thechosen thumbnails so manual sorting stays responsive on large datasets.Training panels show elapsed time, a progress-based ETA, recent logs, and aloss sparkline when the connected trainer reports `loss`. Preflight summariesinclude clearly labelled workload, duration, VRAM, and disk estimates. Theseestimates are planning hints rather than hardware guarantees.Create a Model also supports live training previews with a configurableepoch interval, prompt, and reproducible seed for each model tab. While atraining job is active, its newest 256×256 preview appears in the right sidebarwith the source epoch and next scheduled preview. The full-size trainer outputcan be opened from the card. Built-in adapters may publish previews directly;registered DDPM, Flow, LoRA, APVD, MaskGit, and other trainers can alsoparticipate by writing conventionally named `preview`, `sample`, or `epoch`images beneath their declared output folder.## GenerationsThe **Generations** workspace runs compatible registered image generatorswithout opening their separate desktop interfaces. The connected DDPM and FlowMatching projects can generate from completed models with a reproducible seed,sampler or ODE method, step count, image count, and aspect ratio. Generationwork uses the normal ADAM job queue, progress reporting, cancellation, andlogging.Every completed batch is stored under `data/generations/` with its images and a`generation.json` sidecar. The history gallery can open an image or batch folderand restore the exact settings for another run. DDPM creative notes are storedwith a batch for organization; they are not presented as text conditioning foran unconditional DDPM model.Generation history opens as automatic model folders. Each folder uses theregistered model name and a recent generated image as its cover. Double-clickinga folder filters history to that model and selects its provider and model in thegeneration controls, so the next batch is generated into the same existing modeldirectory. This view does not move or rewrite older generation files.**Generation Cycle…** selects multiple compatible completed models and queuesone generation step per model. Choose images per model, a shared prompt orcreative note, starting seed, slideshow duration, looping, fullscreen playback,and an optional model/trainer label. When the cycle finishes, ADAM opens theresults as a local slideshow while preserving every ordinary generation recordin history.If ADAM discovers a job interrupted by an unexpected shutdown, it offers toopen Jobs & History. The previous record remains intact and can be retried as anew approval-gated job. Job logs can also be exported for troubleshooting.## Connect an existing toolADAM supports importable Python functions and command-line Python scripts.For a no-code setup, open **Settings → External Tools → Add external tool**.Choose the program folder, select its training entry script and importantconfiguration files, then review ADAM's static compatibility and safety report.The report covers:- detected command-line options and required inputs;- likely dataset formats;- output and checkpoint behavior;- progress reporting;- resume-training support; and- potentially risky operations visible in the selected entry script.The 1–10 rating measures how clearly the script fits ADAM's safe command-linecontract. It is not a guarantee that third-party code is harmless. ADAM doesnot execute a script while scanning it, external tools cannot replace built-inregistry entries, and every external-tool run requires explicit approval.After registration, a tool can be planned with a request such as:```textRun APVD Model Trainer with dataset=D:\DreamData, epochs=20, output=D:\APVD\output```ADAM will ask for any required inputs that were omitted before it offers theapproval plan.For manual registry configuration, edit the relevant item in`config/tools.json`:```json{"backend": {"type": "python","module": "my_tools.lora","function": "train"},"demo": false}```The function receives a `ToolContext` as its first argument and keywordarguments from the approved plan. This keeps training code in one place: yourexisting GUI and ADAM can both call the same backend.For scripts:```json{"backend": {"type": "script","path": "D:/AI/LoRATrainer/train.py"},"demo": false}```ADAM invokes scripts directly with the current Python interpreter, capturesstdout/stderr, and never drives another GUI with mouse clicks.## Safety model- Plans are shown before execution.- Long, destructive, or high-volume work requires confirmation.- Unregistered tools cannot be invoked.- External paths and arguments are validated before execution.- The LLM may propose a plan, but only registered tools can execute it.- Pause, resume, and cancel controls are available for active jobs.- Every tool action and state transition is logged.## Tests```powershellpython -m pytest -q```123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591---license: mittags:- desktop-application- ai-tools- dataset-management- lora-training- windows- ai-workflow- experiment-tracking- model-plugins- video-lora---# ADAM — AI Development and Automation ManagerADAM is a local desktop command center for AI experiments: describe an idea,prepare and review a dataset, approve a training plan, generate samples, anduse saved experiment history to decide what to try next.It began as a **Jarvis-inspired assistant for AI workflows** and has grown intoa Windows/PySide6 application with registered tools, model plugins, backgroundjobs, live previews, and optional local Ollama chat and Remote access.**Source release: 1 October 2026 · 322 tests passed across 33 modules.** This repository contains the desktopapplication and its source code. Model weights, personal datasets, saved jobs,and connected external trainer projects are supplied separately by the user.**[Explore the interactive ADAM field guide](https://huggingface.co/spaces/SyntheticMDProductions/ADAM-Field-Guide)**— click the workflow stages, reviewers and model architectures, then explorefour animated explanations of image construction. You can also[download the standalone HTML guide](https://huggingface.co/SyntheticMDProductions/AI_Development_Automation_Manager/resolve/main/docs/field-guide/adam-field-guide.html?download=true)and [the visual map](docs/field-guide/adam-map.png).The animations explain mechanisms; they are not model inference or quality benchmarks.## What ADAM includes| Workspace | What it does || --- | --- || Command center | Local Ollama chat, validated workflow planning, guided model creation, and sequential model batches || Training Studio / Dataset Lab | Dataset browsing, captions, keep/reject decisions, EVE proposals, recoverable exclusions, checkpoint review, and recipes || Jobs / History | Approval, scheduling, progress, previews, pause/cancel, retry, and persistent records || Generations / Showcase Video | Reproducible image batches, saved settings, generation history, and DDPM/Flow showcase MP4s || Video LoRA | Wan 2.1 T2V 1.3B clip preparation, character-reference suggestions, reviewed caption drafts, training, and video generation || Model Intelligence / Experiments | Training and generation evidence, run comparison, and follow-up experiment suggestions || Oasis player | Playable inference for compatible action-conditioned world models || Tools / Remote / System | Declared plugin settings, connected tool folders, optional authenticated device access, and hardware telemetry || Model family | Integration || --- | --- || DDPM, regular Flow Matching, SDXL LoRA | Adapters for separately connected local trainers and generators || PixelRow | Experimental built-in model that generates top to bottom, one row at a time || INRFlow | Experimental built-in coordinate-to-RGB flow model without a pretrained image compressor || Neural Cellular Automata | Included experimental custom plugin that learns image growth from a living seed || Oasis | Experimental connected action world model with temporal latent and temporal pixel-flow workflows || Wan video LoRA | Dedicated workspace and adapter for a connected LoRAVideoTrainer/Musubi environment |See [release notes](docs/releases/2026-10-01.md) for changes since the September 5 release,and [Oasis](docs/oasis_integration.md) / [INRFlow](docs/inrflow_integration.md)for integration details. Experimental architectures are intended for localexploration; this release makes no benchmark-quality claims.## Quick start[Download the complete source ZIP](https://huggingface.co/SyntheticMDProductions/AI_Development_Automation_Manager/resolve/main/ADAM-source-2026-10-01.zip?download=true),extract it, or clone this repository, then run:```powershellpython -m pip install -r requirements.txtpython main.py```Use Python 3.10+ on Windows. You can also double-click `Launch ADAM.bat` afterinstalling the requirements. Choose a CUDA-compatible PyTorch build for GPUtraining according to your hardware. Optional trainer projects keep their owndependencies and model weights; connect them in **Settings → Tool folders**.Ollama is optional for local chat and model-assisted planning. Chrome is neededfor the visible image collector; FFmpeg is needed for video collection and splitting.The release starts with empty tool connections and Remote access disabled.Application state is saved locally under `data/`, `logs/`, and `config/settings.json`.Dataset preparation, captioning, and preview placeholders remain clearly markedas demo tools. The connected Dataset Collector, DDPM trainer, and Local SDXLLoRA Trainer use real adapters and never fall back to simulated training.Existing program folders can be connected from **Settings → Tool folders**.ADAM stores only the path and scans for likely entry points; it does not copy ormodify the external project. Folder assignments can also be pasted into chat:```textDDPM Trainer: D:\AI\DDPMFlow Matching Trainer: D:\AI\FlowMatchImageGenerator```On a new computer, install `requirements.txt` in your chosen Python environmentbefore running `Launch ADAM.bat`. The launcher checks desktop dependencies anddoes not install packages automatically or depend on the developer's personaltrainer folders. Install each optional trainer's dependencies according to thattool's setup instructions before using its ADAM workflow.Remote access is disabled by default. Devices with an access token can browsedatasets, edit captions/review marks and submit work. Only enable it for trusteddevices. The desktop **Allow remote job controls and approval changes** settingalso permits remote confirmation, stopping and retrying jobs. A remote browsercan enable training auto-approval only after that desktop permission is granted;it can always turn auto-approval off. Saved token changes and disabled accesstake effect for new requests without restarting the server.Use private Tailscale access for connections beyond a trusted local network;the built-in HTTP listener does not provide transport encryption by itself.Phone URLs and QR codes contain the access token and should be treated ascredentials. Remote commands require JSON, have bounded request sizes andconnection counts, and reject cross-site browser submissions. These controlsdo not sandbox installed Python plugins or connected trainers: install onlycode you trust.Detection does not automatically authorize training. A real training adapterremains gated until its dataset, model name, run settings, and output locationare explicit.## Training agentsADAM's training lifecycle is divided into four explainable responsibilities:- **EVE** reviews dataset membership and leaves uncertain images for the user.- **ORION** reviews planned epochs, batch size, resolution, image exposures, andestimated optimizer steps. He can require approval but never silently changesthe requested settings. In the Model Creation Assistant, **ORION: apply astarting recipe** fills a conservative, editable draft from the image countand selected resolution before a plan is built.- **ATLAS** watches active training for non-finite loss, sustained critical GPUtemperature, critically low disk space, stalls, and large runtime overruns.Critical conditions pause the trainer process tree so the user can inspect it.- **NOVA** examines available post-training previews and samples for unreadablefiles and exact-looking duplicate collapse. Her report explicitly separatestechnical sample health from subjective or subject-quality review.ORION, ATLAS, and NOVA reports are stored with each durable job record and areshown in Current Plan, Active Job, and Jobs / History respectively. ATLAS'sdefault thresholds can be overridden in `config/settings.json` with the`atlas_*` settings defined in `adam/config.py`.Every new job passes through the shared preflight and ORION review before itsqueue state is chosen. Desktop plans, Remote prompts, and Remote training formsuse the same review. Remote training auto-approval still applies to ordinaryplans, but an ORION warning leaves the job awaiting explicit approval. Reviewinga plan does not change the requested training settings.## Real image collectionWhen a valid Dataset Collector folder is connected, the `dataset_collector`registry entry uses ADAM's real visible-browser adapter. After plan approval it:- opens Bing Images in a normal visible Chrome window;- waits when consent/CAPTCHA/human-verification text is detected;- resumes automatically after the user resolves the page;- downloads valid images at least 256×256;- removes exact duplicate downloads;- writes a matching `.txt` caption beside every image; and- records URLs, captions, sources, and dimensions in `metadata.csv`.No CAPTCHA or website restriction is bypassed. Closing Chrome or stopping thejob ends collection safely. A new timestamped dataset folder is used ratherthan overwriting an existing collection.ADAM keeps an incomplete DDPM request in conversation memory. A follow-up suchas `dataset folder Mario, model name Mario V2, epoch count 100, output D:\Runs`fills the pending fields and validates named datasets against the connectedcollector. It will not start if the dataset cannot be found.## Showcase videosThe **Showcase Video** workspace creates a finished MP4 directly from completedDDPM and Flow Matching models. Select and reorder the models, choose 12–24images per model, a 3-, 4-, or 5-second image duration, shared steps and aspectratio, provider-compatible samplers, seed, and 720p or 1080p output. ADAM runsthe image batches sequentially and then renders a request-list interface thattracks the active model, image number, trainer, steps, sampler, and aspect ratio.LoRA models are intentionally excluded from this streamlined workflow.When Ollama is reachable, messages that are not workflow commands receive aconversational answer. In Chat Mode, attach an image with the **+** button anda vision-capable Ollama model can describe it, suggest a caption, or answerquestions about visible details. Images stay on the local Ollama connection.In Trainer Mode, the planning model can propose a registered ADAM action whenthe request is not recognized by the built-in planner. ADAM validates theproposed tool and every setting against its registry, and confirmation gatesstill apply. This option can be disabled in **Settings → Safety & Notifications**.## Web search in Chat ModeChat Mode can give local Ollama current web context without an API key. Enableit in **Settings → Planning model**, then ask naturally, for example:```textSearch the web for Dandy's World character ideas.What are the latest Ollama release notes?Look up a reference for a cyberpunk city character.```ADAM sends only that search query to Bing's public results feed, reads theresult titles and snippets,and passes up to five titles, snippets, and links to Ollama. It does not openthe result pages, download anything, or let web content run tools. Results areuntrusted reference material, so ADAM is instructed to cite the links and flaguncertainty. Disable the setting to keep Chat Mode fully local.When you explicitly ask ADAM to **read**, **open**, or **research** result links,it can read up to three public HTML/text pages and give Ollama short extracts.For example: `Search the web for Undertale character ideas and read the mostrelevant links.` Direct links can be read with `Read https://example.com/ andsummarize it.` Private/local addresses, non-web protocols, oversized pages,downloads, and more than three pages are blocked. This control can be disabledin Settings.Planning runs away from the interface thread, and conversational Ollama outputis streamed into the chat. ADAM validates training commands against a strictschema and each registered trainer's declared capabilities before offering ajob.In **Settings → Planning model**, choose an automatic, short, balanced, ordetailed response style. Automatic uses a smaller response for simple questionsand makes more room for image reviews, explanations, and planning. **Maximumresponse length** remains a hard limit for response time and GPU memory; thedefault is 1,024 tokens.ADAM stores friendly dataset/model names, paths, trainer types, epochs, andresume checkpoints in `data/assets.json`. Requests such as:```textFrom the Mario dataset, train it on a DDPM for 300 epochs.With the Mario dataset, train it on a LoRA for 100 epochs.Continue the Mario model from the DDPM for 50 epochs.```are resolved to real paths before approval. Continuation is offered only when acompatible checkpoint exists. New DDPM runs retain the latest resume checkpoint.## Run```powershellpython main.py```On Windows, you can also double-click `Launch ADAM.bat`.The app requires Python 3.10+ and PySide6. Optional integrations use `psutil`for system information and `pynvml` for NVIDIA GPU information.```powershellpython -m pip install -r requirements.txt```Try:- Click **Create a model…** in Trainer Mode for the guided Model Creation Assistant.- `Adam, train a LoRA of Hatsune Miku`- `Adam, collect a dataset of liminal spaces`- `Adam, generate previews`- `Adam, check GPU status`- `From the Mario dataset, train it on a DDPM for 300 epochs`- `With the Mario dataset, train it on a LoRA for 100 epochs`Training and large collection plans are never started until you approve theplan. All actions are recorded in `logs/adam.log`, while project artifacts liveunder `data/projects/`.The Model Creation Assistant can start from a built-in Character LoRA, StyleLoRA, DDPM, Flow Matching, or experimental PixelRow preset. It can create a dataset or select aregistered one, recommends starting values, and saves personal presets. Theresult still goes through ADAM's normal validated planner and approval gate.Use **+ Add model** to build a multi-model training batch. Each wide model tabkeeps its own dataset, trainer, name, and settings; the minus button removes anunwanted model, and tabs can be dragged to change the run order. ADAM validatesall models, presents one combined approval plan, and runs them sequentially soonly one training workflow uses the GPU at a time. A failed step stops the batchbefore a later model starts.Before approval, ADAM adds checks for connected tools, dataset contents, theLoRA base model, and output-drive free space. Completed dataset and trainingjobs also include a suggested next step.### Model Batch BuilderUse **Create model batch…** to paste one requested subject per line. ADAM turnsthe list into editable model tabs, removes duplicate names, and lets the currenttrainer recipe be applied to any multi-selection of models. The batch is savedas a draft so it can be closed and resumed later.For a review-first workflow, choose **Collect missing datasets first**. Thisqueues only sequential dataset collection and leaves training in the saveddraft. After collection, reopen the draft, use **Find collected datasets**, andreview each dataset in Training Studio. **Exclude rejected** moves rejectedimages out of the training folder into a recoverable quarantine, and **Restoreexcluded** reverses it. **Keep all images** marks the whole selected dataset asaccepted in one action, after which individual bad images can still be rejected.Training remains locked until each model is explicitlymarked as reviewed and ready. If every linked dataset is acceptable as-is,**Approve all datasets** marks the entire batch ready after one confirmation;it does not inspect individual images or apply pending rejection decisions.Completed Flow Matching models can be selected in **Fine-tune**. ADAM uses thesaved Flow model folder as the continuation source, locks the continuation tothe model's original resolution, and writes the fine-tuned result to a newoutput folder. This continues the saved weights while starting a fresh optimizerand learning-rate schedule; it does not overwrite the original model.## PixelRowPixelRow is ADAM's experimental top-to-bottom image architecture. It trains onordinary image folders and predicts one complete quantized RGB row from allprevious rows, without a diffusion noise schedule. Start with 64×64 images forthe first experiment; 128×128 is available but trains more slowly.PixelRow generation uses one step per image row. The Generations page labelsthese as **Rows** and offers creativity, top-color-choice, and row-framesettings. Enabling **Save row-build frames** writes a PNG sequence beneath thegeneration folder, making the construction process ready for a video or visualcomparison. Seeds reproduce both the finished image and its intermediate rows.## Wan Video LoRAOpen **Video LoRA** in the sidebar to use the connected LoRAVideoTrainer frominside ADAM. This workspace is separate from the image-model creation assistantand image Generations page. It targets **Wan 2.1 T2V 1.3B** only.Connect **Settings → Tool folders → Wan Video LoRA Trainer** to your existingLoRAVideoTrainer folder. An existing `external_loravideotrainer` connection isrecognized automatically. ADAM runs its `.venv/Scripts/python.exe` and installedMusubi Tuner; use that project's setup instructions for its CUDA dependenciesand base weights. ADAM does not install or replace the trainer environment.1. In **Dataset**, choose a folder of short video clips with matching `.txt`captions, import clips, or use **Split long video**. Splitting creates a newfolder of evenly spaced 49-frame clips at 12 FPS, preserving the source.Select clips for looping preview and caption editing. Captions save onselection/tab changes; include the exact trigger word from Training.**Characters & recognition** maintains a local character library with one ormore reference images per character. It samples several frames from eachclip and uses local DINOv2 visual similarity to suggest zero or multiplecharacters. Review the suggestions and uncheck false matches before applyingtrigger words to captions; existing action descriptions are preserved.Recognition suggestions are not applied automatically, and similarityscores are only a review aid. Character references and the library are storedunder `data/video_characters/`.To draft action captions, select one or more clips and choose **AI draftcaptions**. ADAM samples six ordered frames per clip and asks the configuredOllama model to describe visible actions and changes without guessing who ispresent, in English. It retries once if the model returns CJK text. Review andedit each draft as soon as it finishes while the next selected clip is beingprocessed. ADAM trims notes, alternate summaries, and repeated commentary toone short caption sentence. Check the captions to keep, then save;ADAM adds the active training trigger automatically. Failed clips remainunchanged, and unchecked drafts are not written.2. In **Training**, enter a unique run name and review epochs, trigger, framebuckets, training resolution, rank/alpha, learning rate and memory swapping.**Review full training pipeline** creates a job awaiting approval in**Jobs / History**. After approval it validates clips, caches video latents,caches captions, then trains. Failures stop subsequent stages.3. In **Generate**, choose a compatible checkpoint and set prompt, strength,landscape/portrait format, seconds, FPS, steps, seed and block swapping.ADAM converts duration to Wan's `4N+1` frame count and displays the actualduration. Start with **Fast preview preset** before trying longer clips.4. **Videos / takes** lists new MP4s with prompt/seed/settings and existingsamples from the connected trainer. Double-click to play a video.Training outputs default to `data/video_models/<run name>/`, including anisolated cache, dataset configuration, logs and model metadata. Existing outputfolders cannot be overwritten. **Continue weights** loads a Wan adapter into anew run with a fresh optimizer and schedule; its rank and alpha come from thecheckpoint. It does not restore a full interrupted optimizer state. Cancellationkeeps previously written checkpoints, but does not force a new checkpoint.Generations are stored in `data/video_generations/`, with an MP4 and`generation.json` recording the actual seed, model, prompt, settings and outputdimensions. Existing Wan checkpoints in LoRAVideoTrainer's `output/` are indexedseparately from SDXL. The first visit imports compatible local trainer settings;subsequent changes are saved in ADAM's own configuration. The original trainer'sstoryboard editor remains available through that application.All work uses ADAM's shared job queue, logs and pause/cancel controls. Trainingkeeps ORION review and ATLAS supervision, with video-specific workload notes.NOVA requests video samples instead of applying image-preview quality checks.Chat requests mentioning Wan or video LoRA direct you to the dedicated workspace.## Training StudioThe **Training Studio** turns completed work into a reviewable experiment loop:- **Datasets** provides an image gallery, keep/reject decisions, caption editing,exact duplicate detection, and visually similar duplicate candidates.- **Experiments** compares job settings and outcomes, opens outputs, marks apreferred model, and converts successful settings into reusable recipes.- **Checkpoint Lab** browses model checkpoints and output images, recordsconsistent prompt/seed evaluations, and sends preview requests through thenormal approval-aware planner.- **Recipes** preserves training starting points and can import or exportportable JSON recipe files.### EVE AI Dataset ReviewIn Training Studio → Datasets, **EVE AI Review…** performs a local reference-guided visual review. Add one or more good reference images and optional badreferences, then choose Keep and Reject confidence thresholds. EVE uses a smallDINOv2 vision model to divide the selected dataset into **Keep**, **Reject**, and**Uncertain** galleries with confidence scores. The model is downloaded once onfirst use and subsequent analysis stays local.Nothing is applied automatically. Inspect both sides, double-click images for afull view, and move selected results between the three groups before choosing**Apply EVE review**. EVE's decisions remain ordinary Training Studio reviewmarks: they can be manually changed, and rejected files are not moved until**Exclude rejected** is selected. The latest proposal is also saved under`data/eve_reviews/` for auditing. Use **Select all in current group** (orCtrl/Shift selection) to move many images at once; EVE transfers only thechosen thumbnails so manual sorting stays responsive on large datasets.Training panels show elapsed time, a progress-based ETA, recent logs, and aloss sparkline when the connected trainer reports `loss`. Preflight summariesinclude clearly labelled workload, duration, VRAM, and disk estimates. Theseestimates are planning hints rather than hardware guarantees.Create a Model also supports live training previews with a configurableepoch interval, prompt, and reproducible seed for each model tab. While atraining job is active, its newest 256×256 preview appears in the right sidebarwith the source epoch and next scheduled preview. The full-size trainer outputcan be opened from the card. Built-in adapters may publish previews directly;registered DDPM, Flow, LoRA, APVD, MaskGit, and other trainers can alsoparticipate by writing conventionally named `preview`, `sample`, or `epoch`images beneath their declared output folder.## INRFlowADAM includes an experimental, lightweight **INRFlow** trainer and generator asa separate built-in model architecture. It follows the paper's ambient-spacedesign: an image is represented as coordinate-to-RGB pairs, spatial contextlatents summarize the current noisy field, and a point decoder predicts theflow velocity for independently sampled pixel queries. Training therefore usescontinuous flow matching directly on RGB values without a VAE or anotherpretrained image compressor.The implementation is intentionally scaled for local experiments rather thanthe much larger published configurations. The 64px default is the recommendedstarting point on an 8–12 GB GPU. Pixel-query subsampling lowers training memory;batch size, query count, width, and resolution can be reduced further. Modelssave ordinary checkpoints, EMA weights, resumable optimizer state, metadata,and optional training previews beneath`data/model_plugin_outputs/inrflow/`.Completed INRFlow models appear in Generations next to regular Flow Matching,with reproducible seeds, Euler or Heun integration, live ODE previews, SmartGeneration, and square resolution-flexible queries. A different outputresolution is coordinate-field extrapolation, so native resolution is the fairdefault for model comparisons. Creative notes are metadata because the currentbackend is unconditional.This is an independent ADAM-sized implementation informed by the[INRFlow paper](https://arxiv.org/abs/2412.03791) and[Apple's reference repository](https://github.com/apple/ml-inrflow), not a copyof the published training setup or a claim of reproducing its reported modelscale.## GenerationsThe **Generations** workspace runs compatible registered image generatorswithout opening their separate desktop interfaces. DDPM, regular Flow Matching,INRFlow, and PixelRow can generate from completed models with reproduciblesettings; PixelRow uses rows, while both flow backends use ODE sampling steps.Generation work uses the normal ADAM job queue, progress reporting,cancellation, and logging.Every completed batch is stored under `data/generations/` with its images and a`generation.json` sidecar. The history gallery can open an image or batch folderand restore the exact settings for another run. DDPM creative notes are storedwith a batch for organization; they are not presented as text conditioning foran unconditional DDPM model.The workspace groups controls into **Model & Prompt**, **Image Settings**, and**Advanced Settings**. Dimensions, presets, image count, and seed are availablein Image Settings; sampling controls are expanded by default. Collapsing AdvancedSettings preserves its values. Custom LoRA dimensions and reference images areremembered when reopening the page.Generation history opens with image cards for each generator and a preview ofthe latest batch. Click a generator, then a model, to browse its images and selectthat model for generation. **Recent Output**, **All Generations**, and **Favorites**provide alternate history views. The thumbnail strip selects the image shownalongside its metadata and reuse/save actions. In **Compare**, pin one image asa reference and select another thumbnail to view them together. Long metadatavalues are available in tooltips. These views do not move or rewrite oldergeneration files.**Generation Cycle…** selects multiple compatible completed models and queuesone generation step per model. Choose images per model, a shared prompt orcreative note, starting seed, slideshow duration, looping, fullscreen playback,and an optional model/trainer label. When the cycle finishes, ADAM opens theresults as a local slideshow while preserving every ordinary generation recordin history.If ADAM discovers a job interrupted by an unexpected shutdown, it offers toopen Jobs & History. The previous record remains intact and can be retried as anew approval-gated job. Job logs can also be exported for troubleshooting.## Connect an existing toolADAM supports importable Python functions and command-line Python scripts.For a no-code setup, open **Settings → External Tools → Add external tool**.Choose the program folder, select its training entry script and importantconfiguration files, then review ADAM's static compatibility and safety report.The report covers:- detected command-line options and required inputs;- likely dataset formats;- output and checkpoint behavior;- progress reporting;- resume-training support; and- potentially risky operations visible in the selected entry script.The 1–10 rating measures how clearly the script fits ADAM's safe command-linecontract. It is not a guarantee that third-party code is harmless. ADAM doesnot execute a script while scanning it, external tools cannot replace built-inregistry entries, and every external-tool run requires explicit approval.After registration, a tool can be planned with a request such as:```textRun APVD Model Trainer with dataset=D:\DreamData, epochs=20, output=D:\APVD\output```ADAM will ask for any required inputs that were omitted before it offers theapproval plan.For manual registry configuration, edit the relevant item in`config/tools.json`:```json{"backend": {"type": "python","module": "my_tools.lora","function": "train"},"demo": false}```The function receives a `ToolContext` as its first argument and keywordarguments from the approved plan. This keeps training code in one place: yourexisting GUI and ADAM can both call the same backend.For scripts:```json{"backend": {"type": "script","path": "D:/AI/LoRATrainer/train.py"},"demo": false}```ADAM invokes scripts directly with the current Python interpreter, capturesstdout/stderr, and never drives another GUI with mouse clicks.## Safety model- Plans are shown before execution.- Long, destructive, or high-volume work requires confirmation.- Unregistered tools cannot be invoked.- External paths and arguments are validated before execution.- The LLM may propose a plan, but only registered tools can execute it.- Pause, resume, and cancel controls are available for active jobs.- Every tool action and state transition is logged.## Tests```powershellpython scripts/run_tests.py`The runner executes every test module in its own process, keeping Qt applicationlifetimes isolated. A single module can also be run withpython -m pytest tests/test_agents.py -q.``
1f0e60f14332f6b6c5445871e81133162df75d98f3113f8c9c43d6b2dfd8a5d29 ADAM-source-2026-10-01.zip25 unmodified lines262728293031135 unmodified lines1671681691701711721731741751761771787 unmodified lines18618718818919019119237 unmodified lines23023123223323423514 unmodified lines25025125225325425525625725825926026126226326426526626726826927027161 unmodified lines33333433533633733833934034134225 unmodified linesreturn text@dataclass(slots=True)class Asset:id: str135 unmodified linesmatches.append(item)return exact or matchesdef discover(self, config: Any) -> None:folders = config.get("tool_folders", {})if not isinstance(folders, dict):returnfolders = dict(folders)app_root = self.path.parent.parentif not folders.get("oasis_trainer"):try:external = json.loads((app_root / "config" / "external_tools.json").read_text(encoding="utf-8"))7 unmodified linesexternal_lora_root = app_root / "LoRAModelsHere"if external_lora_root.is_dir():for path in external_lora_root.rglob("*.safetensors"):if path.is_file() and "_comfy" not in path.stem.casefold():self.register(kind="model",name=path.stem.removesuffix("_cancelled"),37 unmodified linesroot = Path(str(folders.get(folder_name, ""))) / output_nameif not root.is_dir():continuefor folder in root.iterdir():if not folder.is_dir():continue14 unmodified linesif p.name.rsplit("-", 1)[-1].isdigit()else -1,)elif trainer == "lora":trigger_word = ""checkpoints = sorted((path for path in folder.glob("*.safetensors")if "_comfy" not in path.stem.casefold()),key=lambda p: p.stat().st_mtime,)if checkpoints:name = checkpoints[-1].stem.removesuffix("_cancelled")try:metadata = json.loads((folder / "model_info.json").read_text(encoding="utf-8"))trigger_word = str(metadata.get("trigger_word") or "")except (OSError, ValueError, TypeError, json.JSONDecodeError):trigger_word = ""elif trainer == "flow":checkpoints = []try:61 unmodified linesand item.metadata.get("dataset_location_id") not in valid_location_ids)]dataset_registry.discover_into_assets(self, persist=False)except Exception:passself.save()def _flow_dataset_paths(self) -> dict[str, str]:"""Recover source datasets for Flow models created by ADAM in older runs."""25 unmodified lines2627282930313233343536373839404142434445135 unmodified lines1811821831841851861871881891901911921931941951961971981992002012022032042052062072082092107 unmodified lines21821922022122222322422522622722837 unmodified lines26626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130214 unmodified lines31731831932032132261 unmodified lines38438538638738838939039139239339425 unmodified linesreturn textdef _is_lora_training_checkpoint(path: Path) -> bool:"""Return whether a LoRA weight is an intermediate training snapshot.The LoRA trainer writes both the finished adapter and periodic weights suchas ``name_epoch_0050.safetensors``. The latter are useful for recovery,but are not independently selectable models in ADAM's model library."""name = path.stem.casefold()return bool(re.search(r"(?:^|[_\- ])(?:checkpoint(?:[_\- ]?(?:epoch|e|step))?|epoch|e|step)[_\- ]?\d+(?:[_\- ]|$)",name,))@dataclass(slots=True)class Asset:id: str135 unmodified linesmatches.append(item)return exact or matchesdef discover(self, config: Any, *, persist: bool = True) -> None:# Models are stored by their output folder (or the model file itself).# Keep the registry in step with the filesystem so removing an old# output cannot leave a ghost model that makes name matching ambiguous.self.assets = [itemfor item in self.assetsif item.kind != "model" or (item.path.strip() and Path(item.path).expanduser().exists())# Old ADAM versions registered LoRA epoch snapshots. Prune those# stale records as well as skipping them during new discovery.and not (item.trainer == "lora"and _is_lora_training_checkpoint(Path(item.path)))]folders = config.get("tool_folders", {})if not isinstance(folders, dict):returnfolders = dict(folders)app_root = self.path.parent.parentfrom adam.video_lora import discover_assets as discover_video_assetsdiscover_video_assets(self, app_root, config)if not folders.get("oasis_trainer"):try:external = json.loads((app_root / "config" / "external_tools.json").read_text(encoding="utf-8"))7 unmodified linesexternal_lora_root = app_root / "LoRAModelsHere"if external_lora_root.is_dir():for path in external_lora_root.rglob("*.safetensors"):if (path.is_file()and "_comfy" not in path.stem.casefold()and not _is_lora_training_checkpoint(path)):self.register(kind="model",name=path.stem.removesuffix("_cancelled"),37 unmodified linesroot = Path(str(folders.get(folder_name, ""))) / output_nameif not root.is_dir():continue# LoRA Trainer versions do not all agree on their output layout.# Some write ``output/<run>/<name>.safetensors`` while others add# a second folder below the run. Register the actual weight file# in either layout so the generator can load it directly.if trainer == "lora":for checkpoint_path in root.rglob("*.safetensors"):if (not checkpoint_path.is_file()or "_comfy" in checkpoint_path.stem.casefold()or _is_lora_training_checkpoint(checkpoint_path)):continuetrigger_word = ""for metadata_path in (checkpoint_path.parent / "model_info.json", checkpoint_path.parent.parent / "model_info.json"):try:metadata = json.loads(metadata_path.read_text(encoding="utf-8"))trigger_word = str(metadata.get("trigger_word") or "")if trigger_word:breakexcept (OSError, ValueError, TypeError, json.JSONDecodeError):continueself.register(kind="model",name=checkpoint_path.stem.removesuffix("_cancelled"),path=str(checkpoint_path),trainer="lora",checkpoint=str(checkpoint_path),metadata={"trigger_word": trigger_word or checkpoint_path.stem.removesuffix("_cancelled")},persist=False,)continuefor folder in root.iterdir():if not folder.is_dir():continue14 unmodified linesif p.name.rsplit("-", 1)[-1].isdigit()else -1,)elif trainer == "flow":checkpoints = []try:61 unmodified linesand item.metadata.get("dataset_location_id") not in valid_location_ids)]dataset_registry.discover_into_assets(self, persist=False, update_cache=persist)except Exception:passif persist:self.save()def _flow_dataset_paths(self) -> dict[str, str]:"""Recover source datasets for Flow models created by ADAM in older runs."""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Intent-level AUTO policies for ADAM training requests.
Natural-language parsing belongs in the planner. This module deliberately doesnot inspect prompt wording: it turns an already-selected trainer, profile, anddataset size into transparent, reproducible training settings."""
from __future__ import annotations
from dataclasses import dataclassfrom enum import Enumfrom typing import Any
from adam.model_profiles import ModelProfilefrom adam.models import SystemSnapshotfrom adam.recommendations import SettingsRecommendation, recommend_for_profile
class TrainingProfile(str, Enum): TEST = "test" BALANCED = "balanced" QUALITY = "quality" OVERNIGHT = "overnight"
@dataclass(frozen=True, slots=True)class AutoTrainingPlan: """Resolved, explainable settings for one training run."""
profile: TrainingProfile dataset_target: int epochs: int settings: dict[str, Any] summary: str reasons: tuple[str, ...] = () warnings: tuple[str, ...] = ()
def profile_from_request(request: str) -> TrainingProfile: """Map only stable, user-facing intent modifiers to a named policy.""" lowered = request.casefold() if any(word in lowered for word in ("overnight", "all night", "long run")): return TrainingProfile.OVERNIGHT if any(phrase in lowered for phrase in ("high quality", "best quality", "really good", "quality")): return TrainingProfile.QUALITY if any(word in lowered for word in ("quick", "quickly", "test", "small", "smoke test")): return TrainingProfile.TEST return TrainingProfile.BALANCED
def dataset_target_for(trainer: str, profile: TrainingProfile) -> int: """Choose a collection target, never a random count.
These are conservative collection targets. The later recommendation is calculated from the actual usable count when an existing dataset is known. """ targets = { "lora": {TrainingProfile.TEST: 40, TrainingProfile.BALANCED: 150, TrainingProfile.QUALITY: 300, TrainingProfile.OVERNIGHT: 500}, "ddpm": {TrainingProfile.TEST: 100, TrainingProfile.BALANCED: 400, TrainingProfile.QUALITY: 800, TrainingProfile.OVERNIGHT: 1_200}, "flow": {TrainingProfile.TEST: 100, TrainingProfile.BALANCED: 400, TrainingProfile.QUALITY: 800, TrainingProfile.OVERNIGHT: 1_200}, "inrflow": {TrainingProfile.TEST: 80, TrainingProfile.BALANCED: 300, TrainingProfile.QUALITY: 600, TrainingProfile.OVERNIGHT: 900}, } return targets.get(trainer, targets["ddpm"])[profile]
def resolve_auto_training( profile: ModelProfile, *, trainer: str, policy: TrainingProfile, dataset_items: int, snapshot: SystemSnapshot | None = None,) -> AutoTrainingPlan: """Resolve a named policy through ADAM's existing exposure-aware recommender.""" recommendation: SettingsRecommendation = recommend_for_profile( profile, dataset_items=max(10, dataset_items), snapshot=snapshot, ) epoch_multiplier = { TrainingProfile.TEST: 0.20, TrainingProfile.BALANCED: 1.00, TrainingProfile.QUALITY: 1.35, TrainingProfile.OVERNIGHT: 1.80, }[policy] # Preserve safe bounds from the recommendation; profiles express their own # architecture-specific baseline rather than sharing a global epoch range. minimum = 3 if policy is TrainingProfile.TEST else 10 maximum = 1_000 if policy is TrainingProfile.OVERNIGHT else 600 epochs = max(minimum, min(maximum, round(recommendation.epochs * epoch_multiplier))) settings = dict(recommendation.settings) if "save_every" in settings: settings["save_every"] = max(1, min(int(settings["save_every"]), max(1, epochs // 4))) if "preview_every" in settings: settings["preview_every"] = max(1, min(int(settings["preview_every"]), max(1, epochs // 5))) target = dataset_target_for(trainer, policy) summary = ( f"{policy.value.title()} AUTO policy: target {target:,} source images; " f"{epochs:,} epoch budget based on {max(10, dataset_items):,} expected usable items." ) return AutoTrainingPlan( profile=policy, dataset_target=target, epochs=epochs, settings=settings, summary=summary, reasons=tuple(recommendation.reasons), warnings=tuple(recommendation.warnings), )123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""A small, local CNN that learns which gameplay frames are worth reviewing.
This is intentionally independent from Oasis. Its job is to prioritize andquality-check collected frames; it never supplies inputs to an Oasis checkpointor changes an Oasis model."""from __future__ import annotations
from dataclasses import dataclassfrom pathlib import Pathfrom typing import Callable
IMAGE_SUFFIXES = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}Progress = Callable[[str], None]
@dataclass(slots=True)class ReviewerTrainingResult: checkpoint: str kept_examples: int rejected_examples: int epochs: int
@dataclass(slots=True)class FrameScore: path: str keep_probability: float suggestion: str
def image_paths(folder: str | Path, *, limit: int = 5_000) -> list[Path]: root = Path(folder).expanduser() if not root.is_dir(): return [] return [ path for path in sorted(root.rglob("*")) if path.is_file() and path.suffix.casefold() in IMAGE_SUFFIXES ][:limit]
def reviewer_checkpoint(root: str | Path, dataset_folder: str | Path) -> Path: """Return an ADAM-owned checkpoint path, separate from dataset and Oasis.""" import hashlib
dataset = str(Path(dataset_folder).expanduser().resolve()).encode("utf-8") identifier = hashlib.sha1(dataset).hexdigest()[:12] return Path(root).expanduser().resolve() / "data" / "cnn_reviewers" / f"{identifier}.pt"
def _torch(): try: import torch from torch import nn except ImportError as exc: # pragma: no cover - controlled by application install raise RuntimeError("CNN Reviewer needs PyTorch. Install the ADAM requirements first.") from exc return torch, nn
def make_reviewer_model(): """Build a deliberately small binary CNN for local frame triage.""" _torch_module, nn = _torch() return nn.Sequential( nn.Conv2d(3, 16, kernel_size=5, stride=2, padding=2), nn.ReLU(), nn.Conv2d(16, 32, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.Conv2d(32, 48, kernel_size=3, stride=2, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d((1, 1)), nn.Flatten(), nn.Linear(48, 1), )
def _load_image(path: Path): torch, _nn = _torch() from PIL import Image
with Image.open(path) as image: image = image.convert("RGB").resize((128, 72)) # No torchvision transform is required, which keeps this feature portable. pixels = image.get_flattened_data() if hasattr(image, "get_flattened_data") else image.getdata() values = torch.tensor(list(pixels), dtype=torch.float32) return values.reshape(72, 128, 3).permute(2, 0, 1).div_(255.0)
def _labeled_paths(decisions: dict[str, str], *, per_class_limit: int = 250) -> tuple[list[Path], list[float]]: grouped: dict[str, list[Path]] = {"keep": [], "reject": []} for raw_path, decision in decisions.items(): if decision not in grouped: continue path = Path(raw_path).expanduser() if path.is_file() and path.suffix.casefold() in IMAGE_SUFFIXES: grouped[decision].append(path) kept = sorted(grouped["keep"])[:per_class_limit] rejected = sorted(grouped["reject"])[:per_class_limit] return kept + rejected, [1.0] * len(kept) + [0.0] * len(rejected)
def train_reviewer( root: str | Path, dataset_folder: str | Path, decisions: dict[str, str], *, epochs: int = 8, progress: Progress | None = None,) -> ReviewerTrainingResult: """Train a frame-quality CNN from explicit Keep and Reject review decisions.""" torch, nn = _torch() paths, labels = _labeled_paths(decisions) keep_count = int(sum(labels)) reject_count = len(labels) - keep_count if min(keep_count, reject_count) < 8: raise ValueError("Review at least 8 Keep and 8 Reject frames before training the CNN reviewer.") if progress: progress(f"Loading {len(paths)} reviewed frame(s)…") images = [] valid_labels = [] for path, label in zip(paths, labels): try: images.append(_load_image(path)) valid_labels.append(label) except Exception: continue keep_count = int(sum(valid_labels)) reject_count = len(valid_labels) - keep_count if min(keep_count, reject_count) < 8: raise ValueError("Some reviewed images could not be read; at least 8 valid Keep and Reject frames are needed.") torch.manual_seed(7) inputs = torch.stack(images) targets = torch.tensor(valid_labels, dtype=torch.float32).unsqueeze(1) model = make_reviewer_model() optimizer = torch.optim.Adam(model.parameters(), lr=0.001) loss_fn = nn.BCEWithLogitsLoss() model.train() for epoch in range(max(1, min(int(epochs), 50))): order = torch.randperm(len(inputs)) loss_value = 0.0 batches = 0 for start in range(0, len(order), 16): batch = order[start:start + 16] optimizer.zero_grad() loss = loss_fn(model(inputs[batch]), targets[batch]) loss.backward() optimizer.step() loss_value += float(loss.detach()) batches += 1 if progress: progress(f"CNN reviewer epoch {epoch + 1}/{epochs} · loss {loss_value / max(1, batches):.3f}") checkpoint = reviewer_checkpoint(root, dataset_folder) checkpoint.parent.mkdir(parents=True, exist_ok=True) torch.save({"state_dict": model.state_dict(), "image_size": [128, 72]}, checkpoint) return ReviewerTrainingResult(str(checkpoint), keep_count, reject_count, epochs)
def score_frames(checkpoint: str | Path, folder: str | Path, *, limit: int = 5_000, progress: Progress | None = None) -> list[FrameScore]: """Return review suggestions without modifying the dataset or its decisions.""" torch, _nn = _torch() saved = torch.load(Path(checkpoint), map_location="cpu", weights_only=True) model = make_reviewer_model() model.load_state_dict(saved["state_dict"]) model.eval() paths = image_paths(folder, limit=limit) scores: list[FrameScore] = [] with torch.no_grad(): for index, path in enumerate(paths, 1): try: probability = float(torch.sigmoid(model(_load_image(path).unsqueeze(0))).item()) except Exception: continue suggestion = "keep" if probability >= 0.70 else "reject" if probability <= 0.30 else "review" scores.append(FrameScore(str(path.resolve()), probability, suggestion)) if progress and (index % 100 == 0 or index == len(paths)): progress(f"CNN reviewer scored {index}/{len(paths)} frame(s)…") return scores82 unmodified lines8384858687888982 unmodified lines"resolution", "batch_size", "learning_rate", "gradient_accumulation_steps","dataloader_num_workers", "mixed_precision", "save_every", "preview_steps","training_intensity", "preview_enabled", "preview_every", "preview_prompt","preview_seed",},"flow": {"resolution", "batch_size", "learning_rate", "gradient_accumulation",82 unmodified lines8384858687888982 unmodified lines"resolution", "batch_size", "learning_rate", "gradient_accumulation_steps","dataloader_num_workers", "mixed_precision", "save_every", "preview_steps","training_intensity", "preview_enabled", "preview_every", "preview_prompt","preview_seed", "training_aspect_ratio", "resize_mode",},"flow": {"resolution", "batch_size", "learning_rate", "gradient_accumulation",
10 unmodified lines11121314151624 unmodified lines41424344454610 unmodified lines"ollama_url": "http://localhost:11434","ollama_model": "qwen2.5:1.5b","ollama_chat_max_tokens": 1024,"web_search_enabled": True,"web_link_reading_enabled": True,"command_center_mode": "trainer",24 unmodified lines"ddpm_trainer": "","flow_trainer": "","oasis_trainer": "","preview_generator": "",},}10 unmodified lines111213141516171824 unmodified lines4344454647484910 unmodified lines"ollama_url": "http://localhost:11434","ollama_model": "qwen2.5:1.5b","ollama_chat_max_tokens": 1024,"ollama_chat_response_length": "automatic","ollama_proposed_actions": True,"web_search_enabled": True,"web_link_reading_enabled": True,"command_center_mode": "trainer",24 unmodified lines"ddpm_trainer": "","flow_trainer": "","oasis_trainer": "","wan_video_trainer": "","preview_generator": "",},}
209 unmodified lines21021121221321421521621721817 unmodified lines23623723823924024129 unmodified lines271272273274275276277209 unmodified lines)return locationsdef discover_into_assets(self, assets: "AssetRegistry", *, persist: bool = False) -> list["Asset"]:discovered: list[Asset] = []records = self.discover(asset_registry=assets, refresh_missing=False)for record in records:if not record.exists:continue17 unmodified lines*,asset_registry: "AssetRegistry | None" = None,refresh_missing: bool = True,) -> list[DatasetRecord]:self.load()changed = False29 unmodified linesrecord.exists = Path(record.path).is_dir()if refresh_missing and record.exists and self._needs_refresh(record):self.refresh_async(record.path, source=record.source, location_id=record.location_id)if changed:self.save()return self.sorted_records()209 unmodified lines21021121221321421521621721817 unmodified lines23623723823924024124229 unmodified lines272273274275276277278209 unmodified lines)return locationsdef discover_into_assets(self, assets: "AssetRegistry", *, persist: bool = False, update_cache: bool = True) -> list["Asset"]:discovered: list[Asset] = []records = self.discover(asset_registry=assets, refresh_missing=False, persist=update_cache)for record in records:if not record.exists:continue17 unmodified lines*,asset_registry: "AssetRegistry | None" = None,refresh_missing: bool = True,persist: bool = True,) -> list[DatasetRecord]:self.load()changed = False29 unmodified linesrecord.exists = Path(record.path).is_dir()if refresh_missing and record.exists and self._needs_refresh(record):self.refresh_async(record.path, source=record.source, location_id=record.location_id)if changed and persist:self.save()return self.sorted_records()
1 unmodified line2345675 unmodified lines13141516171815 unmodified lines3435363738397 unmodified lines4748495051525319 unmodified lines73747576777879808182838485868788899091929329 unmodified lines123124125126127128129130131132153 unmodified lines28628728828929029153 unmodified lines3453463473483493503513523533543553563573581 unmodified lineimport jsonimport refrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any5 unmodified linesIMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}@dataclass(frozen=True, slots=True)class ChatGenerationRequest:"""Generation settings recognized from a Command Center message."""15 unmodified linesreference_strength: int | None = Nonereference_image: str = ""has_positive_prompt: bool = False_QUOTED = r'["\u201c\u201d]([^"\u201c\u201d]+)["\u201c\u201d]'7 unmodified lines"""Score whether conversational subject text clearly names a saved model."""def words(value: str) -> list[str]:value = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", " ", value)ignored = {"a", "an", "the", "of", "image", "picture", "model", "ddpm", "flow", "matching", "lora"}return [word for word in re.findall(r"[a-z0-9]+", value.casefold()) if word not in ignored]query_words = words(query)19 unmodified linesThis intentionally requires both a creation verb and the word image/picture soordinary planning requests continue through the regular Command Center planner."""request = " ".join(text.strip().split())if not request or not re.search(r"\b(generate|create|make)\b", request, re.I):return Noneif not re.search(r"\b(image|images|picture|pictures)\b", request, re.I):return Noneprovider_hint = ""provider_match = re.search(r"\b(ddpm|ddim|flow(?:\s+matching)?|lora)\b[\"\u201c\u201d]?(?=\s+(?:image|picture))",request,re.I,)if provider_match:hint = provider_match.group(1).casefold()provider_hint = "ddpm" if hint in {"ddpm", "ddim"} else "flow" if hint.startswith("flow") else "lora"# Support natural phrasing such as "Generate an image of LoRA OrangeCat".lora_subject_match = re.search(rf"\b(?:image|picture)s?\s+of\s+(?:a\s+)?LoRA\s+{_QUOTED}",29 unmodified lines# In promptless commands, a provider suffix is usually part of the saved# model name (for example, "Minecraft Flow"), not prompt prose.if not provider_hint and subject:if re.search(r"\bflow(?:\s+match(?:ing)?)?\s*$", subject, re.I):provider_hint = "flow"elif re.search(r"\bddpm\s*$", subject, re.I):provider_hint = "ddpm"positive_match = re.search(rf"\bpositive\s+prompt(?:\s+of|\s*=|\s*:)?\s*{_QUOTED}",153 unmodified lineslatest_at: strdef generation_model_key(record: GenerationRecord) -> str:"""Keep renamed or duplicated display names separated by model identity."""raw_path = str(record.model_path or "").strip()53 unmodified lineshistory_root = root.resolve() / "data" / "generations"if not history_root.is_dir():return []records = [recordfor metadata_path in history_root.rglob("generation*.json")for record in [GenerationRecord.from_metadata(metadata_path)]if record is not None]records.sort(key=lambda item: item.created_at or item.folder.name, reverse=True)return records[: max(1, int(limit))]def build_generation_plan(1 unmodified line23456785 unmodified lines141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223315 unmodified lines2492502512522532542552562572582597 unmodified lines26726826927027127227327427519 unmodified lines29529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633729 unmodified lines367368369370371372373374375376377378379380153 unmodified lines53453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859953 unmodified lines6536546556566576586596606616626636646656666676686696706716726736746756766776781 unmodified lineimport jsonimport refrom html import unescapefrom dataclasses import dataclassfrom pathlib import Pathfrom typing import Any5 unmodified linesIMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}@dataclass(frozen=True, slots=True)class ImportedLoRAMetadata:"""Portable LoRA-generation settings copied from an image or another app."""prompt: strnegative_prompt: strseed: intsteps: intcfg_scale: float | Nonebase_model_path: strlora_path: strlora_strength: float | Nonesampler: strwidth: int | None = Noneheight: int | None = Nonesampler_note: str = ""def parse_lora_generation_metadata(text: str) -> ImportedLoRAMetadata:"""Parse pasted LoRA metadata without requiring an intermediate JSON file.Browser copy/paste sometimes HTML-escapes JSON (for example `` `` for aspace), so decode those entities before loading it. This intentionallyaccepts only the small, reproducible LoRA schema ADAM understands."""source = str(text or "").strip()# A few sites escape twice when metadata is copied out of a code block.for _ in range(2):decoded = unescape(source)if decoded == source:breaksource = decodedtry:payload = json.loads(source)except (TypeError, ValueError, json.JSONDecodeError):# Some viewers copy a display block rather than strict JSON, omitting# braces, commas, or quotes around values. Recover its named fields.fields: dict[str, Any] = {}for key in ("prompt", "negative_prompt", "seed", "steps", "cfg_scale", "model", "sampler"):match = re.search(rf'["\']?{key}["\']?\s*:\s*(?:["\']([^"\']*)["\']|([^\r\n]+))', source, re.I)if match:fields[key] = (match.group(1) if match.group(1) is not None else match.group(2)).strip().rstrip(",").strip()lora_path_match = re.search(r'["\']?path["\']?\s*:\s*["\']?([^"\',\r\n}\]]+)', source, re.I)strength_match = re.search(r'["\']?strength["\']?\s*:\s*([^,\r\n}\]]+)', source, re.I)if lora_path_match:fields["loras"] = [{"path": lora_path_match.group(1).strip(),"strength": strength_match.group(1).strip() if strength_match else None,}]payload = fieldsif not isinstance(payload, dict):raise ValueError("Metadata must be a JSON object.")# Source apps vary between `width`/`height` and `Width`/`Height`.payload = {str(key).casefold(): value for key, value in payload.items()}def text_value(key: str, *, required: bool = False) -> str:value = payload.get(key, "")if value is None:value = ""if not isinstance(value, str):raise ValueError(f"{key.replace('_', ' ').title()} must be text.")value = value.strip()if required and not value:raise ValueError(f"Metadata is missing {key.replace('_', ' ')}.")return valueloras = payload.get("loras")if not isinstance(loras, list):raise ValueError("Metadata needs a 'loras' list (use [] when no LoRA was used).")if loras and not isinstance(loras[0], dict):raise ValueError("The first LoRA entry must be an object.")lora_path = str(loras[0].get("path", "")).strip() if loras else ""if loras and not lora_path:raise ValueError("The first LoRA entry needs a path.")try:seed = int(payload.get("seed", 0))steps = int(payload.get("steps", 30))except (TypeError, ValueError) as exc:raise ValueError("Seed and steps must be whole numbers.") from exc# Automatic1111-style metadata commonly uses -1 for a fresh random seed.# ADAM uses 0 for the same behavior in generation plans.if seed == -1:seed = 0if not 0 <= seed <= 2_147_483_647 or steps < 1:raise ValueError("Seed or steps is outside ADAM's supported range.")cfg_value = payload.get("cfg_scale")try:cfg_scale = float(cfg_value) if cfg_value is not None else Noneexcept (TypeError, ValueError) as exc:raise ValueError("CFG scale must be a number.") from excstrength_value = loras[0].get("strength") if loras else Nonetry:lora_strength = float(strength_value) if strength_value is not None else Noneexcept (TypeError, ValueError) as exc:raise ValueError("LoRA strength must be a number.") from excdef dimension(key: str) -> int | None:value = payload.get(key)if value is None or value == "":return Nonetry:result = int(value)except (TypeError, ValueError) as exc:raise ValueError(f"{key.title()} must be a whole number.") from excif not 256 <= result <= 2048:raise ValueError(f"{key.title()} must be between 256 and 2048 pixels.")return resultsampler = text_value("sampler") or "DPM++ 2M"supported = {"DPM++ 2M", "DPM++ 2M Karras", "DPM++ 2M SDE", "DPM++ 2M SDE Karras", "DPM++ SDE", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "LMS", "DDIM"}sampler_note = ""if sampler not in supported:normalized = sampler.casefold()replacement = "DPM++ SDE" if "sde" in normalized else "DPM++ 2M" if "2m" in normalized else ""if not replacement:raise ValueError(f"Sampler '{sampler}' is not supported by ADAM's LoRA generator.")sampler_note = f"Sampler '{sampler}' was mapped to '{replacement}' because the connected generator does not support it."sampler = replacementreturn ImportedLoRAMetadata(prompt=text_value("prompt", required=True),negative_prompt=text_value("negative_prompt"),seed=seed,steps=steps,cfg_scale=cfg_scale,base_model_path=text_value("model", required=True),lora_path=lora_path,lora_strength=lora_strength,sampler=sampler,width=dimension("width"),height=dimension("height"),sampler_note=sampler_note,)def parse_pasted_lora_metadata_request(text: str) -> "ChatGenerationRequest | None":"""Recognize copied LoRA metadata as an unambiguous prompt-box command."""source = str(text or "")if not re.search(r'["\']?prompt["\']?\s*:', source, re.I) or not re.search(r'["\']?(?:loras|negative_prompt|sampler)["\']?\s*:', source, re.I):return Nonetry:metadata = parse_lora_generation_metadata(source)except ValueError:return Nonereturn ChatGenerationRequest(prompt=metadata.prompt,subject=Path(metadata.lora_path).stem if metadata.lora_path else "",provider_hint="lora",model_query=Path(metadata.lora_path).stem if metadata.lora_path else "",base_model_query=Path(metadata.base_model_path).stem,negative_prompt=metadata.negative_prompt,steps=metadata.steps,sampler=metadata.sampler,seed=metadata.seed,cfg_scale=metadata.cfg_scale,lora_strength=metadata.lora_strength,width=metadata.width,height=metadata.height,has_positive_prompt=True,is_pasted_metadata=True,metadata_model_path=metadata.lora_path,metadata_base_model_path=metadata.base_model_path,)def parse_plain_generation_metadata(text: str) -> "ChatGenerationRequest | None":"""Read the common CivitAI/A1111 and PixAI copied-text metadata layouts."""source = str(text or "").replace("\r\n", "\n").strip()if not source:return Nonecivitai = re.search(r"\bNegative\s+prompt\s*:", source, re.I)pixai = re.search(r"\b(?:Sampling\s+Steps|Original\s+Prompt)\b", source, re.I)if not civitai and not pixai:return Noneprompt = ""negative = ""if civitai:prompt = source[:civitai.start()].strip(" ,\n")tail = source[civitai.end():]settings = re.search(r"\b(?:Steps|Size)\s*:", tail, re.I)negative = tail[:settings.start()].strip(" ,\n") if settings else tail.strip(" ,\n")else:original = re.search(r"\bOriginal\s+Prompt\s*\n+(.+?)(?=\n+\s*Size\s*\n)", source, re.I | re.S)prompt = (original.group(1) if original else source.split("\n\n", 1)[0]).strip(" ,\n")negative_match = re.search(r"\n\s*Negative\s*\n+(.+?)(?=\n\s*(?:Prompt\s+Helper|#|$))", source, re.I | re.S)negative = negative_match.group(1).strip(" ,\n") if negative_match else ""def number(pattern: str, kind):match = re.search(pattern, source, re.I)return kind(match.group(1)) if match else Nonesteps = number(r"\b(?:Sampling\s+)?Steps\s*:?\s*(\d+)", int)cfg = number(r"\bCFG\s*(?:Scale)?\s*:?\s*(\d+(?:\.\d+)?)", float)seed = number(r"\bSeed\s*:?\s*(-?\d+)", int)if seed == -1:seed = 0size = re.search(r"\bSize\s*:?\s*(\d+)\s*[x×]\s*(\d+)", source, re.I)sampler_match = re.search(r"\b(?:Sampling\s+Method|Sampler)\s*:?\s*([^\n,]+)", source, re.I)sampler = sampler_match.group(1).strip() if sampler_match else ""if sampler:folded = sampler.casefold()sampler = next((name for name in ("DPM++ 2M SDE Karras", "DPM++ 2M SDE", "DPM++ 2M Karras", "DPM++ SDE Karras", "DPM++ SDE", "DPM++ 2M") if name.casefold() in folded), sampler)loras = re.findall(r"<lora:([^:>]+)(?::([\d.]+))?>", prompt, re.I)if loras:prompt = re.sub(r"\s*<lora:[^>]+>", "", prompt, flags=re.I).strip(" ,")return ChatGenerationRequest(prompt=prompt, provider_hint="lora", model_query=loras[0][0].strip() if len(loras) == 1 else "",negative_prompt=negative, steps=steps, seed=seed, sampler=sampler, cfg_scale=cfg,lora_strength=float(loras[0][1]) if len(loras) == 1 and loras[0][1] else None,width=int(size.group(1)) if size else None, height=int(size.group(2)) if size else None,has_positive_prompt=True, is_pasted_metadata=True,)@dataclass(frozen=True, slots=True)class ChatGenerationRequest:"""Generation settings recognized from a Command Center message."""15 unmodified linesreference_strength: int | None = Nonereference_image: str = ""has_positive_prompt: bool = Falseis_pasted_metadata: bool = Falsemetadata_model_path: str = ""metadata_base_model_path: str = ""width: int | None = Noneheight: int | None = None_QUOTED = r'["\u201c\u201d]([^"\u201c\u201d]+)["\u201c\u201d]'7 unmodified lines"""Score whether conversational subject text clearly names a saved model."""def words(value: str) -> list[str]:value = re.sub(r"(?<=[a-z0-9])(?=[A-Z])", " ", value)value = re.sub(r"\bpixel\s+row\b", " ", value, flags=re.I)value = re.sub(r"\binr\s*flow\b", " ", value, flags=re.I)ignored = {"a", "an", "the", "of", "image", "picture", "model", "ddpm", "flow", "matching", "lora", "inr"}return [word for word in re.findall(r"[a-z0-9]+", value.casefold()) if word not in ignored]query_words = words(query)19 unmodified linesThis intentionally requires both a creation verb and the word image/picture soordinary planning requests continue through the regular Command Center planner."""pasted_metadata = parse_pasted_lora_metadata_request(text)if pasted_metadata is not None:return pasted_metadataplain_metadata = parse_plain_generation_metadata(text)if plain_metadata is not None:return plain_metadatarequest = " ".join(text.strip().split())# Do not treat any request that happens to contain both words as an image# generation command. Dataset requests commonly say things such as# "image mode" and "generate captions"; those must continue to the# regular planner (and, in particular, the video dataset collector).# Require the creation verb to directly introduce the image noun instead.generation_command = re.compile(r"\b(?:generate|create|make)\s+"r"(?:(?:an?|the|\d+)\s+)?"r"(?:[\"\u201c\u201d]?(?:ddpm|ddim|inr\s*flow|flow(?:\s+matching)?|pixel\s*row|lora)[\"\u201c\u201d]?\s+)?"r"(?:images?|pictures?)\b",re.I,)if not request or not generation_command.search(request):return Noneprovider_hint = ""provider_match = re.search(r"\b(ddpm|ddim|inr\s*flow|flow(?:\s+matching)?|pixel\s*row|lora)\b[\"\u201c\u201d]?(?=\s+(?:image|picture))",request,re.I,)if provider_match:hint = provider_match.group(1).casefold()provider_hint = ("ddpm" if hint in {"ddpm", "ddim"}else "inrflow" if hint.replace(" ", "") == "inrflow"else "flow" if hint.startswith("flow")else "pixelrow" if hint.replace(" ", "") == "pixelrow"else "lora")# Support natural phrasing such as "Generate an image of LoRA OrangeCat".lora_subject_match = re.search(rf"\b(?:image|picture)s?\s+of\s+(?:a\s+)?LoRA\s+{_QUOTED}",29 unmodified lines# In promptless commands, a provider suffix is usually part of the saved# model name (for example, "Minecraft Flow"), not prompt prose.if not provider_hint and subject:if re.search(r"\binr\s*flow\s*$", subject, re.I):provider_hint = "inrflow"elif re.search(r"\bflow(?:\s+match(?:ing)?)?\s*$", subject, re.I):provider_hint = "flow"elif re.search(r"\bddpm\s*$", subject, re.I):provider_hint = "ddpm"elif re.search(r"\bpixel\s*row\s*$", subject, re.I):provider_hint = "pixelrow"positive_match = re.search(rf"\bpositive\s+prompt(?:\s+of|\s*=|\s*:)?\s*{_QUOTED}",153 unmodified lineslatest_at: str@dataclass(frozen=True, slots=True)class GenerationProviderFolder:"""A generator-centered view over the on-disk generation folders.Output is stored as ``generations/<generator>/<model>/...``. This viewintentionally exposes that first directory level in the UI, keeping allimages made by one generator together without moving any user files."""key: strprovider_id: strprovider_name: strrecords: tuple[GenerationRecord, ...]model_count: intimage_count: intlatest_at: strdef generation_provider_key(record: GenerationRecord) -> str:"""Return the stable key for the generator directory containing a batch."""provider_id = str(record.provider_id or "").strip()if not provider_id:# Metadata written by older versions may not have a provider id. Its# parent is still the generator directory in the current file layout.provider_id = record.folder.parent.namereturn provider_id.casefold()def group_generation_providers(records: list[GenerationRecord],) -> list[GenerationProviderFolder]:"""Build newest-first generator folders from existing generation records."""grouped: dict[str, list[GenerationRecord]] = {}for record in records:grouped.setdefault(generation_provider_key(record), []).append(record)folders: list[GenerationProviderFolder] = []for key, provider_records in grouped.items():newest_first = sorted(provider_records,key=lambda item: item.created_at or item.folder.name,reverse=True,)latest = newest_first[0]provider_id = str(latest.provider_id or latest.folder.parent.name)provider_name = str(latest.provider_name or provider_id)folders.append(GenerationProviderFolder(key=key,provider_id=provider_id,provider_name=provider_name,records=tuple(newest_first),model_count=len({generation_model_key(record) for record in newest_first}),image_count=sum(len(record.images) for record in newest_first),latest_at=latest.created_at,))folders.sort(key=lambda item: (item.latest_at, item.provider_name.casefold()), reverse=True)return foldersdef generation_model_key(record: GenerationRecord) -> str:"""Keep renamed or duplicated display names separated by model identity."""raw_path = str(record.model_path or "").strip()53 unmodified lineshistory_root = root.resolve() / "data" / "generations"if not history_root.is_dir():return []# History can grow into thousands of image batches. Sort inexpensive file# metadata first, then decode only the newest records requested by the UI.# This keeps a page refresh responsive without moving or rewriting history.try:metadata_paths = sorted(history_root.rglob("generation*.json"),key=lambda path: path.stat().st_mtime,reverse=True,)except OSError:metadata_paths = list(history_root.rglob("generation*.json"))records = []for metadata_path in metadata_paths:record = GenerationRecord.from_metadata(metadata_path)if record is not None:records.append(record)if len(records) >= max(1, int(limit)):breakrecords.sort(key=lambda item: item.created_at or item.folder.name, reverse=True)return recordsdef build_generation_plan(
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200"""Evidence-led summaries for ADAM's saved training and generation history.
This module intentionally stays independent of the Qt interface so its advice canbe tested and reused by a future remote surface. It does not assess a model'sabsolute quality: it identifies useful follow-up experiments from the evidenceADAM has recorded locally."""from __future__ import annotations
import jsonfrom dataclasses import dataclassfrom pathlib import Path
from adam.experiment_tracker import ExperimentRunfrom adam.generations import GenerationRecordfrom adam.image_preferences import PreferenceProfile
@dataclass(frozen=True, slots=True)class ModelIntelligence: key: str model_name: str architecture: str runs: tuple[ExperimentRun, ...] generations: tuple[GenerationRecord, ...] rated_images: int positive_ratings: int rejected_images: int state: str diagnosis: str recommendation: str recommended_epochs: int
def _normalized(value: str) -> str: return " ".join(str(value or "").casefold().split())
def _paths_match(left: str, right: str, cache: dict[str, Path] | None = None) -> bool: if not left or not right: return False try: cache = cache if cache is not None else {} for value in (left, right): if value not in cache: cache[value] = Path(value).expanduser().resolve() left_path, right_path = cache[left], cache[right] return left_path == right_path or left_path in right_path.parents or right_path in left_path.parents except OSError: return _normalized(left) == _normalized(right)
def _generation_matches(run: ExperimentRun, record: GenerationRecord, cache: dict[str, Path] | None = None) -> bool: if _paths_match(run.output_folder, record.model_path, cache): return True if any(_paths_match(path, record.model_path, cache) for path in run.checkpoint_paths): return True return _normalized(run.model_name) == _normalized(record.model_name)
def _ratings(records: tuple[GenerationRecord, ...], root: Path | None = None) -> tuple[int, int, int]: rated = positive = rejected = 0 seen: set[str] = set() preferences_by_model: dict[tuple[str, str], PreferenceProfile] = {} image_keys: dict[Path, str] = {} for record in records: preferences = None if root: key = (record.provider_id, record.model_path) if key not in preferences_by_model: preferences_by_model[key] = PreferenceProfile(root, record.provider_id, record.model_name, record.model_path) preferences = preferences_by_model[key] for image in record.images: if image not in image_keys: image_keys[image] = str(image.expanduser().resolve()) image_key = image_keys[image] if image_key in seen: continue seen.add(image_key) evaluation = record.image_evaluations.get(image_key, {}) saved_rating = preferences.rating_for(image) if preferences else None rating = saved_rating.rating if saved_rating else str(evaluation.get("rating", "")).casefold() # Preference ratings are persisted separately today. The evaluator # score still counts as review evidence when it is available. score = evaluation.get("score") if rating or isinstance(score, (int, float)): rated += 1 if rating in {"favorite", "keep"} or (isinstance(score, (int, float)) and score >= 0.70): positive += 1 if rating == "reject" or (isinstance(score, (int, float)) and score <= 0.35): rejected += 1 return rated, positive, rejected
def _diagnose( runs: tuple[ExperimentRun, ...], generations: tuple[GenerationRecord, ...], rated: int, positive: int, rejected: int,) -> tuple[str, str, str, int]: latest = runs[0] finished = [run for run in runs if run.status.casefold() == "finished"] epoch_budget = max(1, latest.epochs) previous = runs[1] if len(runs) > 1 else None
if not finished: return ( "Needs a completed run", "ADAM has not recorded a finished training run for this model yet, so it cannot judge training behavior.", "Finish one run and generate a small, fixed-prompt test batch before changing several settings at once.", epoch_budget, ) if rated == 0: return ( "Needs visual review", "Training history exists, but there are no scored test generations linked to this model. Loss alone cannot tell ADAM which checkpoint you prefer.", "Generate 4–8 images with one repeatable prompt and seed, then rate the results in Generations before starting a follow-up.", epoch_budget, ) if rejected > positive and rated >= 3: return ( "Review data or settings", f"{rejected} of {rated} reviewed generated images were rejected or scored low. More epochs by themselves are unlikely to be the best first change.", "Review dataset variety, captions, and the fixed-prompt gallery. Keep the epoch count similar for the next controlled test, changing only one training setting.", epoch_budget, ) if previous and latest.final_loss is not None and previous.final_loss is not None: loss_change = latest.final_loss - previous.final_loss if abs(loss_change) <= max(0.0001, abs(previous.final_loss) * 0.03): return ( "Likely plateau", "The last two recorded losses changed very little. That is a plateau signal, not proof that the model has stopped improving visually.", "Run a shorter follow-up (about 25% fewer epochs) with a lower learning rate or improved data; compare it using the same evaluation prompt and seed.", max(1, round(epoch_budget * 0.75)), ) if positive >= max(2, rejected * 2): return ( "Promising", f"{positive} reviewed generated images look positive versus {rejected} rejected. The model has enough signal for a focused continuation test.", "Preserve this run as a baseline. Try a modest continuation of about 25% more epochs, then compare the same prompt-and-seed gallery before committing further.", max(epoch_budget + 1, round(epoch_budget * 1.25)), ) return ( "Gather one more comparison", "ADAM has mixed review evidence. A single outcome can be affected by prompt choice, seed, or dataset coverage.", "Make another small fixed-prompt generation batch, rate it, and change only one setting in the next run so the result is interpretable.", epoch_budget, )
def build_model_intelligence( runs: list[ExperimentRun], generations: list[GenerationRecord], *, root: Path | None = None,) -> list[ModelIntelligence]: """Group local records into newest-first, model-centered intelligence cards.""" grouped: dict[tuple[str, str], list[ExperimentRun]] = {} for run in runs: key = (_normalized(run.model_name), _normalized(run.model_architecture)) if key[0]: grouped.setdefault(key, []).append(run)
profiles: list[ModelIntelligence] = [] path_cache: dict[str, Path] = {} for (name_key, architecture_key), raw_runs in grouped.items(): model_runs = tuple(sorted(raw_runs, key=lambda run: run.timestamp, reverse=True)) model_generations = tuple( record for record in generations if any(_generation_matches(run, record, path_cache) for run in model_runs) ) rated, positive, rejected = _ratings(model_generations, root) state, diagnosis, recommendation, epochs = _diagnose( model_runs, model_generations, rated, positive, rejected ) profiles.append(ModelIntelligence( key=f"{architecture_key}:{name_key}", model_name=model_runs[0].model_name, architecture=model_runs[0].model_architecture, runs=model_runs, generations=model_generations, rated_images=rated, positive_ratings=positive, rejected_images=rejected, state=state, diagnosis=diagnosis, recommendation=recommendation, recommended_epochs=epochs, )) return sorted(profiles, key=lambda profile: profile.runs[0].timestamp, reverse=True)
def recommended_training_request(profile: ModelIntelligence) -> str: """Create an approval-aware follow-up request using the latest run as a baseline.""" run = profile.runs[0] options = { key: value for key, value in run.settings.items() if key not in {"dataset_dir", "model_name", "epochs", "output_dir", "resume_from"} } return ( f"From the {run.dataset_name or run.dataset_path} dataset, train a " f"{run.model_architecture.upper()} model for {profile.recommended_epochs} epochs. " f"Name the model {run.model_name} Follow-up. " "[ADAM_TRAINING_OPTIONS:" + json.dumps(options, sort_keys=True) + "] " "[ADAM_TRAINER:" + run.model_architecture + "]" )72 unmodified lines7374757677787995 unmodified lines1751761771781791801812 unmodified lines1841851861871881894 unmodified lines194195196197198199200201202177 unmodified lines38038138238338438572 unmodified linespreview_state = {"epoch": 0, "path": ""}last_progress_emit = {"time": 0.0, "overall": -1, "message": ""}progress_samples: list[dict[str, float]] = []def on_progress(percent: int, message: str, step_index: int = index, **details: Any) -> None:overall = int(((step_index + percent / 100) / total_steps) * 100)95 unmodified lines@staticmethoddef _estimate_step_eta(details: dict[str, Any],samples: list[dict[str, float]],now: float,) -> dict[str, Any]:"""Estimate remaining runtime from real step cadence instead of percent alone."""2 unmodified linesunit = str(details.get("unit", "step") or "step")epoch = _safe_int(details.get("epoch"))total_epochs = _safe_int(details.get("total_epochs"))if (not current or not total) and epoch and total_epochs:current, total, unit = epoch, total_epochs, "epoch"payload: dict[str, Any] = {4 unmodified linesif not current or not total or current >= total:return payloadlast = samples[-1] if samples else Noneif last and current <= last["current"]:return payloadsamples.append({"time": now, "current": float(current)})del samples[:-25]if len(samples) < 2:return payload177 unmodified linesstep = job.plan.steps[job.current_step]if step.tool_id != "ddpm_trainer":raise ValueError("Safe epoch-boundary adjustment currently supports DDPM training.")allowed = {"batch_size", "training_intensity", "gradient_accumulation_steps"}cleaned = {key: int(value) for key, value in updates.items() if key in allowed}if not cleaned or not 1 <= cleaned.get("batch_size", 1) <= 64 \72 unmodified lines7374757677787995 unmodified lines1751761771781791801812 unmodified lines1841851861871881891901914 unmodified lines196197198199200201202203204205206207208209210211212213177 unmodified lines39139239339439539639739839940072 unmodified linespreview_state = {"epoch": 0, "path": ""}last_progress_emit = {"time": 0.0, "overall": -1, "message": ""}progress_samples: list[dict[str, Any]] = []def on_progress(percent: int, message: str, step_index: int = index, **details: Any) -> None:overall = int(((step_index + percent / 100) / total_steps) * 100)95 unmodified lines@staticmethoddef _estimate_step_eta(details: dict[str, Any],samples: list[dict[str, Any]],now: float,) -> dict[str, Any]:"""Estimate remaining runtime from real step cadence instead of percent alone."""2 unmodified linesunit = str(details.get("unit", "step") or "step")epoch = _safe_int(details.get("epoch"))total_epochs = _safe_int(details.get("total_epochs"))if details.get("reset_eta"):samples.clear()if (not current or not total) and epoch and total_epochs:current, total, unit = epoch, total_epochs, "epoch"payload: dict[str, Any] = {4 unmodified linesif not current or not total or current >= total:return payloadlast = samples[-1] if samples else Noneif last and (int(last.get("total", total)) != totalor str(last.get("unit", unit)) != unitor current < last["current"]):# A different tqdm operation or a restarted counter needs a fresh# cadence; carrying the old rate creates wildly incorrect ETAs.samples.clear()last = Noneif last and current <= last["current"]:return payloadsamples.append({"time": now, "current": float(current), "total": float(total), "unit": unit})del samples[:-25]if len(samples) < 2:return payload177 unmodified linesstep = job.plan.steps[job.current_step]if step.tool_id != "ddpm_trainer":raise ValueError("Safe epoch-boundary adjustment currently supports DDPM training.")if step.arguments.get("progressive_stages"):raise ValueError("Change batch settings before starting a progressive run; each stage manages its own saved handoff.")allowed = {"batch_size", "training_intensity", "gradient_accumulation_steps"}cleaned = {key: int(value) for key, value in updates.items() if key in allowed}if not cleaned or not 1 <= cleaned.get("batch_size", 1) <= 64 \
236 unmodified lines237238239240241242243236 unmodified lines"demo": False,}defaults.update(tool)defaults["arguments"] = list(defaults.get("arguments") or [*core_arguments, *list(schema)])defaults["required_arguments"] = list(defaults.get("required_arguments") or [])return defaults236 unmodified lines237238239240241242243244245236 unmodified lines"demo": False,}defaults.update(tool)defaults["arguments"] = list(dict.fromkeys(defaults.get("arguments") or [*core_arguments, *list(schema)]))defaults["required_arguments"] = list(defaults.get("required_arguments") or [])return defaults
15 unmodified lines1617181920212215 unmodified lines}TRAINING_SETTINGS = {"resolution": {"label": "Resolution", "type": "choice", "options": [64, 128, 256, 384, 512], "default": 128, "group": "Basic"},"batch_size": {"label": "Batch size", "type": "int", "default": 1, "min": 1, "max": 64, "group": "Basic"},"learning_rate": {"label": "Learning rate", "type": "float", "default": 0.0001, "min": 0.0000001, "max": 0.1, "decimals": 7, "step": 0.00005, "group": "Optimization"},"gradient_accumulation_steps": {"label": "Gradient accumulation", "type": "int", "default": 1, "min": 1, "max": 64, "group": "Optimization"},15 unmodified lines16171819202122232415 unmodified lines}TRAINING_SETTINGS = {"resolution": {"label": "Longest edge", "type": "choice", "options": [64, 128, 256, 384, 512], "default": 128, "group": "Basic", "description": "The longest side of the native training canvas."},"training_aspect_ratio": {"label": "Training aspect ratio", "type": "choice", "options": ["Dataset (Auto)", "1:1 (Square)", "16:9 (Widescreen)", "9:16 (Portrait)", "4:3 (Classic)", "3:4 (Portrait Classic)", "3:2 (Photo)", "2:3 (Portrait Photo)"], "default": "Dataset (Auto)", "group": "Basic", "description": "Dataset Auto uses the median source-image aspect ratio; 256 with 16:9 creates a 256x144 model."},"resize_mode": {"label": "Image fitting", "type": "choice", "options": ["fit", "fill", "stretch"], "default": "fit", "group": "Dataset", "description": "fit preserves the entire image and edge-pads only when needed; fill crops; stretch changes proportions."},"batch_size": {"label": "Batch size", "type": "int", "default": 1, "min": 1, "max": 64, "group": "Basic"},"learning_rate": {"label": "Learning rate", "type": "float", "default": 0.0001, "min": 0.0000001, "max": 0.1, "decimals": 7, "step": 0.00005, "group": "Optimization"},"gradient_accumulation_steps": {"label": "Gradient accumulation", "type": "int", "default": 1, "min": 1, "max": 64, "group": "Optimization"},
36 unmodified lines37383940414236 unmodified lines"steps": {"label": "ODE steps", "type": "int", "default": 20, "min": 1, "max": 200, "group": "Generation"},"sampler": {"label": "Method", "type": "choice", "options": ["Heun", "Euler"], "default": "Heun", "group": "Generation"},"aspect_ratio": {"label": "Aspect ratio", "type": "choice", "options": ["1:1 (Square)", "4:3 (Landscape)", "3:4 (Portrait)", "3:2 (Landscape)", "2:3 (Portrait)", "16:9 (Widescreen)", "9:16 (Vertical)"], "default": "1:1 (Square)", "group": "Generation"},"seed": {"label": "Seed", "type": "int", "default": 0, "min": 0, "max": 2147483647, "group": "Generation"},"preview_interval": {"label": "Steps per preview", "type": "int", "default": 0, "min": 0, "max": 500, "group": "Preview"},"smart_generation": {"label": "Smart Generation", "type": "bool", "default": False, "group": "Smart Generation"},36 unmodified lines373839404142434436 unmodified lines"steps": {"label": "ODE steps", "type": "int", "default": 20, "min": 1, "max": 200, "group": "Generation"},"sampler": {"label": "Method", "type": "choice", "options": ["Heun", "Euler"], "default": "Heun", "group": "Generation"},"aspect_ratio": {"label": "Aspect ratio", "type": "choice", "options": ["1:1 (Square)", "4:3 (Landscape)", "3:4 (Portrait)", "3:2 (Landscape)", "2:3 (Portrait)", "16:9 (Widescreen)", "9:16 (Vertical)"], "default": "1:1 (Square)", "group": "Generation"},"width": {"label": "Width", "type": "int", "default": 0, "min": 0, "max": 2048, "group": "Generation"},"height": {"label": "Height", "type": "int", "default": 0, "min": 0, "max": 2048, "group": "Generation"},"seed": {"label": "Seed", "type": "int", "default": 0, "min": 0, "max": 2147483647, "group": "Generation"},"preview_interval": {"label": "Steps per preview", "type": "int", "default": 0, "min": 0, "max": 500, "group": "Preview"},"smart_generation": {"label": "Smart Generation", "type": "bool", "default": False, "group": "Smart Generation"},
12"""ADAM-sized INRFlow image model plugin."""
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106from __future__ import annotations
import jsonimport refrom pathlib import Pathfrom typing import Any
import torchfrom PIL import Image
from adam.executor import ToolExecutionError
from .model import MODEL_FORMAT_VERSION, INRFlowConfig, INRFlowModel
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}FINAL_CHECKPOINT_NAME = "inrflow_model.pt"CONFIG_NAME = "inrflow_config.json"
def safe_model_name(value: str) -> str: name = re.sub(r"\s+", " ", value.strip()) if not name or len(name) > 96 or any(character in name for character in '<>:"/\\|?*\x00'): raise ToolExecutionError( "Choose a short INRFlow model name without reserved filename characters." ) return name
def ensure_below(path: Path, root: Path, label: str) -> Path: resolved = path.expanduser().resolve() try: resolved.relative_to(root.expanduser().resolve()) except ValueError as exc: raise ToolExecutionError(f"{label} must stay inside {root.resolve()}.") from exc return resolved
def image_files(folder: Path) -> list[Path]: try: return sorted( path for path in folder.rglob("*") if path.is_file() and path.suffix.casefold() in IMAGE_EXTENSIONS ) except OSError: return []
def resolve_checkpoint(path: Path) -> Path: candidate = path.expanduser().resolve() if candidate.is_dir(): candidate = candidate / FINAL_CHECKPOINT_NAME if not candidate.is_file(): raise ToolExecutionError( "The selected INRFlow checkpoint does not exist or is incomplete." ) return candidate
def load_checkpoint( path: Path, device: torch.device, *, prefer_ema: bool = True,) -> tuple[INRFlowModel, dict[str, Any]]: checkpoint_path = resolve_checkpoint(path) try: payload = torch.load(checkpoint_path, map_location=device, weights_only=True) except (OSError, RuntimeError, ValueError, TypeError) as exc: raise ToolExecutionError(f"Could not load the INRFlow checkpoint: {exc}") from exc if not isinstance(payload, dict) or "model_state" not in payload or "config" not in payload: raise ToolExecutionError("The selected file is not a valid INRFlow checkpoint.") if int(payload.get("format_version", 0)) != MODEL_FORMAT_VERSION: raise ToolExecutionError("This INRFlow checkpoint uses an unsupported format version.") try: config = INRFlowConfig.from_dict(dict(payload["config"])) model = INRFlowModel(config).to(device) state = payload.get("ema_state") if prefer_ema else None model.load_state_dict(state if isinstance(state, dict) else payload["model_state"], strict=True) except (KeyError, TypeError, ValueError, RuntimeError) as exc: raise ToolExecutionError(f"The INRFlow checkpoint is incompatible: {exc}") from exc return model, payload
def save_image(image: torch.Tensor, path: Path) -> None: pixels = ( image.detach() .float() .cpu() .clamp(-1.0, 1.0) .add(1.0) .mul(127.5) .round() .to(torch.uint8) .numpy() ) path.parent.mkdir(parents=True, exist_ok=True) Image.fromarray(pixels, mode="RGB").save(path, format="PNG")
def write_json(path: Path, payload: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(payload, indent=2), encoding="utf-8") temporary.replace(path)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305from __future__ import annotations
import randomfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
import torch
from adam.executor import ToolExecutionErrorfrom adam.generations import generation_metadata_path, generation_output_folderfrom adam.image_preferences import GenerationPreferenceEvaluator, PreferenceProfile
from .common import ensure_below, load_checkpoint, safe_model_name, save_image, write_jsonfrom .model import sample_image
def generate( context, model_name: str, model_path: str, prompt: str, image_count: int, steps: int, seed: int, sampler: str, aspect_ratio: str, output_resolution: str = "Native", noise_scale: float = 1.0, query_chunk_size: int = 1024, preview_interval: int = 5, smart_generation: bool = False, smart_wanted_results: int = 8, smart_max_candidates: int = 32, smart_min_score: float = 0.7, smart_mode: str = "threshold", smart_keep_rejected: bool = True,) -> dict[str, Any]: """Generate images by integrating the learned ambient-space velocity field.""" name = safe_model_name(model_name) model_root = ( context.root.resolve() / "data" / "model_plugin_outputs" / "inrflow" ).resolve() selected = ensure_below(Path(model_path), model_root, "INRFlow model") if not selected.exists(): raise ToolExecutionError("The selected INRFlow model no longer exists.") count = int(image_count) step_count = int(steps) if not 1 <= count <= 48: raise ToolExecutionError("INRFlow image count must be between 1 and 48.") if not 2 <= step_count <= 200: raise ToolExecutionError("INRFlow ODE steps must be between 2 and 200.") method = sampler.strip().title() if method not in {"Euler", "Heun"}: raise ToolExecutionError("INRFlow supports the Euler and Heun ODE methods.") if aspect_ratio != "1:1 (Coordinate Field)": raise ToolExecutionError("INRFlow currently generates square coordinate fields.") if not 0.1 <= float(noise_scale) <= 2.0: raise ToolExecutionError("INRFlow starting noise scale must be between 0.1 and 2.0.") if int(query_chunk_size) not in {256, 512, 1024, 2048, 4096}: raise ToolExecutionError("Choose a supported INRFlow query chunk size.") if not 0 <= int(preview_interval) <= step_count: raise ToolExecutionError("Preview interval must be between 0 and the ODE step count.") if len(prompt) > 500: raise ToolExecutionError("The INRFlow creative note must be 500 characters or shorter.")
smart_enabled = bool(smart_generation) wanted_results = int(smart_wanted_results or count) max_candidates = int(smart_max_candidates or count) threshold = float(smart_min_score) top_n_mode = str(smart_mode).casefold() == "top_n" if smart_enabled: if not 1 <= wanted_results <= 48: raise ToolExecutionError("Wanted Smart Generation results must be between 1 and 48.") if not wanted_results <= max_candidates <= 256: raise ToolExecutionError( "Maximum Smart Generation candidates must be between wanted results and 256." ) if not 0.0 <= threshold <= 1.0: raise ToolExecutionError("Minimum Smart Generation score must be between 0 and 1.") if str(smart_mode).casefold() not in {"threshold", "top_n"}: raise ToolExecutionError("Smart Generation mode must be threshold or top_n.") count = wanted_results
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model, checkpoint = load_checkpoint(selected, device, prefer_ema=True) if str(output_resolution) == "Native": resolution = model.config.resolution else: try: resolution = int(output_resolution) except (TypeError, ValueError) as exc: raise ToolExecutionError("Choose Native or a supported INRFlow output resolution.") from exc if resolution not in {32, 64, 128, 256}: raise ToolExecutionError("INRFlow output resolution must be 32, 64, 128, or 256.") if resolution % model.config.patch_size: raise ToolExecutionError( "That output resolution is not divisible by this model's spatial latent patch." ) if resolution != model.config.resolution: context.log( f"Querying the learned coordinate field at {resolution}px; it was trained at " f"{model.config.resolution}px, so this is resolution extrapolation." )
generated_total = max_candidates if smart_enabled else count base_seed = int(seed) if base_seed <= 0: base_seed = random.SystemRandom().randint( 1, 2_147_483_647 - generated_total ) if base_seed + generated_total - 1 > 2_147_483_647: raise ToolExecutionError("The INRFlow seed is too large for this image count.")
output = generation_output_folder(context.root, context.tool.id, name) timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") image_paths: list[str] = [] selected_paths: list[str] = [] image_evaluations: dict[str, dict[str, object]] = {} profile = ( PreferenceProfile(context.root, context.tool.id, name, str(selected)) if smart_enabled else None ) evaluator = GenerationPreferenceEvaluator(context.root) if smart_enabled else None context.log( f"Loaded {name}: trained at {model.config.resolution}px, generating at " f"{resolution}px with {method} on {device}." ) context.log( "INRFlow is unconditional; the creative note is saved with the result but is not a text prompt." )
try: for image_index in range(generated_total): context.checkpoint() current_seed = base_seed + image_index generator = torch.Generator(device=device) generator.manual_seed(current_seed) live_path = output / ".live" / context.job_id / f"image_{image_index + 1:03d}.png"
def on_step(done: int, total: int, image: torch.Tensor) -> None: context.checkpoint() overall = (image_index + done / max(1, total)) / generated_total context.progress( max(1, min(99, round(overall * 100))), f"Image {image_index + 1} of {generated_total} · ODE step {done} of {total}", current=done, total=total, image_index=image_index, image_count=generated_total, unit="step", ) if int(preview_interval) > 0 and ( done % int(preview_interval) == 0 or done == total ): save_image(image, live_path) context.preview( live_path, kind="generation", current=done, total=total, image_index=image_index, image_count=generated_total, seed=current_seed, steps=step_count, )
image = sample_image( model, resolution=resolution, steps=step_count, method=method, noise_scale=float(noise_scale), query_chunk_size=int(query_chunk_size), generator=generator, step_callback=on_step, ) destination = output / ( f"{timestamp}_{context.job_id}_INRFlow_{method}_seed_{current_seed}_" f"{resolution}px.png" ) save_image(image, destination) image_paths.append(str(destination)) if smart_enabled and profile is not None and evaluator is not None: score = evaluator.score( profile, [destination], keep_threshold=threshold, reject_threshold=profile.reject_threshold, )[0] image_evaluations[str(destination.resolve())] = { "score": score.score, "confidence": score.confidence, "category": score.category, "reason": score.reason, } if not top_n_mode and score.score is not None and score.score >= threshold: selected_paths.append(str(destination)) if len(selected_paths) >= wanted_results: break except torch.cuda.OutOfMemoryError as exc: if device.type == "cuda": torch.cuda.empty_cache() raise ToolExecutionError( "INRFlow ran out of VRAM while generating. Lower output resolution or query chunk size." ) from exc finally: if evaluator is not None: evaluator.vision.unload()
if smart_enabled and top_n_mode: ranked = sorted( image_paths, key=lambda path: float( image_evaluations.get(str(Path(path).resolve()), {}).get("score") or -1.0 ), reverse=True, ) selected_paths = ranked[:wanted_results] if smart_enabled: chosen = set(selected_paths) ordered_images = [*selected_paths, *[path for path in image_paths if path not in chosen]] saved_images = ordered_images if bool(smart_keep_rejected) else selected_paths else: ordered_images = image_paths saved_images = image_paths
metadata = { "version": 1, "provider_id": context.tool.id, "provider_name": context.tool.name, "model_name": name, "model_path": str(selected), "model_type": "inrflow", "architecture": "inrflow_ambient_space", "prompt": prompt.strip(), "prompt_behavior": "label_only", "seed": base_seed, "image_seeds": [base_seed + index for index in range(len(image_paths))], "image_count": len(saved_images), "steps": step_count, "sampler": method, "aspect_ratio": aspect_ratio, "training_resolution": model.config.resolution, "output_resolution": resolution, "noise_scale": float(noise_scale), "query_chunk_size": int(query_chunk_size), "preview_interval": int(preview_interval), "images": saved_images, "image_evaluations": image_evaluations, "checkpoint_epoch": int(checkpoint.get("completed_epochs", 0) or 0), "used_ema_weights": isinstance(checkpoint.get("ema_state"), dict), "uses_pretrained_compressor": False, "smart_generation": { "enabled": smart_enabled, "mode": str(smart_mode), "wanted_results": wanted_results if smart_enabled else count, "maximum_candidates": max_candidates if smart_enabled else count, "minimum_score": threshold, "selected_count": len(selected_paths) if smart_enabled else count, "candidate_count": len(image_paths), "profile_id": profile.id if profile else "", "keep_rejected_candidates": bool(smart_keep_rejected), }, "created_at": datetime.now(timezone.utc).isoformat(), } write_json(generation_metadata_path(output, timestamp, context.job_id), metadata) live_folder = output / ".live" / context.job_id if live_folder.is_dir(): for path in live_folder.glob("*.png"): try: path.unlink() except OSError: pass try: live_folder.rmdir() live_folder.parent.rmdir() except OSError: pass
if smart_enabled: context.progress( 100, f"Smart Generation selected {len(selected_paths)} of {wanted_results} requested " f"image(s) from {len(image_paths)} candidate(s)", ) else: context.progress(100, f"Generated {count} INRFlow image(s)") return { "output_folder": str(output), "assets": [ { "kind": "generation", "name": f"{name} · {timestamp}", "path": str(output), "trainer": "inrflow", "metadata": { "resolution": resolution, "steps": step_count, "sampler": method, }, } ], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394PLUGIN_ID = "inrflow"
MODEL_INFO = { "name": "INRFlow (Ambient Space)", "version": "0.1", "category": "Image Generation", "description": ( "ADAM-sized INRFlow: coordinate-to-RGB flow matching directly in pixel space, " "with spatial context latents and no pretrained image compressor." ), "architecture": "inrflow_ambient_space", "status": "experimental", "output_type": "image", "capabilities": [ "fresh_training", "resume_training", "image_generation", "smart_generation", "live_preview", "resolution_flexible_generation", ], "input_formats": ["image folder"], "output_formats": ["INRFlow checkpoint", "INRFlow metadata", "PNG preview"], "hardware": {"recommended_vram_gb": 8, "recommended_system_ram_gb": 16}, "vram_behavior": { "scales_with": [ "resolution", "batch_size", "hidden_size", "depth", "query_points", "sampling_steps", ], "estimate": ( "Designed for 64px experiments on 8–12 GB GPUs. At 128px, reduce batch " "size and query points before shrinking the model." ), }, "method_reference": "https://arxiv.org/abs/2412.03791", "reference_implementation": "https://github.com/apple/ml-inrflow",}
TRAINING_SETTINGS = { "resolution": { "label": "Training resolution", "type": "choice", "options": [32, 64, 128, 256], "default": 64, "group": "Basic", "description": "Start at 64px for an architecture comparison on an RTX 3060.", }, "resize_mode": { "label": "Image fitting", "type": "choice", "options": ["fill", "fit", "stretch"], "default": "fill", "group": "Dataset", }, "horizontal_flip": { "label": "Random horizontal flip", "type": "bool", "default": True, "group": "Dataset", }, "batch_size": { "label": "Batch size", "type": "int", "default": 4, "min": 1, "max": 32, "group": "Basic", }, "learning_rate": { "label": "Learning rate", "type": "float", "default": 0.0001, "min": 0.0000001, "max": 0.1, "decimals": 7, "step": 0.00005, "group": "Optimization", }, "weight_decay": { "label": "Weight decay", "type": "float", "default": 0.0, "min": 0.0, "max": 1.0, "decimals": 5, "step": 0.001, "group": "Optimization", "advanced": True, }, "gradient_accumulation_steps": { "label": "Gradient accumulation", "type": "int", "default": 1, "min": 1, "max": 64, "group": "Optimization", }, "workers": { "label": "Loader workers", "type": "int", "default": 0, "min": 0, "max": 16, "group": "Dataset", }, "mixed_precision": { "label": "Precision", "type": "choice", "options": ["fp16", "bf16", "no"], "default": "fp16", "group": "Optimization", }, "patch_size": { "label": "Spatial latent patch", "type": "choice", "options": [4, 8, 16], "default": 8, "group": "INRFlow", "description": "Each spatial context latent attends to the coordinate-value pairs in one patch.", }, "hidden_size": { "label": "Transformer width", "type": "choice", "options": [128, 192, 256, 384], "default": 256, "group": "INRFlow", "advanced": True, }, "depth": { "label": "Transformer layers", "type": "choice", "options": [2, 4, 6, 8], "default": 4, "group": "INRFlow", "advanced": True, }, "num_heads": { "label": "Attention heads", "type": "choice", "options": [4, 8], "default": 8, "group": "INRFlow", "advanced": True, }, "decoder_layers": { "label": "Point decoder layers", "type": "choice", "options": [1, 2], "default": 1, "group": "INRFlow", "advanced": True, }, "fourier_frequencies": { "label": "Coordinate frequencies", "type": "choice", "options": [4, 6, 8, 10], "default": 8, "group": "INRFlow", "advanced": True, }, "query_points": { "label": "Pixel queries per image", "type": "choice", "options": [256, 512, 1024, 2048, 4096], "default": 1024, "group": "INRFlow", "description": "Point-wise subsampling is a defining INRFlow training advantage.", }, "time_sampling": { "label": "Flow-time sampling", "type": "choice", "options": ["logit_normal", "uniform"], "default": "logit_normal", "group": "INRFlow", "advanced": True, }, "ema_decay": { "label": "EMA decay", "type": "float", "default": 0.999, "min": 0.9, "max": 0.99999, "decimals": 5, "step": 0.0001, "group": "Optimization", "advanced": True, }, "save_every": { "label": "Save every", "type": "int", "default": 10, "min": 1, "max": 1000, "group": "Checkpoints", }, "preview_enabled": { "label": "Generate previews while training", "type": "bool", "default": True, "group": "Preview", }, "preview_every": { "label": "Preview interval", "type": "int", "default": 5, "min": 1, "max": 100000, "group": "Preview", }, "preview_steps": { "label": "Preview flow steps", "type": "int", "default": 20, "min": 2, "max": 200, "group": "Preview", }, "preview_prompt": { "label": "Preview note", "type": "text", "default": "", "group": "Preview", }, "preview_seed": { "label": "Preview seed", "type": "int", "default": 123456789, "min": 0, "max": 2147483647, "group": "Preview", },}
GENERATION_SETTINGS = { "prompt": { "label": "Creative note", "type": "multiline_text", "default": "", "group": "Generation", }, "image_count": { "label": "Images", "type": "int", "default": 1, "min": 1, "max": 48, "group": "Generation", }, "steps": { "label": "ODE steps", "type": "int", "default": 50, "min": 2, "max": 200, "group": "Generation", }, "sampler": { "label": "ODE method", "type": "choice", "options": ["Euler", "Heun"], "default": "Euler", "group": "Generation", }, "aspect_ratio": { "label": "Aspect ratio", "type": "choice", "options": ["1:1 (Coordinate Field)"], "default": "1:1 (Coordinate Field)", "group": "Generation", }, "seed": { "label": "Seed", "type": "int", "default": 0, "min": 0, "max": 2147483647, "group": "Generation", }, "output_resolution": { "label": "Output resolution", "type": "choice", "options": ["Native", "32", "64", "128", "256"], "default": "Native", "group": "Coordinate Field", "description": "INRFlow can query the learned coordinate field at a different resolution.", }, "noise_scale": { "label": "Starting noise scale", "type": "float", "default": 1.0, "min": 0.1, "max": 2.0, "decimals": 2, "step": 0.05, "group": "Generation", }, "query_chunk_size": { "label": "Query chunk size", "type": "choice", "options": [256, 512, 1024, 2048, 4096], "default": 1024, "group": "Advanced", "advanced": True, "description": "Reduce this if resolution-flexible generation runs out of VRAM.", }, "preview_interval": { "label": "Steps per live preview", "type": "int", "default": 5, "min": 0, "max": 200, "group": "Preview", }, "smart_generation": { "label": "Smart Generation", "type": "bool", "default": False, "group": "Smart Generation", }, "smart_wanted_results": { "label": "Wanted results", "type": "int", "default": 8, "min": 1, "max": 48, "group": "Smart Generation", }, "smart_max_candidates": { "label": "Maximum candidates", "type": "int", "default": 32, "min": 1, "max": 256, "group": "Smart Generation", }, "smart_min_score": { "label": "Minimum score", "type": "float", "default": 0.7, "min": 0, "max": 1, "group": "Smart Generation", }, "smart_mode": { "label": "Selection mode", "type": "choice", "options": ["threshold", "top_n"], "default": "threshold", "group": "Smart Generation", }, "smart_keep_rejected": { "label": "Keep rejected candidates", "type": "bool", "default": True, "group": "Smart Generation", },}
TRAINING_TOOL = { "id": "inrflow_trainer", "name": "INRFlow Trainer", "description": "Trains coordinate-to-RGB flow matching directly in ambient image space.", "capabilities": ["fresh_training", "resume_training", "progress", "pause", "cancel", "live_preview"], "backend": { "type": "python", "module": "adam.model_plugins_builtin.inrflow.trainer", "function": "train", },}
GENERATION_TOOL = { "id": "inrflow_generator", "name": "INRFlow Generator", "description": "Integrates an INRFlow coordinate field from Gaussian noise to an image.", "model_trainers": ["inrflow"], "capabilities": [ "image_generation", "smart_generation", "seed", "ode_method", "batch", "resolution_flexible_generation", "live_preview", "progress", "cancel", ], "generation_options": { "samplers": ["Euler", "Heun"], "aspect_ratios": ["1:1 (Coordinate Field)"], "step_min": 2, "step_max": 200, "step_default": 50, "preview_step_default": 5, }, "backend": { "type": "python", "module": "adam.model_plugins_builtin.inrflow.generator", "function": "generate", },}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400from __future__ import annotations
import mathfrom dataclasses import asdict, dataclassfrom typing import Any, Callable
import torchfrom torch import Tensor, nnfrom torch.nn import functional as F
MODEL_FORMAT_VERSION = 1
@dataclass(frozen=True, slots=True)class INRFlowConfig: resolution: int = 64 patch_size: int = 8 hidden_size: int = 256 depth: int = 4 num_heads: int = 8 decoder_layers: int = 1 fourier_frequencies: int = 8
def __post_init__(self) -> None: if self.resolution not in {32, 64, 128, 256}: raise ValueError("INRFlow resolution must be 32, 64, 128, or 256.") if self.patch_size not in {4, 8, 16} or self.resolution % self.patch_size: raise ValueError("INRFlow patch size must be 4, 8, or 16 and divide the resolution.") if not 64 <= self.hidden_size <= 768: raise ValueError("INRFlow transformer width must be between 64 and 768.") if not 1 <= self.depth <= 12 or not 1 <= self.decoder_layers <= 4: raise ValueError("INRFlow transformer depth is outside the supported range.") if self.num_heads not in {2, 4, 8, 16} or self.hidden_size % self.num_heads: raise ValueError("INRFlow width must be divisible by its attention-head count.") if not 2 <= self.fourier_frequencies <= 16: raise ValueError("INRFlow coordinate frequencies must be between 2 and 16.")
def to_dict(self) -> dict[str, int]: return asdict(self)
@classmethod def from_dict(cls, payload: dict[str, Any]) -> "INRFlowConfig": return cls( resolution=int(payload.get("resolution", 64)), patch_size=int(payload.get("patch_size", 8)), hidden_size=int(payload.get("hidden_size", 256)), depth=int(payload.get("depth", 4)), num_heads=int(payload.get("num_heads", 8)), decoder_layers=int(payload.get("decoder_layers", 1)), fourier_frequencies=int(payload.get("fourier_frequencies", 8)), )
def coordinate_grid( height: int, width: int, *, device: torch.device | str | None = None,) -> Tensor: """Return normalized x/y coordinates as a flattened Nx2 field.""" y = torch.linspace(0.0, 1.0, height, device=device) x = torch.linspace(0.0, 1.0, width, device=device) yy, xx = torch.meshgrid(y, x, indexing="ij") return torch.stack((xx, yy), dim=-1).reshape(height * width, 2)
class FourierCoordinates(nn.Module): def __init__(self, frequencies: int) -> None: super().__init__() bands = torch.pow(2.0, torch.arange(frequencies, dtype=torch.float32)) * math.pi self.register_buffer("bands", bands, persistent=False) self.output_size = 2 + 4 * frequencies
def forward(self, coordinates: Tensor) -> Tensor: phases = coordinates.unsqueeze(-1) * self.bands return torch.cat( (coordinates, phases.sin().flatten(-2), phases.cos().flatten(-2)), dim=-1 )
class TimeEmbedding(nn.Module): def __init__(self, hidden_size: int, frequency_size: int = 64) -> None: super().__init__() self.frequency_size = frequency_size self.mlp = nn.Sequential( nn.Linear(frequency_size, hidden_size), nn.SiLU(), nn.Linear(hidden_size, hidden_size), )
def forward(self, time: Tensor) -> Tensor: half = self.frequency_size // 2 frequencies = torch.exp( -math.log(10_000.0) * torch.arange(half, device=time.device, dtype=torch.float32) / max(1, half) ) phases = time.float().unsqueeze(1) * frequencies.unsqueeze(0) embedding = torch.cat((phases.cos(), phases.sin()), dim=1) return self.mlp(embedding)
class PatchContextEncoder(nn.Module): """Cross-attend one spatial latent to nearby coordinate/value pairs."""
def __init__(self, config: INRFlowConfig, coordinates: FourierCoordinates) -> None: super().__init__() hidden = config.hidden_size self.patch_size = config.patch_size self.coordinates = coordinates self.point_projection = nn.Sequential( nn.Linear(coordinates.output_size + 3, hidden), nn.LayerNorm(hidden), nn.SiLU(), ) self.center_projection = nn.Linear(coordinates.output_size, hidden) self.latent_seed = nn.Parameter(torch.randn(1, 1, hidden) * 0.02) self.attention = nn.MultiheadAttention( hidden, config.num_heads, batch_first=True ) self.norm1 = nn.LayerNorm(hidden) self.norm2 = nn.LayerNorm(hidden) self.mlp = nn.Sequential( nn.Linear(hidden, hidden * 2), nn.GELU(), nn.Linear(hidden * 2, hidden) )
@staticmethod def _patchify(values: Tensor, height: int, width: int, patch: int) -> Tensor: batch, points, channels = values.shape if points != height * width or height % patch or width % patch: raise ValueError("INRFlow context field does not match its patch grid.") return values.reshape( batch, height // patch, patch, width // patch, patch, channels ).permute(0, 1, 3, 2, 4, 5).reshape( batch, (height // patch) * (width // patch), patch * patch, channels )
def forward( self, context_coordinates: Tensor, context_values: Tensor, *, height: int, width: int, ) -> tuple[Tensor, Tensor]: batch = context_values.shape[0] encoded_coordinates = self.coordinates(context_coordinates) point_features = self.point_projection( torch.cat((encoded_coordinates, context_values), dim=-1) ) point_patches = self._patchify( point_features, height, width, self.patch_size ) coordinate_patches = self._patchify( context_coordinates, height, width, self.patch_size ) centers = coordinate_patches.mean(dim=2) latent_queries = self.latent_seed + self.center_projection( self.coordinates(centers) ) latent_count = point_patches.shape[1] queries = latent_queries.reshape(batch * latent_count, 1, -1) points = point_patches.reshape( batch * latent_count, self.patch_size * self.patch_size, -1 ) attended, _weights = self.attention( queries, points, points, need_weights=False ) latents = self.norm1(queries + attended) latents = latents + self.mlp(self.norm2(latents)) return latents.reshape(batch, latent_count, -1), centers
def _modulate(value: Tensor, shift: Tensor, scale: Tensor) -> Tensor: return value * (1.0 + scale.unsqueeze(1)) + shift.unsqueeze(1)
class TimeConditionedBlock(nn.Module): def __init__(self, hidden_size: int, heads: int) -> None: super().__init__() self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=False) self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False) self.attention = nn.MultiheadAttention(hidden_size, heads, batch_first=True) self.mlp = nn.Sequential( nn.Linear(hidden_size, hidden_size * 4), nn.GELU(approximate="tanh"), nn.Linear(hidden_size * 4, hidden_size), ) self.modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, hidden_size * 4)) nn.init.zeros_(self.modulation[-1].weight) nn.init.zeros_(self.modulation[-1].bias)
def forward(self, latents: Tensor, time_embedding: Tensor) -> Tensor: shift1, scale1, shift2, scale2 = self.modulation(time_embedding).chunk(4, dim=-1) attended, _weights = self.attention( _modulate(self.norm1(latents), shift1, scale1), _modulate(self.norm1(latents), shift1, scale1), _modulate(self.norm1(latents), shift1, scale1), need_weights=False, ) latents = latents + attended return latents + self.mlp(_modulate(self.norm2(latents), shift2, scale2))
class QueryDecoderBlock(nn.Module): def __init__(self, hidden_size: int, heads: int) -> None: super().__init__() self.query_norm = nn.LayerNorm(hidden_size) self.latent_norm = nn.LayerNorm(hidden_size) self.attention = nn.MultiheadAttention(hidden_size, heads, batch_first=True) self.output_norm = nn.LayerNorm(hidden_size) self.mlp = nn.Sequential( nn.Linear(hidden_size, hidden_size * 2), nn.GELU(approximate="tanh"), nn.Linear(hidden_size * 2, hidden_size), )
def forward(self, queries: Tensor, latents: Tensor) -> Tensor: attended, _weights = self.attention( self.query_norm(queries), self.latent_norm(latents), self.latent_norm(latents), need_weights=False, ) queries = queries + attended return queries + self.mlp(self.output_norm(queries))
class INRFlowModel(nn.Module): """Coordinate-query flow model following INRFlow's ambient-space structure."""
def __init__(self, config: INRFlowConfig) -> None: super().__init__() self.config = config self.coordinate_embedding = FourierCoordinates(config.fourier_frequencies) self.time_embedding = TimeEmbedding(config.hidden_size) self.context_encoder = PatchContextEncoder(config, self.coordinate_embedding) self.latent_coordinate_projection = nn.Linear( self.coordinate_embedding.output_size, config.hidden_size ) self.trunk = nn.ModuleList([ TimeConditionedBlock(config.hidden_size, config.num_heads) for _ in range(config.depth) ]) self.query_projection = nn.Sequential( nn.Linear(self.coordinate_embedding.output_size + 3, config.hidden_size), nn.LayerNorm(config.hidden_size), nn.SiLU(), ) self.decoder = nn.ModuleList([ QueryDecoderBlock(config.hidden_size, config.num_heads) for _ in range(config.decoder_layers) ]) self.output = nn.Sequential( nn.LayerNorm(config.hidden_size), nn.Linear(config.hidden_size, 3) ) nn.init.zeros_(self.output[-1].weight) nn.init.zeros_(self.output[-1].bias)
def encode_context( self, context_coordinates: Tensor, context_values: Tensor, time: Tensor, *, height: int, width: int, ) -> tuple[Tensor, Tensor]: latents, centers = self.context_encoder( context_coordinates, context_values, height=height, width=width ) time_embedding = self.time_embedding(time) latents = latents + self.latent_coordinate_projection( self.coordinate_embedding(centers) ) for block in self.trunk: latents = block(latents, time_embedding) return latents, time_embedding
def decode_queries( self, latents: Tensor, time_embedding: Tensor, query_coordinates: Tensor, query_values: Tensor, ) -> Tensor: queries = self.query_projection(torch.cat(( self.coordinate_embedding(query_coordinates), query_values ), dim=-1)) queries = queries + time_embedding.unsqueeze(1) for block in self.decoder: queries = block(queries, latents) return self.output(queries)
def forward( self, context_coordinates: Tensor, context_values: Tensor, time: Tensor, query_coordinates: Tensor, query_values: Tensor, *, height: int, width: int, ) -> Tensor: latents, time_embedding = self.encode_context( context_coordinates, context_values, time, height=height, width=width ) return self.decode_queries( latents, time_embedding, query_coordinates, query_values )
@torch.inference_mode() def velocity_field( self, coordinates: Tensor, values: Tensor, time: Tensor, *, height: int, width: int, query_chunk_size: int = 1024, ) -> Tensor: latents, time_embedding = self.encode_context( coordinates, values, time, height=height, width=width ) outputs = [] for start in range(0, coordinates.shape[1], query_chunk_size): stop = min(coordinates.shape[1], start + query_chunk_size) outputs.append(self.decode_queries( latents, time_embedding, coordinates[:, start:stop], values[:, start:stop], )) return torch.cat(outputs, dim=1)
@torch.inference_mode()def sample_image( model: INRFlowModel, *, resolution: int, steps: int, method: str, noise_scale: float, query_chunk_size: int, generator: torch.Generator, step_callback: Callable[[int, int, Tensor], None] | None = None,) -> Tensor: """Integrate the learned velocity from Gaussian noise (t=0) to data (t=1).""" if resolution % model.config.patch_size: raise ValueError("Output resolution must be divisible by the trained patch size.") model.eval() device = next(model.parameters()).device coordinates = coordinate_grid(resolution, resolution, device=device).unsqueeze(0) values = torch.randn( 1, resolution * resolution, 3, device=device, generator=generator ) * float(noise_scale) times = torch.linspace(0.0, 1.0, int(steps) + 1, device=device) for index in range(int(steps)): time = times[index].expand(1) next_time = times[index + 1].expand(1) delta = times[index + 1] - times[index] with torch.autocast( device_type=device.type, dtype=torch.float16, enabled=device.type == "cuda", ): first = model.velocity_field( coordinates, values, time, height=resolution, width=resolution, query_chunk_size=query_chunk_size, ) if method == "Heun": predicted = values + delta * first second = model.velocity_field( coordinates, predicted, next_time, height=resolution, width=resolution, query_chunk_size=query_chunk_size, ) if method == "Heun": values = values + delta * 0.5 * (first + second) else: values = values + delta * first if step_callback is not None: image = values[0].reshape(resolution, resolution, 3).clamp(-1, 1) step_callback(index + 1, int(steps), image) return values[0].reshape(resolution, resolution, 3).clamp(-1, 1)
def parameter_count(model: nn.Module) -> int: return sum(parameter.numel() for parameter in model.parameters())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523from __future__ import annotations
import copyimport randomfrom contextlib import nullcontextfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
import torchfrom PIL import Image, ImageOps, ImageStatfrom torch.utils.data import DataLoader, Dataset
from adam.executor import ToolExecutionError
from .common import ( CONFIG_NAME, FINAL_CHECKPOINT_NAME, ensure_below, image_files, load_checkpoint, resolve_checkpoint, safe_model_name, save_image, write_json,)from .model import ( MODEL_FORMAT_VERSION, INRFlowConfig, INRFlowModel, coordinate_grid, parameter_count, sample_image,)
class INRFlowImageDataset(Dataset[torch.Tensor]): def __init__( self, paths: list[Path], *, resolution: int, resize_mode: str, horizontal_flip: bool, ) -> None: self.paths = paths self.resolution = resolution self.resize_mode = resize_mode self.horizontal_flip = horizontal_flip
def __len__(self) -> int: return len(self.paths)
def __getitem__(self, index: int) -> torch.Tensor: path = self.paths[index] try: with Image.open(path) as opened: image = opened.convert("RGB") size = (self.resolution, self.resolution) if self.resize_mode == "fill": image = ImageOps.fit(image, size, method=Image.Resampling.LANCZOS) elif self.resize_mode == "fit": mean = tuple( int(value) for value in ImageStat.Stat(image.resize((1, 1))).mean ) image = ImageOps.pad( image, size, method=Image.Resampling.LANCZOS, color=mean ) else: image = image.resize(size, Image.Resampling.LANCZOS) if self.horizontal_flip and random.random() < 0.5: image = image.transpose(Image.Transpose.FLIP_LEFT_RIGHT) buffer = bytearray(image.tobytes()) except (OSError, ValueError) as exc: raise RuntimeError(f"Could not read training image {path.name}: {exc}") from exc pixels = torch.frombuffer(buffer, dtype=torch.uint8).reshape( self.resolution, self.resolution, 3 ) return pixels.float().div(127.5).sub(1.0).permute(2, 0, 1)
def _checkpoint_payload( model: INRFlowModel, ema_model: INRFlowModel, optimizer: torch.optim.Optimizer, *, model_name: str, dataset_dir: Path, completed_epochs: int, global_step: int, training_settings: dict[str, Any],) -> dict[str, Any]: return { "format_version": MODEL_FORMAT_VERSION, "architecture": "inrflow_ambient_space", "method": "conditionally_independent_continuous_flow_matching", "model_name": model_name, "config": model.config.to_dict(), "model_state": model.state_dict(), "ema_state": ema_model.state_dict(), "optimizer_state": optimizer.state_dict(), "completed_epochs": int(completed_epochs), "global_step": int(global_step), "dataset_dir": str(dataset_dir), "training_settings": training_settings, "saved_at": datetime.now(timezone.utc).isoformat(), }
def _save_checkpoint(path: Path, payload: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") torch.save(payload, temporary) temporary.replace(path)
@torch.no_grad()def _update_ema(ema_model: INRFlowModel, model: INRFlowModel, decay: float) -> None: source = model.state_dict() for name, value in ema_model.state_dict().items(): incoming = source[name] if value.is_floating_point(): value.mul_(decay).add_(incoming, alpha=1.0 - decay) else: value.copy_(incoming)
def _preview( context, model: INRFlowModel, output: Path, *, epoch: int, next_epoch: int, steps: int, seed: int, prompt: str,) -> None: device = next(model.parameters()).device generator = torch.Generator(device=device) generator.manual_seed(int(seed)) image = sample_image( model, resolution=model.config.resolution, steps=int(steps), method="Euler", noise_scale=1.0, query_chunk_size=1024, generator=generator, step_callback=lambda _done, _total, _image: context.checkpoint(), ) destination = output / "previews" / f"preview_epoch_{epoch:06d}.png" save_image(image, destination) context.preview( destination, epoch=epoch, next_epoch=next_epoch, prompt=prompt, seed=seed, steps=int(steps), )
def train( context, dataset_dir: str, model_name: str, epochs: int, output_dir: str, resume_from: str = "", resolution: int = 64, resize_mode: str = "fill", horizontal_flip: bool = True, batch_size: int = 4, learning_rate: float = 0.0001, weight_decay: float = 0.0, gradient_accumulation_steps: int = 1, workers: int = 0, mixed_precision: str = "fp16", patch_size: int = 8, hidden_size: int = 256, depth: int = 4, num_heads: int = 8, decoder_layers: int = 1, fourier_frequencies: int = 8, query_points: int = 1024, time_sampling: str = "logit_normal", ema_decay: float = 0.999, save_every: int = 10, preview_enabled: bool = True, preview_every: int = 5, preview_steps: int = 20, preview_prompt: str = "", preview_seed: int = 123456789,) -> dict[str, Any]: """Train an ADAM-sized INRFlow model directly on RGB coordinate fields.""" name = safe_model_name(model_name) dataset = Path(dataset_dir).expanduser().resolve() if not dataset.is_dir(): raise ToolExecutionError("The selected INRFlow dataset folder no longer exists.") training_dataset = dataset accepted_frames = dataset / "frames" frame_paths = image_files(accepted_frames) if accepted_frames.is_dir() else [] if frame_paths: training_dataset, paths = accepted_frames, frame_paths else: paths = image_files(dataset) if len(paths) < 2: raise ToolExecutionError( "INRFlow needs at least two readable image files before training can start." )
output_root = ( context.root.resolve() / "data" / "model_plugin_outputs" / "inrflow" ).resolve() output = ensure_below(Path(output_dir), output_root, "INRFlow output") if output.exists() and not output.is_dir(): raise ToolExecutionError("The INRFlow output path must be a folder.") if output.exists() and any(output.iterdir()): raise ToolExecutionError( "The INRFlow output folder is not empty. Choose a new model output." ) output.mkdir(parents=True, exist_ok=True)
if resize_mode not in {"fill", "fit", "stretch"}: raise ToolExecutionError("INRFlow image fitting must be fill, fit, or stretch.") if not 1 <= int(epochs) <= 100_000: raise ToolExecutionError("INRFlow epochs must be between 1 and 100000.") if not 1 <= int(batch_size) <= 32 or not 1 <= int(gradient_accumulation_steps) <= 64: raise ToolExecutionError("INRFlow batch size or gradient accumulation is invalid.") if not 1e-7 <= float(learning_rate) <= 0.1 or not 0.0 <= float(weight_decay) <= 1.0: raise ToolExecutionError("INRFlow learning rate or weight decay is invalid.") if not 0 <= int(workers) <= 16 or mixed_precision not in {"fp16", "bf16", "no"}: raise ToolExecutionError("INRFlow loader workers or precision is invalid.") if int(query_points) < 1 or int(query_points) > int(resolution) ** 2: raise ToolExecutionError("Pixel queries cannot exceed the number of training pixels.") if time_sampling not in {"logit_normal", "uniform"}: raise ToolExecutionError("INRFlow time sampling must be logit_normal or uniform.") if not 0.9 <= float(ema_decay) <= 0.99999: raise ToolExecutionError("INRFlow EMA decay must be between 0.9 and 0.99999.") if not 1 <= int(save_every) <= 1000 or not 1 <= int(preview_every) <= 100_000: raise ToolExecutionError("INRFlow save and preview intervals must be positive.") if not 2 <= int(preview_steps) <= 200: raise ToolExecutionError("INRFlow preview steps must be between 2 and 200.")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") resume_payload: dict[str, Any] | None = None if resume_from.strip(): resume_path = ensure_below( resolve_checkpoint(Path(resume_from)), output_root, "INRFlow resume checkpoint" ) model, resume_payload = load_checkpoint(resume_path, device, prefer_ema=False) config = model.config context.log( "Continuing with the checkpoint architecture: " f"{config.resolution}px, width {config.hidden_size}, depth {config.depth}." ) else: try: config = INRFlowConfig( resolution=int(resolution), patch_size=int(patch_size), hidden_size=int(hidden_size), depth=int(depth), num_heads=int(num_heads), decoder_layers=int(decoder_layers), fourier_frequencies=int(fourier_frequencies), ) except ValueError as exc: raise ToolExecutionError(str(exc)) from exc model = INRFlowModel(config).to(device)
if int(query_points) > config.resolution ** 2: raise ToolExecutionError( "Pixel queries cannot exceed the resumed model's training resolution." ) ema_model = copy.deepcopy(model).to(device).eval() if resume_payload is not None and isinstance(resume_payload.get("ema_state"), dict): try: ema_model.load_state_dict(resume_payload["ema_state"], strict=True) except RuntimeError: context.log("The previous EMA weights were incompatible; EMA restarted from the model.")
dataset_object = INRFlowImageDataset( paths, resolution=config.resolution, resize_mode=resize_mode, horizontal_flip=bool(horizontal_flip), ) loader = DataLoader( dataset_object, batch_size=int(batch_size), shuffle=True, num_workers=int(workers), pin_memory=device.type == "cuda", drop_last=False, ) optimizer = torch.optim.AdamW( model.parameters(), lr=float(learning_rate), betas=(0.9, 0.95), weight_decay=float(weight_decay), ) start_epoch = 0 global_step = 0 if resume_payload is not None: start_epoch = int(resume_payload.get("completed_epochs", 0) or 0) global_step = int(resume_payload.get("global_step", 0) or 0) if isinstance(resume_payload.get("optimizer_state"), dict): try: optimizer.load_state_dict(resume_payload["optimizer_state"]) for group in optimizer.param_groups: group["lr"] = float(learning_rate) group["weight_decay"] = float(weight_decay) except (ValueError, RuntimeError): context.log("The old optimizer state was incompatible; using a fresh optimizer.")
use_fp16 = mixed_precision == "fp16" and device.type == "cuda" use_bf16 = ( mixed_precision == "bf16" and device.type == "cuda" and bool(getattr(torch.cuda, "is_bf16_supported", lambda: False)()) ) if mixed_precision != "no" and not (use_fp16 or use_bf16): context.log(f"{mixed_precision.upper()} is unavailable here; INRFlow will use full precision.") autocast_dtype = torch.bfloat16 if use_bf16 else torch.float16 try: scaler = torch.amp.GradScaler("cuda", enabled=use_fp16) except (AttributeError, TypeError): scaler = torch.cuda.amp.GradScaler(enabled=use_fp16)
accumulation = int(gradient_accumulation_steps) requested_epochs = int(epochs) final_epoch = start_epoch + requested_epochs batches_per_epoch = max(1, len(loader)) total_batches = requested_epochs * batches_per_epoch coordinates = coordinate_grid(config.resolution, config.resolution, device=device) settings = { "resolution": config.resolution, "resize_mode": resize_mode, "horizontal_flip": bool(horizontal_flip), "batch_size": int(batch_size), "learning_rate": float(learning_rate), "weight_decay": float(weight_decay), "gradient_accumulation_steps": accumulation, "workers": int(workers), "mixed_precision": mixed_precision, "query_points": int(query_points), "time_sampling": time_sampling, "ema_decay": float(ema_decay), **config.to_dict(), } write_json( output / CONFIG_NAME, { "format_version": MODEL_FORMAT_VERSION, "model_type": "inrflow", "model_name": name, **config.to_dict(), }, ) context.log( f"Training INRFlow on {len(paths)} images from {training_dataset} at " f"{config.resolution}x{config.resolution}, {parameter_count(model):,} parameters, " f"batch {batch_size}, device {device}." ) context.log( "Images stay in RGB coordinate space: no VAE or other pretrained image compressor is used." ) optimizer.zero_grad(set_to_none=True) processed_batches = 0 last_loss = 0.0 try: for epoch in range(start_epoch + 1, final_epoch + 1): model.train() epoch_loss = 0.0 for batch_index, images in enumerate(loader, 1): context.checkpoint() images = images.to(device, non_blocking=device.type == "cuda") batch = images.shape[0] clean = images.permute(0, 2, 3, 1).reshape(batch, -1, 3) noise = torch.randn_like(clean) if time_sampling == "logit_normal": time = torch.sigmoid(torch.randn(batch, device=device)) else: time = torch.rand(batch, device=device) mixed = (1.0 - time[:, None, None]) * noise + time[:, None, None] * clean target = clean - noise sample_count = min(int(query_points), clean.shape[1]) indices = torch.randperm(clean.shape[1], device=device)[:sample_count] all_coordinates = coordinates.unsqueeze(0).expand(batch, -1, -1) amp = ( torch.autocast( device_type=device.type, dtype=autocast_dtype, enabled=use_fp16 or use_bf16, ) if device.type in {"cuda", "cpu"} else nullcontext() ) with amp: velocity = model( all_coordinates, mixed, time, all_coordinates[:, indices], mixed[:, indices], height=config.resolution, width=config.resolution, ) loss = torch.nn.functional.mse_loss(velocity, target[:, indices]) scaled_loss = loss / accumulation scaler.scale(scaled_loss).backward() if batch_index % accumulation == 0 or batch_index == batches_per_epoch: scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 2.0) scaler.step(optimizer) scaler.update() optimizer.zero_grad(set_to_none=True) global_step += 1 _update_ema(ema_model, model, float(ema_decay)) last_loss = float(loss.detach().item()) epoch_loss += last_loss processed_batches += 1 percent = max(1, min(99, round(processed_batches * 100 / total_batches))) context.progress( percent, f"Epoch {epoch} of {final_epoch} · flow loss {last_loss:.4f}", epoch=epoch, total_epochs=final_epoch, current_step=processed_batches, total_steps=total_batches, unit="batch", loss=last_loss, )
payload = _checkpoint_payload( model, ema_model, optimizer, model_name=name, dataset_dir=dataset, completed_epochs=epoch, global_step=global_step, training_settings=settings, ) if epoch % int(save_every) == 0: _save_checkpoint(output / "checkpoints" / f"epoch_{epoch:06d}.pt", payload) if bool(preview_enabled) and epoch % int(preview_every) == 0: _preview( context, ema_model, output, epoch=epoch, next_epoch=min(final_epoch, epoch + int(preview_every)), steps=int(preview_steps), seed=int(preview_seed), prompt=preview_prompt, ) context.log(f"Finished epoch {epoch}; average loss {epoch_loss / batches_per_epoch:.4f}.") except torch.cuda.OutOfMemoryError as exc: if device.type == "cuda": torch.cuda.empty_cache() raise ToolExecutionError( "INRFlow ran out of VRAM. Reduce batch size, then pixel queries, resolution, or model width." ) from exc
final_payload = _checkpoint_payload( model, ema_model, optimizer, model_name=name, dataset_dir=dataset, completed_epochs=final_epoch, global_step=global_step, training_settings=settings, ) final_checkpoint = output / FINAL_CHECKPOINT_NAME _save_checkpoint(final_checkpoint, final_payload) write_json( output / "training_metadata.json", { "format_version": MODEL_FORMAT_VERSION, "model_type": "inrflow", "architecture": "inrflow_ambient_space", "method": "conditionally_independent_continuous_flow_matching", "model_name": name, "dataset_dir": str(dataset), "image_count": len(paths), "completed_epochs": final_epoch, "epochs_this_run": requested_epochs, "global_step": global_step, "final_loss": last_loss, "parameter_count": parameter_count(model), "checkpoint": str(final_checkpoint), "uses_pretrained_compressor": False, "method_reference": "https://arxiv.org/abs/2412.03791", "settings": settings, "finished_at": datetime.now(timezone.utc).isoformat(), }, ) context.progress(100, "INRFlow training completed") return { "output_folder": str(output), "model_name": name, "assets": [ { "kind": "model", "name": name, "path": str(output), "trainer": "inrflow", "dataset_path": str(dataset), "checkpoint": str(final_checkpoint), "epochs": final_epoch, "metadata": { "architecture": "inrflow_ambient_space", "resolution": config.resolution, "parameter_count": parameter_count(model), "uses_pretrained_compressor": False, }, } ], }1 unmodified line234567891011121314151617181920212223242526272829303132333435366 unmodified lines43444546474849501 unmodified lineMODEL_INFO = {"name": "Oasis Action World Model","version": "1.0","category": "Playable World Models","description": "Action-conditioned playable world model trainer for gameplay frame sequences.","architecture": "action_conditioned_rectified_flow_video","status": "experimental","output_type": "playable_world","capabilities": ["fresh_training", "resume_training", "playable_inference", "live_preview"],"input_formats": ["Oasis action dataset folder", "semicolon-separated Oasis dataset folders"],"output_formats": ["action_flow_model_info.json", "diffusers unet folder", "png preview"],"hardware": {"recommended_vram_gb": 12, "recommended_system_ram_gb": 32},"vram_behavior": {"scales_with": ["resolution", "batch_size", "sequence_context"],"estimate": "High; 256x144 with batch 2 is the conservative RTX 3060 starting point.",},}TRAINING_SETTINGS = {"resolution": {"label": "Resolution", "type": "choice", "options": ["128x72", "256x144", "384x216", "512x288"], "default": "256x144", "group": "Basic"},"batch_size": {"label": "Batch size", "type": "int", "default": 2, "min": 1, "max": 16, "group": "Basic"},"learning_rate": {"label": "Learning rate", "type": "float", "default": 0.00002, "min": 0.0000001, "max": 0.01, "decimals": 7, "step": 0.00001, "group": "Optimization"},"workers": {"label": "Loader workers", "type": "int", "default": 2, "min": 0, "max": 8, "group": "Dataset"},"mixed_precision": {"label": "Precision", "type": "choice", "options": ["fp32", "fp16", "no"], "default": "fp32", "group": "Optimization"},"gradient_accumulation": {"label": "Gradient accumulation", "type": "int", "default": 1, "min": 1, "max": 16, "group": "Optimization"},"frame_gap": {"label": "Prediction horizon", "type": "int", "default": 3, "min": 1, "max": 60, "group": "Sequence"},"sequence_context": {"label": "Context length", "type": "int", "default": 1, "min": 1, "max": 32, "group": "Sequence"},"action_aggregation": {"label": "Action aggregation", "type": "choice", "options": ["window", "mean", "last"], "default": "window", "group": "Sequence"},"validation_split": {"label": "Validation split", "type": "float", "default": 0.1, "min": 0.01, "max": 0.5, "decimals": 3, "step": 0.01, "group": "Dataset"},"validation_batches": {"label": "Validation batches", "type": "int", "default": 8, "min": 0, "max": 128, "group": "Dataset"},"save_every": {"label": "Save every", "type": "int", "default": 5, "min": 1, "max": 1000, "group": "Checkpoints"},"preview_enabled": {"label": "Generate previews while training", "type": "bool", "default": True, "group": "Preview"},"preview_every": {"label": "Preview interval", "type": "int", "default": 5, "min": 1, "max": 100000, "group": "Preview"},"preview_steps": {"label": "Preview steps", "type": "int", "default": 1, "min": 1, "max": 50, "group": "Preview"},6 unmodified lines"neutral_action_dropout": {"label": "Neutral action dropout", "type": "float", "default": 0.15, "min": 0.0, "max": 0.9, "decimals": 3, "step": 0.05, "group": "Advanced", "advanced": True},"action_contrast_weight": {"label": "Action contrast weight", "type": "float", "default": 0.35, "min": 0.0, "max": 5.0, "decimals": 3, "step": 0.05, "group": "Advanced", "advanced": True},"action_contrast_margin": {"label": "Action contrast margin", "type": "float", "default": 0.02, "min": 0.0, "max": 1.0, "decimals": 4, "step": 0.005, "group": "Advanced", "advanced": True},"gradient_checkpointing": {"label": "Gradient checkpointing", "type": "bool", "default": False, "group": "Advanced", "advanced": True},"balance_actions": {"label": "Balance rare actions", "type": "bool", "default": False, "group": "Advanced", "advanced": True},}GENERATION_SETTINGS = {1 unmodified line2345678910111213141516171819202122232425262728293031323334353637383940416 unmodified lines4849505152535455565758596061626364651 unmodified lineMODEL_INFO = {"name": "Oasis Action World Model","version": "1.1","category": "Playable World Models","description": "Action-conditioned playable world model trainer for gameplay frame sequences.","architecture": "action_conditioned_rectified_flow_video | action_conditioned_latent_vae_flow_video | action_conditioned_temporal_latent_flow | action_conditioned_temporal_pixel_flow","status": "experimental","output_type": "playable_world","capabilities": ["fresh_training", "resume_training", "playable_inference", "live_preview"],"input_formats": ["Oasis action dataset folder", "semicolon-separated Oasis dataset folders"],"output_formats": ["action_flow_model_info.json", "diffusers unet folder", "VAE folder for latent models", "png preview"],"hardware": {"recommended_vram_gb": 12, "recommended_system_ram_gb": 32},"vram_behavior": {"scales_with": ["resolution", "batch_size", "history frames"],"estimate": "High; 256x144 with batch 2 is the conservative RTX 3060 starting point.",},}TRAINING_SETTINGS = {"model_engine": {"label": "Model engine", "type": "choice", "options": ["pixel_flow", "vae_cpu_lite", "temporal_latent", "temporal_pixel_flow"], "option_labels": {"pixel_flow": "Pixel Flow (RGB)", "vae_cpu_lite": "VAE CPU Lite", "temporal_latent": "Temporal Latent (VAE + history)", "temporal_pixel_flow": "Temporal Pixel Flow"}, "default": "temporal_latent", "group": "Basic", "description": "Temporal Pixel Flow keeps recent-frame and timed-input conditioning while predicting full RGB frames without a VAE. It needs more VRAM than Temporal Latent."},"resolution": {"label": "Resolution", "type": "choice", "options": ["256x144", "512x288"], "default": "256x144", "group": "Basic", "description": "Must be 16:9 with both dimensions divisible by 16."},"frame_gap": {"label": "Frame gap", "type": "int", "default": 1, "min": 1, "max": 60, "group": "Basic", "description": "How many recorded frames one generated game frame spans. Use 1 for a 12–15 FPS recording when you want the most responsive native AI FPS."},"batch_size": {"label": "Batch size", "type": "int", "default": 2, "min": 1, "max": 16, "group": "Basic"},"learning_rate": {"label": "Learning rate", "type": "float", "default": 0.00002, "min": 0.0000001, "max": 0.01, "decimals": 7, "step": 0.00001, "group": "Optimization"},"workers": {"label": "Loader workers", "type": "int", "default": 2, "min": 0, "max": 8, "group": "Dataset"},"mixed_precision": {"label": "Precision", "type": "choice", "options": ["fp16", "no"], "default": "fp16", "group": "Optimization", "description": "The connected Oasis trainer supports FP16 or full precision (no AMP)."},"gradient_accumulation": {"label": "Gradient accumulation", "type": "int", "default": 1, "min": 1, "max": 16, "group": "Optimization"},"sequence_context": {"label": "Legacy context length", "type": "int", "default": 1, "min": 1, "max": 32, "group": "Sequence", "advanced": True, "description": "Only used by the older pixel-flow engines."},"context_frames": {"label": "History frames", "type": "choice", "options": [1, 4, 8], "default": 4, "group": "Sequence", "description": "How much recent visual and input history the temporal model uses."},"rollout_frames": {"label": "Future frames", "type": "choice", "options": [1, 3], "default": 3, "group": "Sequence", "description": "How many future frames each temporal training example predicts."},"vae_epochs": {"label": "VAE warm-up epochs", "type": "int", "default": 5, "min": 1, "max": 100, "group": "Sequence", "description": "Initial epochs used to learn the compact visual representation for latent engines. Not used by pixel_flow or temporal_pixel_flow."},"action_aggregation": {"label": "Action aggregation", "type": "choice", "options": ["window", "mean", "last"], "default": "window", "group": "Sequence"},"validation_split": {"label": "Validation split", "type": "float", "default": 0.1, "min": 0.01, "max": 0.5, "decimals": 3, "step": 0.01, "group": "Dataset"},"validation_batches": {"label": "Validation batches", "type": "int", "default": 8, "min": 0, "max": 128, "group": "Dataset"},"save_every": {"label": "Save every", "type": "int", "default": 5, "min": 1, "max": 1000, "group": "Checkpoints"},"best_checkpoint_min_improvement": {"label": "Best-checkpoint improvement (%)", "type": "float", "default": 0.1, "min": 0.0, "max": 20.0, "decimals": 2, "step": 0.1, "group": "Checkpoints", "advanced": True, "description": "Save a separate best-validation checkpoint only when held-out quality improves by this percentage. ADAM uses that checkpoint automatically when playing the completed model."},"preview_enabled": {"label": "Generate previews while training", "type": "bool", "default": True, "group": "Preview"},"preview_every": {"label": "Preview interval", "type": "int", "default": 5, "min": 1, "max": 100000, "group": "Preview"},"preview_steps": {"label": "Preview steps", "type": "int", "default": 1, "min": 1, "max": 50, "group": "Preview"},6 unmodified lines"neutral_action_dropout": {"label": "Neutral action dropout", "type": "float", "default": 0.15, "min": 0.0, "max": 0.9, "decimals": 3, "step": 0.05, "group": "Advanced", "advanced": True},"action_contrast_weight": {"label": "Action contrast weight", "type": "float", "default": 0.35, "min": 0.0, "max": 5.0, "decimals": 3, "step": 0.05, "group": "Advanced", "advanced": True},"action_contrast_margin": {"label": "Action contrast margin", "type": "float", "default": 0.02, "min": 0.0, "max": 1.0, "decimals": 4, "step": 0.005, "group": "Advanced", "advanced": True},"contrast_every": {"label": "Contrast every N batches", "type": "int", "default": 4, "min": 1, "max": 128, "group": "Advanced", "advanced": True},"contrast_samples": {"label": "Contrast samples", "type": "int", "default": 2, "min": 2, "max": 32, "group": "Advanced", "advanced": True},"chunk_size": {"label": "Transitions per training chunk", "type": "int", "default": 0, "min": 0, "max": 1000000, "group": "Dataset", "description": "0 uses every transition each epoch. A balanced chunk bounds large-dataset training time."},"chunk_mode": {"label": "Chunk selection", "type": "choice", "options": ["balanced", "random", "sequential"], "default": "balanced", "group": "Dataset"},"chunk_offset": {"label": "Chunk offset", "type": "int", "default": 0, "min": 0, "max": 100000000, "group": "Dataset", "advanced": True},"replay_older_percent": {"label": "Older-data replay (%)", "type": "float", "default": 50.0, "min": 0.0, "max": 500.0, "decimals": 1, "step": 25.0, "group": "Dataset", "advanced": True},"include_older_data": {"label": "Mix selected older datasets", "type": "bool", "default": True, "group": "Dataset", "advanced": True},"recovery_minutes": {"label": "Emergency recovery every minutes", "type": "int", "default": 30, "min": 0, "max": 240, "group": "Checkpoints", "advanced": True},"benchmark_batches": {"label": "Speed-test batches", "type": "int", "default": 8, "min": 1, "max": 100, "group": "Advanced", "advanced": True},"tf32": {"label": "Use TF32 acceleration", "type": "bool", "default": True, "group": "Optimization", "advanced": True},"gradient_checkpointing": {"label": "Gradient checkpointing", "type": "bool", "default": False, "group": "Advanced", "advanced": True},"balance_actions": {"label": "Balance rare actions", "type": "bool", "default": True, "group": "Advanced", "advanced": True},}GENERATION_SETTINGS = {
12"""PixelRow autoregressive image model plugin."""
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586from __future__ import annotations
import jsonimport refrom pathlib import Pathfrom typing import Any
import torchfrom PIL import Image
from adam.executor import ToolExecutionError
from .model import MODEL_FORMAT_VERSION, PixelRowConfig, PixelRowModel, canvas_to_uint8
IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}FINAL_CHECKPOINT_NAME = "pixelrow_model.pt"CONFIG_NAME = "pixelrow_config.json"
def safe_model_name(value: str) -> str: name = re.sub(r"\s+", " ", value.strip()) if not name or len(name) > 96 or any(character in name for character in '<>:"/\\|?*\x00'): raise ToolExecutionError("Choose a short PixelRow model name without reserved filename characters.") return name
def ensure_below(path: Path, root: Path, label: str) -> Path: resolved = path.expanduser().resolve() try: resolved.relative_to(root.expanduser().resolve()) except ValueError as exc: raise ToolExecutionError(f"{label} must stay inside {root.resolve()}.") from exc return resolved
def image_files(folder: Path) -> list[Path]: try: return sorted( path for path in folder.rglob("*") if path.is_file() and path.suffix.casefold() in IMAGE_EXTENSIONS ) except OSError: return []
def resolve_checkpoint(path: Path) -> Path: candidate = path.expanduser().resolve() if candidate.is_dir(): candidate = candidate / FINAL_CHECKPOINT_NAME if not candidate.is_file(): raise ToolExecutionError("The selected PixelRow checkpoint does not exist or is incomplete.") return candidate
def load_checkpoint(path: Path, device: torch.device) -> tuple[PixelRowModel, dict[str, Any]]: checkpoint_path = resolve_checkpoint(path) try: payload = torch.load(checkpoint_path, map_location=device, weights_only=False) except (OSError, RuntimeError, ValueError, TypeError) as exc: raise ToolExecutionError(f"Could not load the PixelRow checkpoint: {exc}") from exc if not isinstance(payload, dict) or "model_state" not in payload or "config" not in payload: raise ToolExecutionError("The selected file is not a valid PixelRow checkpoint.") if int(payload.get("format_version", 0)) != MODEL_FORMAT_VERSION: raise ToolExecutionError("This PixelRow checkpoint uses an unsupported format version.") try: config = PixelRowConfig.from_dict(dict(payload["config"])) model = PixelRowModel(config).to(device) model.load_state_dict(payload["model_state"], strict=True) except (KeyError, TypeError, ValueError, RuntimeError) as exc: raise ToolExecutionError(f"The PixelRow checkpoint is incompatible: {exc}") from exc return model, payload
def save_canvas(canvas: torch.Tensor, path: Path, completed_rows: int | None = None) -> None: pixels = canvas_to_uint8(canvas, completed_rows=completed_rows).numpy() path.parent.mkdir(parents=True, exist_ok=True) Image.fromarray(pixels, mode="RGB").save(path, format="PNG")
def write_json(path: Path, payload: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(payload, indent=2), encoding="utf-8") temporary.replace(path)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212from __future__ import annotations
import randomfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
import torch
from adam.executor import ToolExecutionErrorfrom adam.generations import generation_metadata_path, generation_output_folder
from .common import ensure_below, load_checkpoint, safe_model_name, save_canvas, write_json
def generate( context, model_name: str, model_path: str, prompt: str, image_count: int, steps: int, seed: int, sampler: str, aspect_ratio: str, temperature: float = 0.85, top_k: int = 4, save_progress_frames: bool = True, frame_interval: int = 2, preview_interval: int = 4,) -> dict[str, Any]: """Generate images one complete RGB row at a time.""" name = safe_model_name(model_name) model_root = (context.root.resolve() / "data" / "model_plugin_outputs" / "pixelrow").resolve() selected = ensure_below(Path(model_path), model_root, "PixelRow model") if not selected.exists(): raise ToolExecutionError("The selected PixelRow model no longer exists.") if not 1 <= int(image_count) <= 48: raise ToolExecutionError("PixelRow image count must be between 1 and 48.") if not 1 <= int(steps) <= 128: raise ToolExecutionError("PixelRow rows to generate must be between 1 and 128.") if sampler != "Categorical": raise ToolExecutionError("PixelRow currently supports categorical row sampling.") if aspect_ratio != "1:1 (Native)": raise ToolExecutionError("PixelRow currently generates at its native square resolution.") if not 0.05 <= float(temperature) <= 3.0: raise ToolExecutionError("PixelRow creativity must be between 0.05 and 3.0.") if not 1 <= int(top_k) <= 64: raise ToolExecutionError("PixelRow top color choices must be between 1 and 64.") if int(frame_interval) not in {1, 2, 4, 8, 16}: raise ToolExecutionError("PixelRow frame interval must be 1, 2, 4, 8, or 16 rows.") if not 0 <= int(preview_interval) <= 128: raise ToolExecutionError("PixelRow live preview interval must be between 0 and 128 rows.") if len(prompt) > 500: raise ToolExecutionError("The PixelRow creative note must be 500 characters or shorter.")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model, checkpoint = load_checkpoint(selected, device) height = model.config.resolution rows_to_generate = min(int(steps), height) effective_top_k = min(int(top_k), model.config.color_bins) if int(steps) > height: context.log( f"This model is {height}px tall, so PixelRow will stop after its {height} native rows." ) if effective_top_k != int(top_k): context.log( f"This model has {model.config.color_bins} color levels; top color choices was capped to that value." )
count = int(image_count) base_seed = int(seed) if base_seed <= 0: base_seed = random.SystemRandom().randint(1, 2_147_483_647 - count) if base_seed + count - 1 > 2_147_483_647: raise ToolExecutionError("The PixelRow seed is too large for this image count.")
output = generation_output_folder(context.root, context.tool.id, name) timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") image_paths: list[str] = [] frame_folders: list[str] = [] context.log( f"Loaded {name}: {height}x{height}, {model.config.color_bins} color levels, device {device}." ) context.log("PixelRow uses the creative note as metadata; generation is unconditional.")
try: for image_index in range(count): context.checkpoint() current_seed = base_seed + image_index torch_generator = torch.Generator(device=device) torch_generator.manual_seed(current_seed) frame_folder = output / "row_progress" / f"{timestamp}_{context.job_id}_seed_{current_seed}" last_frame_path: Path | None = None
def row_ready(completed_rows: int, canvas: torch.Tensor) -> None: nonlocal last_frame_path context.checkpoint() overall = ((image_index * rows_to_generate) + completed_rows) / max(1, count * rows_to_generate) context.progress( max(1, min(99, round(overall * 100))), f"Image {image_index + 1} of {count} · row {completed_rows} of {rows_to_generate}", current=completed_rows, total=rows_to_generate, image_index=image_index, image_count=count, unit="row", ) save_frame = bool(save_progress_frames) and ( completed_rows % int(frame_interval) == 0 or completed_rows == rows_to_generate ) publish_preview = int(preview_interval) > 0 and ( completed_rows % int(preview_interval) == 0 or completed_rows == rows_to_generate ) if save_frame: last_frame_path = frame_folder / f"row_{completed_rows:04d}.png" save_canvas(canvas, last_frame_path, completed_rows=completed_rows) if publish_preview: preview_path = last_frame_path if preview_path is None or not preview_path.is_file(): preview_path = output / ".live" / context.job_id / f"image_{image_index + 1:03d}.png" save_canvas(canvas, preview_path, completed_rows=completed_rows) context.preview( preview_path, kind="generation", current=completed_rows, total=rows_to_generate, image_index=image_index, image_count=count, seed=current_seed, steps=rows_to_generate, )
canvas = model.generate( rows=rows_to_generate, temperature=float(temperature), top_k=effective_top_k, generator=torch_generator, row_callback=row_ready, ) destination = output / ( f"{timestamp}_{context.job_id}_PixelRow_seed_{current_seed}_rows_{rows_to_generate}.png" ) save_canvas(canvas, destination, completed_rows=rows_to_generate) image_paths.append(str(destination)) if bool(save_progress_frames): frame_folders.append(str(frame_folder)) except torch.cuda.OutOfMemoryError as exc: if device.type == "cuda": torch.cuda.empty_cache() raise ToolExecutionError( "PixelRow ran out of VRAM while generating. Generate fewer images in one batch." ) from exc
created_at = datetime.now(timezone.utc).isoformat() metadata = { "version": 1, "provider_id": context.tool.id, "provider_name": context.tool.name, "model_name": name, "model_path": str(selected), "model_type": "pixelrow", "prompt": prompt.strip(), "prompt_behavior": "label_only", "seed": base_seed, "image_seeds": [base_seed + index for index in range(count)], "image_count": count, "steps": rows_to_generate, "sampler": sampler, "aspect_ratio": aspect_ratio, "resolution": height, "temperature": float(temperature), "top_k": effective_top_k, "save_progress_frames": bool(save_progress_frames), "frame_interval": int(frame_interval), "row_progress_folders": frame_folders, "preview_interval": int(preview_interval), "images": image_paths, "checkpoint_epoch": int(checkpoint.get("completed_epochs", 0) or 0), "created_at": created_at, } write_json(generation_metadata_path(output, timestamp, context.job_id), metadata) # Leave only durable showcase frames; the live-preview file is an implementation detail. live_folder = output / ".live" / context.job_id if live_folder.is_dir(): for path in live_folder.glob("*.png"): try: path.unlink() except OSError: pass try: live_folder.rmdir() except OSError: pass try: live_folder.parent.rmdir() except OSError: pass context.progress(100, f"Generated {count} PixelRow image(s)") return { "output_folder": str(output), "assets": [{ "kind": "generation", "name": f"{name} · {timestamp}", "path": str(output), "trainer": "pixelrow", "metadata": { "row_progress_folders": frame_folders, "rows_generated": rows_to_generate, }, }], }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301PLUGIN_ID = "pixelrow"
MODEL_INFO = { "name": "PixelRow", "version": "0.1", "category": "Image Generation", "description": ( "Experimental autoregressive image model that constructs pictures from " "top to bottom, predicting one complete RGB row at a time." ), "architecture": "autoregressive_rows", "status": "experimental", "output_type": "image", "capabilities": [ "fresh_training", "resume_training", "image_generation", "live_preview", "row_progress_frames", ], "input_formats": ["image folder"], "output_formats": ["PixelRow checkpoint", "PNG image", "PNG row progress frames"], "hardware": {"recommended_vram_gb": 6, "recommended_system_ram_gb": 16}, "vram_behavior": { "scales_with": ["resolution", "batch_size", "color_bins", "hidden_size"], "estimate": "Moderate at 64px; reduce batch size first when training at 128px.", },}
TRAINING_SETTINGS = { "resolution": { "label": "Resolution", "type": "choice", "options": [32, 64, 128], "default": 64, "group": "Basic", "description": "PixelRow currently learns square images. Start at 64px for the first car experiment.", }, "resize_mode": { "label": "Image fitting", "type": "choice", "options": ["fill", "fit", "stretch"], "default": "fill", "group": "Dataset", "description": "Fill preserves proportions and center-crops; fit pads; stretch changes proportions.", }, "horizontal_flip": { "label": "Random horizontal flip", "type": "bool", "default": True, "group": "Dataset", }, "batch_size": { "label": "Batch size", "type": "int", "default": 8, "min": 1, "max": 64, "group": "Basic", }, "learning_rate": { "label": "Learning rate", "type": "float", "default": 0.0002, "min": 0.0000001, "max": 0.1, "decimals": 7, "step": 0.00005, "group": "Optimization", }, "gradient_accumulation_steps": { "label": "Gradient accumulation", "type": "int", "default": 1, "min": 1, "max": 64, "group": "Optimization", }, "workers": { "label": "Loader workers", "type": "int", "default": 0, "min": 0, "max": 16, "group": "Dataset", "description": "Zero is the safest choice for the Windows desktop app.", }, "mixed_precision": { "label": "Precision", "type": "choice", "options": ["fp16", "no"], "default": "fp16", "group": "Optimization", }, "hidden_size": { "label": "Spatial memory channels", "type": "choice", "options": [64, 128, 192, 256], "default": 128, "group": "PixelRow", "advanced": True, "description": "Column-aware memory carried from completed rows into the next-row prediction.", }, "recurrent_layers": { "label": "Sequence layers", "type": "int", "default": 2, "min": 1, "max": 4, "group": "PixelRow", "advanced": True, }, "row_channels": { "label": "Row feature channels", "type": "choice", "options": [32, 64, 96, 128], "default": 64, "group": "PixelRow", "advanced": True, }, "color_bins": { "label": "Color levels per channel", "type": "choice", "options": [16, 32, 64], "default": 32, "group": "PixelRow", "advanced": True, "description": "PixelRow predicts a color category instead of averaging raw RGB values.", }, "edge_loss_weight": { "label": "Line-detail strength", "type": "float", "default": 0.05, "min": 0.0, "max": 1.0, "decimals": 3, "step": 0.01, "group": "PixelRow", "advanced": True, "description": "Encourages horizontal and vertical color boundaries to match the training images.", }, "save_every": { "label": "Save every", "type": "int", "default": 10, "min": 1, "max": 1000, "group": "Checkpoints", }, "preview_enabled": { "label": "Generate previews while training", "type": "bool", "default": True, "group": "Preview", }, "preview_every": { "label": "Preview interval", "type": "int", "default": 5, "min": 1, "max": 100000, "group": "Preview", }, "preview_prompt": { "label": "Preview note", "type": "text", "default": "", "group": "Preview", }, "preview_seed": { "label": "Preview seed", "type": "int", "default": 123456789, "min": 0, "max": 2147483647, "group": "Preview", },}
GENERATION_SETTINGS = { "prompt": { "label": "Creative note", "type": "multiline_text", "default": "", "group": "Generation", }, "image_count": { "label": "Images", "type": "int", "default": 1, "min": 1, "max": 48, "group": "Generation", }, "steps": { "label": "Rows to generate", "type": "int", "default": 128, "min": 1, "max": 128, "group": "Generation", "description": "Values above the trained image height automatically produce the complete image.", }, "sampler": { "label": "Row sampling", "type": "choice", "options": ["Categorical"], "default": "Categorical", "group": "Generation", }, "aspect_ratio": { "label": "Aspect ratio", "type": "choice", "options": ["1:1 (Native)"], "default": "1:1 (Native)", "group": "Generation", }, "seed": { "label": "Seed", "type": "int", "default": 0, "min": 0, "max": 2147483647, "group": "Generation", }, "temperature": { "label": "Creativity", "type": "float", "default": 0.85, "min": 0.05, "max": 3.0, "decimals": 2, "step": 0.05, "group": "PixelRow", }, "top_k": { "label": "Top color choices", "type": "int", "default": 4, "min": 1, "max": 64, "group": "PixelRow", "description": "Smaller values are more conservative; larger values add variation.", }, "save_progress_frames": { "label": "Save row-build frames", "type": "bool", "default": True, "group": "Row Showcase", }, "frame_interval": { "label": "Save every N rows", "type": "choice", "options": [1, 2, 4, 8, 16], "default": 2, "group": "Row Showcase", }, "preview_interval": { "label": "Rows per live preview", "type": "int", "default": 4, "min": 0, "max": 128, "group": "Preview", },}
TRAINING_TOOL = { "id": "pixelrow_trainer", "name": "PixelRow Trainer", "description": "Trains an experimental model to construct images one RGB row at a time.", "capabilities": ["fresh_training", "resume_training", "progress", "pause", "cancel", "live_preview"], "backend": { "type": "python", "module": "adam.model_plugins_builtin.pixelrow.trainer", "function": "train", },}
GENERATION_TOOL = { "id": "pixelrow_generator", "name": "PixelRow Generator", "description": "Builds images from top to bottom and can save the visible row-by-row process.", "model_trainers": ["pixelrow"], "capabilities": ["image_generation", "seed", "batch", "row_progress_frames", "live_preview", "progress", "cancel"], "generation_options": { "samplers": ["Categorical"], "aspect_ratios": ["1:1 (Native)"], "step_min": 1, "step_max": 128, "step_default": 128, "step_label": "Rows", "preview_step_label": "Rows / preview", "preview_step_default": 4, }, "backend": { "type": "python", "module": "adam.model_plugins_builtin.pixelrow.generator", "function": "generate", },}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244from __future__ import annotations
from dataclasses import asdict, dataclassfrom typing import Any, Callable
import torchfrom torch import Tensor, nnfrom torch.nn import functional as F
MODEL_FORMAT_VERSION = 1
@dataclass(frozen=True, slots=True)class PixelRowConfig: resolution: int = 64 hidden_size: int = 128 recurrent_layers: int = 2 row_channels: int = 64 color_bins: int = 32
def __post_init__(self) -> None: if self.resolution not in {32, 64, 128}: raise ValueError("PixelRow resolution must be 32, 64, or 128.") if not 64 <= self.hidden_size <= 1024: raise ValueError("PixelRow hidden size must be between 64 and 1024.") if not 1 <= self.recurrent_layers <= 4: raise ValueError("PixelRow recurrent layers must be between 1 and 4.") if not 16 <= self.row_channels <= 256: raise ValueError("PixelRow row channels must be between 16 and 256.") if self.color_bins not in {16, 32, 64}: raise ValueError("PixelRow color bins must be 16, 32, or 64.")
def to_dict(self) -> dict[str, int]: return asdict(self)
@classmethod def from_dict(cls, payload: dict[str, Any]) -> "PixelRowConfig": return cls( resolution=int(payload.get("resolution", 64)), hidden_size=int(payload.get("hidden_size", 128)), recurrent_layers=int(payload.get("recurrent_layers", 2)), row_channels=int(payload.get("row_channels", 64)), color_bins=int(payload.get("color_bins", 32)), )
class ResidualRowBlock(nn.Module): def __init__(self, channels: int) -> None: super().__init__() groups = max(1, min(8, channels // 8)) self.norm = nn.GroupNorm(groups, channels) self.conv1 = nn.Conv1d(channels, channels, 5, padding=2) self.conv2 = nn.Conv1d(channels, channels, 3, padding=1)
def forward(self, value: Tensor) -> Tensor: residual = value value = self.conv1(F.gelu(self.norm(value))) value = self.conv2(F.gelu(value)) return value + residual
class PixelRowModel(nn.Module): """A row-level autoregressive model with categorical RGB outputs.
During training the GRU sees only the rows above each target row. The row decoder predicts all pixels in the next row together, so generation takes exactly one autoregressive decision per image row. """
def __init__(self, config: PixelRowConfig) -> None: super().__init__() self.config = config self.row_encoder = nn.Sequential( nn.Conv1d(3, config.hidden_size, 5, padding=2), nn.GELU(), nn.Conv1d(config.hidden_size, config.hidden_size, 5, padding=2), nn.GELU(), ) self.start_embedding = nn.Parameter( torch.zeros(1, 1, config.hidden_size, config.resolution) ) self.row_position = nn.Embedding(config.resolution, config.hidden_size) self.sequence = nn.GRU( input_size=config.hidden_size, hidden_size=config.hidden_size, num_layers=config.recurrent_layers, batch_first=True, dropout=0.1 if config.recurrent_layers > 1 else 0.0, ) self.hidden_to_row = nn.Conv1d(config.hidden_size, config.row_channels, 1) self.column_features = nn.Parameter( torch.randn(1, config.row_channels, config.resolution) * 0.02 ) self.row_decoder = nn.Sequential( ResidualRowBlock(config.row_channels), ResidualRowBlock(config.row_channels), nn.GroupNorm(max(1, min(8, config.row_channels // 8)), config.row_channels), nn.GELU(), nn.Conv1d(config.row_channels, 3 * config.color_bins, 1), ) nn.init.normal_(self.start_embedding, std=0.02)
def encode_rows(self, rows: Tensor) -> Tensor: """Encode BxHx3xW normalized RGB rows into BxHxCxW features.""" batch, height, channels, width = rows.shape if channels != 3 or width != self.config.resolution: raise ValueError("PixelRow input rows do not match the model configuration.") encoded = self.row_encoder(rows.reshape(batch * height, channels, width)) return encoded.reshape(batch, height, self.config.hidden_size, width)
def decode_hidden(self, hidden: Tensor) -> Tensor: """Decode BxHxCxW states to BxHx3xBinsxW logits.""" batch, height, channels, width = hidden.shape features = self.hidden_to_row(hidden.reshape(batch * height, channels, width)) features = features + self.column_features logits = self.row_decoder(features) return logits.reshape( batch, height, 3, self.config.color_bins, self.config.resolution, )
def forward(self, target_rows: Tensor) -> Tensor: """Teacher-force the image while preserving strict top-to-bottom causality.""" batch, height, channels, width = target_rows.shape if height != self.config.resolution or channels != 3 or width != self.config.resolution: raise ValueError("PixelRow expects square BxHx3xW tensors at its trained resolution.") encoded = self.encode_rows(target_rows) inputs = torch.cat( (self.start_embedding.expand(batch, -1, -1, -1), encoded[:, :-1]), dim=1 ) positions = self.row_position(torch.arange(height, device=target_rows.device)) inputs = inputs + positions.view(1, height, self.config.hidden_size, 1) # Each column gets a recurrent sequence, while the row encoder and # decoder exchange local horizontal context through 1D convolutions. column_sequences = inputs.permute(0, 3, 1, 2).reshape( batch * width, height, self.config.hidden_size ) sequence_output, _state = self.sequence(column_sequences) spatial_output = sequence_output.reshape( batch, width, height, self.config.hidden_size ).permute(0, 2, 3, 1).contiguous() return self.decode_hidden(spatial_output)
def loss(self, images: Tensor, *, edge_loss_weight: float = 0.0) -> tuple[Tensor, dict[str, float]]: targets = quantize_images(images, self.config.color_bins) normalized = dequantize_images(targets, self.config.color_bins) logits = self(normalized) categorical = F.cross_entropy( logits.permute(0, 1, 2, 4, 3).reshape(-1, self.config.color_bins), targets.reshape(-1), ) edge_loss = categorical.new_zeros(()) if edge_loss_weight > 0: levels = torch.linspace(-1.0, 1.0, self.config.color_bins, device=images.device) expected = (logits.softmax(dim=3) * levels.view(1, 1, 1, -1, 1)).sum(dim=3) horizontal = F.l1_loss(expected[..., 1:] - expected[..., :-1], normalized[..., 1:] - normalized[..., :-1]) vertical = F.l1_loss(expected[:, 1:] - expected[:, :-1], normalized[:, 1:] - normalized[:, :-1]) edge_loss = (horizontal + vertical) * 0.5 total = categorical + float(edge_loss_weight) * edge_loss return total, { "categorical": float(categorical.detach().item()), "edge": float(edge_loss.detach().item()), }
@torch.inference_mode() def generate( self, *, rows: int | None = None, temperature: float = 1.0, top_k: int = 8, generator: torch.Generator | None = None, row_callback: Callable[[int, Tensor], None] | None = None, ) -> Tensor: """Generate one image and optionally report its partially completed canvas.""" self.eval() total_rows = min(max(1, int(rows or self.config.resolution)), self.config.resolution) temperature = max(0.05, float(temperature)) top_k = min(max(1, int(top_k)), self.config.color_bins) device = next(self.parameters()).device canvas = torch.zeros(1, self.config.resolution, 3, self.config.resolution, device=device) recurrent_state: Tensor | None = None previous_embedding: Tensor | None = None for row_index in range(total_rows): if previous_embedding is None: step_input = self.start_embedding[:, 0] else: step_input = previous_embedding position = self.row_position(torch.tensor([row_index], device=device)).unsqueeze(-1) column_input = (step_input + position).permute(0, 2, 1).reshape( self.config.resolution, 1, self.config.hidden_size ) column_output, recurrent_state = self.sequence(column_input, recurrent_state) spatial_output = column_output.reshape( 1, self.config.resolution, 1, self.config.hidden_size ).permute(0, 2, 3, 1).contiguous() logits = self.decode_hidden(spatial_output)[:, 0] / temperature if top_k < self.config.color_bins: best_values, best_indices = torch.topk(logits, top_k, dim=2) probabilities = best_values.softmax(dim=2) sampled_offset = torch.multinomial( probabilities.permute(0, 1, 3, 2).reshape(-1, top_k), 1, generator=generator, ).reshape(1, 3, self.config.resolution) sampled = best_indices.permute(0, 1, 3, 2).gather( 3, sampled_offset.unsqueeze(-1) ).squeeze(-1) else: probabilities = logits.softmax(dim=2) sampled = torch.multinomial( probabilities.permute(0, 1, 3, 2).reshape(-1, self.config.color_bins), 1, generator=generator, ).reshape(1, 3, self.config.resolution) normalized_row = dequantize_images(sampled, self.config.color_bins) canvas[:, row_index] = normalized_row previous_embedding = self.row_encoder(normalized_row) if row_callback is not None: row_callback(row_index + 1, canvas[0].detach()) return canvas[0]
def quantize_images(images: Tensor, color_bins: int) -> Tensor: """Convert normalized RGB values in [-1, 1] to categorical color levels.""" return ((images.clamp(-1, 1) + 1.0) * 0.5 * (color_bins - 1)).round().long()
def dequantize_images(indices: Tensor, color_bins: int) -> Tensor: """Convert categorical color levels back to normalized RGB values.""" return indices.float() * (2.0 / (color_bins - 1)) - 1.0
def canvas_to_uint8(canvas: Tensor, completed_rows: int | None = None) -> Tensor: """Convert Hx3xW normalized rows to a display-ready HxWx3 byte tensor.""" image = ((canvas.detach().float().cpu().clamp(-1, 1) + 1.0) * 127.5).round().byte() image = image.permute(0, 2, 1).contiguous() if completed_rows is not None and completed_rows < image.shape[0]: image[completed_rows:] = 32 return image123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411from __future__ import annotations
import randomfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Any
import torchfrom PIL import Image, ImageOps, ImageStatfrom torch.utils.data import DataLoader, Dataset
from adam.executor import ToolExecutionError
from .common import ( CONFIG_NAME, FINAL_CHECKPOINT_NAME, ensure_below, image_files, load_checkpoint, resolve_checkpoint, safe_model_name, save_canvas, write_json,)from .model import MODEL_FORMAT_VERSION, PixelRowConfig, PixelRowModel
class PixelRowImageDataset(Dataset[torch.Tensor]): def __init__( self, paths: list[Path], *, resolution: int, resize_mode: str, horizontal_flip: bool, ) -> None: self.paths = paths self.resolution = resolution self.resize_mode = resize_mode self.horizontal_flip = horizontal_flip
def __len__(self) -> int: return len(self.paths)
def __getitem__(self, index: int) -> torch.Tensor: path = self.paths[index] try: with Image.open(path) as opened: image = opened.convert("RGB") if self.resize_mode == "fill": image = ImageOps.fit( image, (self.resolution, self.resolution), method=Image.Resampling.LANCZOS, ) elif self.resize_mode == "fit": mean = tuple(int(value) for value in ImageStat.Stat(image.resize((1, 1))).mean) image = ImageOps.pad( image, (self.resolution, self.resolution), method=Image.Resampling.LANCZOS, color=mean, ) else: image = image.resize( (self.resolution, self.resolution), Image.Resampling.LANCZOS ) if self.horizontal_flip and random.random() < 0.5: image = image.transpose(Image.Transpose.FLIP_LEFT_RIGHT) buffer = bytearray(image.tobytes()) except (OSError, ValueError) as exc: raise RuntimeError(f"Could not read training image {path.name}: {exc}") from exc pixels = torch.frombuffer(buffer, dtype=torch.uint8).reshape( self.resolution, self.resolution, 3 ) # Model layout is H rows x RGB channels x W columns. return pixels.permute(0, 2, 1).float().div(127.5).sub(1.0)
def _checkpoint_payload( model: PixelRowModel, optimizer: torch.optim.Optimizer, *, model_name: str, dataset_dir: Path, completed_epochs: int, global_step: int, training_settings: dict[str, Any],) -> dict[str, Any]: return { "format_version": MODEL_FORMAT_VERSION, "architecture": "autoregressive_rows", "model_name": model_name, "config": model.config.to_dict(), "model_state": model.state_dict(), "optimizer_state": optimizer.state_dict(), "completed_epochs": int(completed_epochs), "global_step": int(global_step), "dataset_dir": str(dataset_dir), "training_settings": training_settings, "saved_at": datetime.now(timezone.utc).isoformat(), }
def _save_checkpoint(path: Path, payload: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") torch.save(payload, temporary) temporary.replace(path)
def _preview( context, model: PixelRowModel, output: Path, *, epoch: int, next_epoch: int, seed: int, prompt: str,) -> None: device = next(model.parameters()).device generator = torch.Generator(device=device) generator.manual_seed(int(seed)) canvas = model.generate( rows=model.config.resolution, temperature=0.85, top_k=min(4, model.config.color_bins), generator=generator, ) destination = output / "previews" / f"preview_epoch_{epoch:06d}.png" save_canvas(canvas, destination, completed_rows=model.config.resolution) context.preview( destination, epoch=epoch, next_epoch=next_epoch, prompt=prompt, seed=seed, steps=model.config.resolution, )
def train( context, dataset_dir: str, model_name: str, epochs: int, output_dir: str, resume_from: str = "", resolution: int = 64, resize_mode: str = "fill", horizontal_flip: bool = True, batch_size: int = 8, learning_rate: float = 0.0002, gradient_accumulation_steps: int = 1, workers: int = 0, mixed_precision: str = "fp16", hidden_size: int = 128, recurrent_layers: int = 2, row_channels: int = 64, color_bins: int = 32, edge_loss_weight: float = 0.05, save_every: int = 10, preview_enabled: bool = True, preview_every: int = 5, preview_prompt: str = "", preview_seed: int = 123456789,) -> dict[str, Any]: """Train PixelRow inside ADAM's managed plugin-output area.""" name = safe_model_name(model_name) dataset = Path(dataset_dir).expanduser().resolve() if not dataset.is_dir(): raise ToolExecutionError("The selected PixelRow dataset folder no longer exists.") training_dataset = dataset accepted_frames = dataset / "frames" frame_paths = image_files(accepted_frames) if accepted_frames.is_dir() else [] if frame_paths: training_dataset = accepted_frames paths = frame_paths else: paths = image_files(dataset) if len(paths) < 2: raise ToolExecutionError("PixelRow needs at least two readable image files before training can start.")
output_root = (context.root.resolve() / "data" / "model_plugin_outputs" / "pixelrow").resolve() output = ensure_below(Path(output_dir), output_root, "PixelRow output") if output.exists() and not output.is_dir(): raise ToolExecutionError("The PixelRow output path must be a folder.") if output.exists() and any(output.iterdir()): raise ToolExecutionError("The PixelRow output folder is not empty. Choose a new model output.") output.mkdir(parents=True, exist_ok=True)
if resize_mode not in {"fill", "fit", "stretch"}: raise ToolExecutionError("PixelRow image fitting must be fill, fit, or stretch.") if not 1 <= int(epochs) <= 100_000: raise ToolExecutionError("PixelRow epochs must be between 1 and 100000.") if not 1 <= int(batch_size) <= 64 or not 1 <= int(gradient_accumulation_steps) <= 64: raise ToolExecutionError("PixelRow batch size and gradient accumulation must be between 1 and 64.") if not 1e-7 <= float(learning_rate) <= 0.1: raise ToolExecutionError("PixelRow learning rate must be between 0.0000001 and 0.1.") if not 0 <= int(workers) <= 16 or mixed_precision not in {"fp16", "no"}: raise ToolExecutionError("PixelRow loader workers or precision is outside the supported range.") if not 0.0 <= float(edge_loss_weight) <= 1.0: raise ToolExecutionError("PixelRow line-detail strength must be between 0 and 1.") if not 1 <= int(save_every) <= 1000 or not 1 <= int(preview_every) <= 100_000: raise ToolExecutionError("PixelRow save and preview intervals must be positive.")
device = torch.device("cuda" if torch.cuda.is_available() else "cpu") resume_payload: dict[str, Any] | None = None if resume_from.strip(): resume_path = ensure_below( resolve_checkpoint(Path(resume_from)), output_root, "PixelRow resume checkpoint" ) model, resume_payload = load_checkpoint(resume_path, device) config = model.config context.log( "Continuing with the checkpoint architecture: " f"{config.resolution}px, width {config.hidden_size}, {config.color_bins} color levels." ) else: try: config = PixelRowConfig( resolution=int(resolution), hidden_size=int(hidden_size), recurrent_layers=int(recurrent_layers), row_channels=int(row_channels), color_bins=int(color_bins), ) except ValueError as exc: raise ToolExecutionError(str(exc)) from exc model = PixelRowModel(config).to(device)
dataset_object = PixelRowImageDataset( paths, resolution=config.resolution, resize_mode=resize_mode, horizontal_flip=bool(horizontal_flip), ) loader = DataLoader( dataset_object, batch_size=int(batch_size), shuffle=True, num_workers=int(workers), pin_memory=device.type == "cuda", drop_last=False, ) optimizer = torch.optim.AdamW(model.parameters(), lr=float(learning_rate), betas=(0.9, 0.95)) start_epoch = 0 global_step = 0 if resume_payload is not None: start_epoch = int(resume_payload.get("completed_epochs", 0) or 0) global_step = int(resume_payload.get("global_step", 0) or 0) optimizer_state = resume_payload.get("optimizer_state") if isinstance(optimizer_state, dict): try: optimizer.load_state_dict(optimizer_state) for group in optimizer.param_groups: group["lr"] = float(learning_rate) except (ValueError, RuntimeError): context.log("The previous optimizer state was incompatible; continuing with a fresh optimizer.")
use_fp16 = mixed_precision == "fp16" and device.type == "cuda" if mixed_precision == "fp16" and not use_fp16: context.log("FP16 requires CUDA; PixelRow will train in full precision on this device.") try: scaler = torch.amp.GradScaler("cuda", enabled=use_fp16) except (AttributeError, TypeError): # PyTorch 2.2 compatibility. scaler = torch.cuda.amp.GradScaler(enabled=use_fp16) accumulation = int(gradient_accumulation_steps) requested_epochs = int(epochs) final_epoch = start_epoch + requested_epochs batches_per_epoch = max(1, len(loader)) total_batches = requested_epochs * batches_per_epoch settings = { "resolution": config.resolution, "resize_mode": resize_mode, "horizontal_flip": bool(horizontal_flip), "batch_size": int(batch_size), "learning_rate": float(learning_rate), "gradient_accumulation_steps": accumulation, "workers": int(workers), "mixed_precision": mixed_precision, "hidden_size": config.hidden_size, "recurrent_layers": config.recurrent_layers, "row_channels": config.row_channels, "color_bins": config.color_bins, "edge_loss_weight": float(edge_loss_weight), } write_json(output / CONFIG_NAME, { "format_version": MODEL_FORMAT_VERSION, "model_type": "pixelrow", "model_name": name, **config.to_dict(), }) context.log( f"Training PixelRow on {len(paths)} images from {training_dataset} at " f"{config.resolution}x{config.resolution}, " f"batch {batch_size}, learning rate {learning_rate}, device {device}." ) optimizer.zero_grad(set_to_none=True) processed_batches = 0 last_loss = 0.0 try: for epoch in range(start_epoch + 1, final_epoch + 1): model.train() epoch_loss = 0.0 for batch_index, images in enumerate(loader, 1): context.checkpoint() images = images.to(device, non_blocking=device.type == "cuda") with torch.autocast(device_type=device.type, dtype=torch.float16, enabled=use_fp16): loss, parts = model.loss(images, edge_loss_weight=float(edge_loss_weight)) scaled_loss = loss / accumulation scaler.scale(scaled_loss).backward() if batch_index % accumulation == 0 or batch_index == batches_per_epoch: scaler.unscale_(optimizer) torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0) scaler.step(optimizer) scaler.update() optimizer.zero_grad(set_to_none=True) global_step += 1 last_loss = float(loss.detach().item()) epoch_loss += last_loss processed_batches += 1 percent = max(1, min(99, round(processed_batches * 100 / total_batches))) context.progress( percent, f"Epoch {epoch} of {final_epoch} · loss {last_loss:.4f}", epoch=epoch, total_epochs=final_epoch, current_step=processed_batches, total_steps=total_batches, unit="batch", loss=last_loss, categorical_loss=parts["categorical"], edge_loss=parts["edge"], )
payload = _checkpoint_payload( model, optimizer, model_name=name, dataset_dir=dataset, completed_epochs=epoch, global_step=global_step, training_settings=settings, ) if epoch % int(save_every) == 0: _save_checkpoint(output / "checkpoints" / f"epoch_{epoch:06d}.pt", payload) if bool(preview_enabled) and epoch % int(preview_every) == 0: _preview( context, model, output, epoch=epoch, next_epoch=min(final_epoch, epoch + int(preview_every)), seed=int(preview_seed), prompt=preview_prompt, ) context.log(f"Finished epoch {epoch}; average loss {epoch_loss / batches_per_epoch:.4f}.") except torch.cuda.OutOfMemoryError as exc: if device.type == "cuda": torch.cuda.empty_cache() raise ToolExecutionError( "PixelRow ran out of VRAM. Reduce batch size first, then sequence width or resolution." ) from exc
final_payload = _checkpoint_payload( model, optimizer, model_name=name, dataset_dir=dataset, completed_epochs=final_epoch, global_step=global_step, training_settings=settings, ) final_checkpoint = output / FINAL_CHECKPOINT_NAME _save_checkpoint(final_checkpoint, final_payload) write_json(output / "training_metadata.json", { "format_version": MODEL_FORMAT_VERSION, "model_type": "pixelrow", "architecture": "autoregressive_rows", "model_name": name, "dataset_dir": str(dataset), "image_count": len(paths), "completed_epochs": final_epoch, "epochs_this_run": requested_epochs, "global_step": global_step, "final_loss": last_loss, "checkpoint": str(final_checkpoint), "settings": settings, "finished_at": datetime.now(timezone.utc).isoformat(), }) context.progress(100, "PixelRow training completed") return { "output_folder": str(output), "model_name": name, "assets": [{ "kind": "model", "name": name, "path": str(output), "trainer": "pixelrow", "dataset_path": str(dataset), "checkpoint": str(final_checkpoint), "epochs": final_epoch, "metadata": { "architecture": "autoregressive_rows", "resolution": config.resolution, "color_bins": config.color_bins, }, }], }44 unmodified lines4546474849505144 unmodified lines"image_count": {"label": "Images", "type": "int", "default": 1, "min": 1, "max": 48, "group": "Generation"},"steps": {"label": "Steps", "type": "int", "default": 30, "min": 1, "max": 150, "group": "Generation"},"cfg_scale": {"label": "CFG scale", "type": "float", "default": 7.0, "min": 0.1, "max": 30.0, "decimals": 2, "step": 0.5, "group": "Generation"},"sampler": {"label": "Sampler", "type": "choice", "options": ["DPM++ 2M", "DPM++ SDE", "Euler", "Euler a", "DDIM"], "default": "DPM++ 2M", "group": "Generation"},"aspect_ratio": {"label": "Aspect ratio", "type": "choice", "options": ["1:1 (Square)", "4:3 (Landscape)", "3:4 (Portrait)", "3:2 (Landscape)", "2:3 (Portrait)", "16:9 (Widescreen)", "9:16 (Vertical)"], "default": "1:1 (Square)", "group": "Generation"},"width": {"label": "Width", "type": "int", "default": 1024, "min": 256, "max": 2048, "group": "Generation"},"height": {"label": "Height", "type": "int", "default": 1024, "min": 256, "max": 2048, "group": "Generation"},44 unmodified lines4546474849505144 unmodified lines"image_count": {"label": "Images", "type": "int", "default": 1, "min": 1, "max": 48, "group": "Generation"},"steps": {"label": "Steps", "type": "int", "default": 30, "min": 1, "max": 150, "group": "Generation"},"cfg_scale": {"label": "CFG scale", "type": "float", "default": 7.0, "min": 0.1, "max": 30.0, "decimals": 2, "step": 0.5, "group": "Generation"},"sampler": {"label": "Sampler", "type": "choice", "options": ["DPM++ 2M", "DPM++ 2M Karras", "DPM++ 2M SDE", "DPM++ 2M SDE Karras", "DPM++ SDE", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "LMS", "DDIM"], "default": "DPM++ 2M", "group": "Generation"},"aspect_ratio": {"label": "Aspect ratio", "type": "choice", "options": ["1:1 (Square)", "4:3 (Landscape)", "3:4 (Portrait)", "3:2 (Landscape)", "2:3 (Portrait)", "16:9 (Widescreen)", "9:16 (Vertical)"], "default": "1:1 (Square)", "group": "Generation"},"width": {"label": "Width", "type": "int", "default": 1024, "min": 256, "max": 2048, "group": "Generation"},"height": {"label": "Height", "type": "int", "default": 1024, "min": 256, "max": 2048, "group": "Generation"},
1"""Wan 2.1 video LoRA integration."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950PLUGIN_ID = "wan_video"
MODEL_INFO = { "name": "Wan Video LoRA", "version": "1.0", "category": "Video Generation", "description": "Train Wan 2.1 T2V 1.3B LoRAs on captioned clips and generate MP4 videos with the connected LoRAVideoTrainer.", "architecture": "wan21_t2v_1_3b_lora", "status": "experimental", "output_type": "video", "workspace": "video_lora", "input_formats": ["captioned video folder"], "output_formats": ["safetensors", "mp4"], "hardware": {"recommended_vram_gb": 12, "recommended_system_ram_gb": 32}, "capabilities": ["fresh_training", "resume_training", "video_generation"],}
TRAINING_SETTINGS = { "trigger_word": {"label": "Trigger word", "type": "text", "default": "subject_token", "required": True, "group": "Dataset"}, "resolution": {"label": "Training resolution", "type": "choice", "options": ["448x256", "256x448"], "default": "448x256", "group": "Dataset"}, "target_frames": {"label": "Frame buckets", "type": "choice", "options": ["25", "49", "25,49"], "default": "25,49", "group": "Dataset", "description": "A clip must have at least the shortest selected frame count. Longer clips can supply multiple buckets."}, "batch_size": {"label": "Batch size", "type": "int", "default": 1, "min": 1, "max": 4, "group": "Training"}, "learning_rate": {"label": "Learning rate", "type": "float", "default": 0.0001, "min": 0.0000001, "max": 0.01, "decimals": 7, "group": "Training"}, "rank": {"label": "LoRA rank", "type": "int", "default": 16, "min": 1, "max": 128, "group": "Training"}, "alpha": {"label": "LoRA alpha", "type": "int", "default": 16, "min": 1, "max": 128, "group": "Training"}, "blocks_to_swap": {"label": "Training blocks to swap", "type": "int", "default": 20, "min": 0, "max": 29, "group": "Memory", "description": "More swapping reduces GPU memory use and increases CPU transfer time."}, "save_every": {"label": "Save every N epochs", "type": "int", "default": 2, "min": 1, "max": 1000, "group": "Checkpoints"}, "seed": {"label": "Training seed", "type": "int", "default": 42, "min": 0, "max": 2147483647, "group": "Advanced", "advanced": True},}
GENERATION_SETTINGS = { "prompt": {"label": "Prompt", "type": "multiline_text", "default": "", "required": True, "group": "Prompt"}, "format": {"label": "Video format", "type": "choice", "options": ["Landscape 832x480", "Portrait 480x832"], "default": "Landscape 832x480", "group": "Video"}, "duration": {"label": "Requested seconds", "type": "float", "default": 2.0, "min": 2.0, "max": 15.0, "decimals": 2, "step": 0.5, "group": "Video"}, "fps": {"label": "Playback FPS", "type": "int", "default": 12, "min": 4, "max": 60, "group": "Video"}, "steps": {"label": "Inference steps", "type": "int", "default": 20, "min": 1, "max": 100, "group": "Generation"}, "lora_strength": {"label": "LoRA strength", "type": "float", "default": 0.8, "min": 0.0, "max": 2.0, "decimals": 2, "step": 0.05, "group": "Generation"}, "seed": {"label": "Seed", "type": "int", "default": 1701, "min": 0, "max": 2147483647, "group": "Generation"}, "randomize_seed": {"label": "Randomize seed", "type": "bool", "default": False, "group": "Generation"}, "blocks_to_swap": {"label": "Generation blocks to swap", "type": "int", "default": 24, "min": 0, "max": 29, "group": "Memory"}, "experimental_speed": {"label": "Experimental TF32 speed mode", "type": "bool", "default": False, "group": "Advanced", "advanced": True},}
TRAINING_TOOL = { "id": "wan_video_trainer", "name": "Wan Video LoRA Trainer", "capabilities": ["fresh_training", "resume_training", "progress", "pause", "cancel"], "backend": {"type": "python", "module": "adam.tools.wan_video_adapter", "function": "train"},}GENERATION_TOOL = { "id": "wan_video_generator", "name": "Wan Video Generator", "model_trainers": ["wan_video"], "arguments": ["model_name", "model_path", *GENERATION_SETTINGS], "required_arguments": ["model_path", "prompt"], "capabilities": ["video_generation", "progress", "pause", "cancel"], "backend": {"type": "python", "module": "adam.tools.wan_video_adapter", "function": "generate"},}35 unmodified lines36373839404135 unmodified linesdef evaluate_job_output(job: Job) -> dict[str, Any]:"""Evaluate technical sample health without claiming to judge artistic quality."""if not any(step.tool_id.endswith("_trainer") for step in job.plan.steps):return {}paths = _candidate_images(job)35 unmodified lines363738394041424335 unmodified linesdef evaluate_job_output(job: Job) -> dict[str, Any]:"""Evaluate technical sample health without claiming to judge artistic quality."""if any(step.tool_id == "wan_video_trainer" for step in job.plan.steps):return {"agent": "NOVA", "status": "NEEDS VIDEO SAMPLES", "summary": "Wan training saved adapter weights. Generate a fixed-seed video in Video LoRA and review motion, subject consistency and flicker.", "sample_count": 0}if not any(step.tool_id.endswith("_trainer") for step in job.plan.steps):return {}paths = _candidate_images(job)
23 unmodified lines2425262728299 unmodified lines394041424344452 unmodified lines48495051525312 unmodified lines66676869707172737475767778798064 unmodified lines14514614714814915015115215315415515615715815916016116216312 unmodified lines1761771781791801812 unmodified lines18418518618718818923 unmodified lines21321421523 unmodified linesSUPPORTED_ACTIONS = BINARY_ACTIONS | CONTINUOUS_ACTIONS | DERIVED_ACTIONSREQUIRED_CANONICAL_ACTIONS = {"w", "a", "s", "d", "jump"}IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}METADATA_FIELDS = {"session_id", "session_started_at", "frame_index", "filename","timestamp_seconds", "camera_encoding",9 unmodified linesvalid_transitions: int = 0sessions: int = 0resolution: str = ""action_counts: dict[str, int] = field(default_factory=dict)errors: list[str] = field(default_factory=list)warnings: list[str] = field(default_factory=list)2 unmodified linesreturn not self.errorsdef dataset_directories(value: str | list[str] | tuple[str, ...]) -> list[Path]:entries = value if isinstance(value, (list, tuple)) else str(value or "").split(";")directories: list[Path] = []12 unmodified linesreturn int(match.group(1)) if match else Nonedef validate_oasis_dataset(value: str | list[str] | tuple[str, ...], *, frame_gap: int = 1) -> OasisDatasetReport:report = OasisDatasetReport()frame_gap = max(1, int(frame_gap))directories = dataset_directories(value)if not directories:report.errors.append("Select at least one Oasis action dataset folder.")return reportseen_resolution: tuple[int, int] | None = Noneaction_counts = {name: 0 for name in sorted(REQUIRED_CANONICAL_ACTIONS | CONTINUOUS_ACTIONS)}transition_total = 0session_ids: set[str] = set()64 unmodified linesf"{actions_path.name} line {line_number} points to missing frame {filename}; skipping row.")continuetry:with Image.open(frame_path) as image:image.verify()with Image.open(frame_path) as image:size = image.sizeexcept Exception as exc:report.errors.append(f"Broken image file {frame_path.name}: {exc}")continueif seen_resolution is None:seen_resolution = sizereport.resolution = f"{size[0]}x{size[1]}"elif size != seen_resolution:report.errors.append(f"Inconsistent frame resolution: {frame_path.name} is {size[0]}x{size[1]}, expected {seen_resolution[0]}x{seen_resolution[1]}.")unexpected = sorted(set(row) - SUPPORTED_ACTIONS - METADATA_FIELDS)if unexpected:report.errors.append(f"{actions_path.name} line {line_number} contains unsupported action field(s): {', '.join(unexpected[:6])}.")12 unmodified linesreport.errors.append(f"{actions_path.name} repeats frame_index {frame_index} in session {session_id}.")continueseen_keys.add(key)for name in action_counts:try:value = float(row.get(name, 0))2 unmodified linesvalue = 0.0if abs(value) > (0.5 if name in BINARY_ACTIONS else 0.02):action_counts[name] += 1row["_session_id"] = session_idrows_by_session.setdefault(session_id, []).append(row)session_ids.add(f"{resolved}:{session_id}")23 unmodified linesif report.valid_rows and not any(action_counts.values()):report.errors.append("No non-idle action labels were found. Record idle plus at least one active control.")return report23 unmodified lines242526272829309 unmodified lines40414243444546474849502 unmodified lines535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211312 unmodified lines12612712812913013113213313413513613713813914014114214314414514614764 unmodified lines21221321421521621721821922022122222322422522622722822923023112 unmodified lines2442452462472482492502 unmodified lines25325425525625725825926026123 unmodified lines28528628728828929029129229329423 unmodified linesSUPPORTED_ACTIONS = BINARY_ACTIONS | CONTINUOUS_ACTIONS | DERIVED_ACTIONSREQUIRED_CANONICAL_ACTIONS = {"w", "a", "s", "d", "jump"}IMAGE_EXTENSIONS = {".jpg", ".jpeg", ".png", ".webp", ".bmp"}RECORDED_ACTIONS = BINARY_ACTIONS | CONTINUOUS_ACTIONSMETADATA_FIELDS = {"session_id", "session_started_at", "frame_index", "filename","timestamp_seconds", "camera_encoding",9 unmodified linesvalid_transitions: int = 0sessions: int = 0resolution: str = ""capture_fps: float | None = Nonerecommended_frame_gap: int | None = Nonenative_ai_fps: float | None = Noneaction_counts: dict[str, int] = field(default_factory=dict)idle_rows: int = 0errors: list[str] = field(default_factory=list)warnings: list[str] = field(default_factory=list)2 unmodified linesreturn not self.errorsdef _read_dataset_info(directory: Path) -> dict[str, Any]:"""Read optional recorder metadata without making it a dataset requirement."""try:value = json.loads((directory / "dataset_info.json").read_text(encoding="utf-8"))return value if isinstance(value, dict) else {}except (OSError, json.JSONDecodeError):return {}def _recommended_frame_gap(capture_fps: float, _camera_encoding: str) -> int:"""Choose a playable horizon that targets about 12 genuine AI frames per second.This intentionally differs from the external trainer's older movement-focusedheuristic. A 12–15 FPS recording should train at gap 1, rather than beingslowed to a 3–5 FPS playable world before GPU speed is even considered."""target_ai_fps = 12.0return max(1, min(12, round(capture_fps / target_ai_fps)))def oasis_pace(value: str | list[str] | tuple[str, ...], *, frame_gap: int,) -> dict[str, float | int | None]:"""Return portable pacing information derived from connected recorder metadata.A model only makes one genuine frame for every prediction horizon. Displayinterpolation can look smoother, but cannot make controls more responsive."""rates: list[float] = []camera_encodings: list[str] = []for directory in dataset_directories(value):info = _read_dataset_info(directory)try:rate = float(info.get("capture_fps"))except (TypeError, ValueError):continueif rate > 0:rates.append(rate)camera_encodings.append(str(info.get("camera_encoding", "legacy_pixels")))if not rates or len({round(rate, 6) for rate in rates}) != 1:return {"capture_fps": None, "recommended_frame_gap": None, "native_ai_fps": None}capture_fps = rates[0]camera_encoding = ("relative_degrees_v1"if "relative_degrees_v1" in camera_encodingselse camera_encodings[0])gap = max(1, int(frame_gap))return {"capture_fps": capture_fps,"recommended_frame_gap": _recommended_frame_gap(capture_fps, camera_encoding),"native_ai_fps": capture_fps / gap,}def dataset_directories(value: str | list[str] | tuple[str, ...]) -> list[Path]:entries = value if isinstance(value, (list, tuple)) else str(value or "").split(";")directories: list[Path] = []12 unmodified linesreturn int(match.group(1)) if match else Nonedef validate_oasis_dataset(value: str | list[str] | tuple[str, ...], *, frame_gap: int = 1,verify_images: bool = True,) -> OasisDatasetReport:report = OasisDatasetReport()frame_gap = max(1, int(frame_gap))pace = oasis_pace(value, frame_gap=frame_gap)report.capture_fps = pace["capture_fps"] # type: ignore[assignment]report.recommended_frame_gap = pace["recommended_frame_gap"] # type: ignore[assignment]report.native_ai_fps = pace["native_ai_fps"] # type: ignore[assignment]directories = dataset_directories(value)if not directories:report.errors.append("Select at least one Oasis action dataset folder.")return reportseen_resolution: tuple[int, int] | None = Noneaction_counts = {name: 0 for name in sorted(RECORDED_ACTIONS)}transition_total = 0session_ids: set[str] = set()64 unmodified linesf"{actions_path.name} line {line_number} points to missing frame {filename}; skipping row.")continueif verify_images:try:with Image.open(frame_path) as image:image.verify()with Image.open(frame_path) as image:size = image.sizeexcept Exception as exc:report.errors.append(f"Broken image file {frame_path.name}: {exc}")continueif seen_resolution is None:seen_resolution = sizereport.resolution = f"{size[0]}x{size[1]}"elif size != seen_resolution:report.errors.append(f"Inconsistent frame resolution: {frame_path.name} is {size[0]}x{size[1]}, expected {seen_resolution[0]}x{seen_resolution[1]}.")unexpected = sorted(set(row) - SUPPORTED_ACTIONS - METADATA_FIELDS)if unexpected:report.errors.append(f"{actions_path.name} line {line_number} contains unsupported action field(s): {', '.join(unexpected[:6])}.")12 unmodified linesreport.errors.append(f"{actions_path.name} repeats frame_index {frame_index} in session {session_id}.")continueseen_keys.add(key)action_active = Falsefor name in action_counts:try:value = float(row.get(name, 0))2 unmodified linesvalue = 0.0if abs(value) > (0.5 if name in BINARY_ACTIONS else 0.02):action_counts[name] += 1action_active = Trueif not action_active:report.idle_rows += 1row["_session_id"] = session_idrows_by_session.setdefault(session_id, []).append(row)session_ids.add(f"{resolved}:{session_id}")23 unmodified linesif report.valid_rows and not any(action_counts.values()):report.errors.append("No non-idle action labels were found. Record idle plus at least one active control.")return reportdef inspect_oasis_dataset(value: str | list[str] | tuple[str, ...], *, frame_gap: int = 1,) -> OasisDatasetReport:"""Quickly inspect training-relevant labels and pacing without decoding images."""return validate_oasis_dataset(value, frame_gap=frame_gap, verify_images=False)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112"""Small, UI-independent helpers for ADAM's native Oasis Player page."""
from __future__ import annotations
import jsonimport randomfrom pathlib import Path
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".bmp"}ACTION_MODEL_TYPES = { "action_conditioned_rectified_flow_video", "action_conditioned_latent_vae_flow_video", "action_conditioned_temporal_latent_flow", "action_conditioned_temporal_pixel_flow",}LATENT_MODEL_TYPES = { "action_conditioned_latent_vae_flow_video", "action_conditioned_temporal_latent_flow",}
def is_action_model(path: str | Path) -> bool: """Return whether *path* is a complete Oasis action-world-model folder.""" folder = Path(path) try: info = json.loads((folder / "action_flow_model_info.json").read_text(encoding="utf-8")) except (OSError, ValueError, TypeError): return False weights = ( folder / "unet" / "diffusion_pytorch_model.safetensors", folder / "unet" / "diffusion_pytorch_model.bin", ) model_type = info.get("model_type") has_unet = (folder / "unet" / "config.json").is_file() and any(candidate.is_file() for candidate in weights) has_vae = (folder / "vae" / "config.json").is_file() and (folder / "vae" / "pytorch_model.bin").is_file() return model_type in ACTION_MODEL_TYPES and has_unet and (model_type not in LATENT_MODEL_TYPES or has_vae)
def model_info(path: str | Path) -> dict: """Read compatible model metadata, raising a useful error for the UI.""" folder = Path(path) if not is_action_model(folder): raise ValueError("Choose a complete Oasis action model folder.") return json.loads((folder / "action_flow_model_info.json").read_text(encoding="utf-8"))
def frame_size(info: dict) -> tuple[int, int]: """Return the trained (width, height), including legacy checkpoint metadata.""" if info.get("width") and info.get("height"): return int(info["width"]), int(info["height"]) value = str(info.get("resolution", "256x144")).lower().replace("×", "x") if "x" in value: width, height = (int(part.strip()) for part in value.split("x", 1)) return width, height width = int(value) return width, round(width * 9 / 16)
def discover_models(oasis_root: str | Path, assets=()) -> list[tuple[str, Path]]: """Find local Oasis models without copying, moving, or modifying them.""" found: dict[Path, str] = {} root = Path(oasis_root) library = root / "output_action_flow_models" if library.is_dir(): for folder in library.iterdir(): if folder.is_dir() and is_action_model(folder): found[folder.resolve()] = folder.name for asset in assets: if getattr(asset, "kind", "") != "model" or getattr(asset, "trainer", "") != "oasis": continue folder = Path(getattr(asset, "path", "")) if is_action_model(folder): found[folder.resolve()] = getattr(asset, "name", "") or folder.name return sorted(((name, path) for path, name in found.items()), key=lambda item: item[0].casefold())
def capture_path(root: str | Path, prefix: str = "oasis_frame") -> Path: """Choose an ADAM-owned, collision-resistant PNG destination.""" from datetime import datetime from uuid import uuid4
folder = Path(root) / "data" / "oasis_captures" folder.mkdir(parents=True, exist_ok=True) return folder / f"{prefix}_{datetime.now().strftime('%Y%m%d_%H%M%S_%f')}_{uuid4().hex[:6]}.png"
def random_roblox_dataset_frame(oasis_root: str | Path, chooser=None) -> Path: """Pick one image from a deeply nested Roblox Dataset without assuming its layout.
Oasis recordings often live in several named recording folders, each with a ``frames`` folder. Reservoir sampling avoids holding every path in memory. ``chooser`` is injectable for deterministic tests. """ root = Path(oasis_root) / "OldDatasets" / "Roblox Dataset" if not root.is_dir(): raise FileNotFoundError("The connected Oasis Trainer has no OldDatasets/Roblox Dataset folder.") pick = None count = 0 chooser = chooser or random.randrange try: for path in root.rglob("*"): if not path.is_file() or path.suffix.casefold() not in IMAGE_EXTENSIONS: continue count += 1 if chooser(count) == 0: pick = path except OSError as exc: raise OSError(f"ADAM could not read the Roblox Dataset: {exc}") from exc if pick is None: raise FileNotFoundError("No PNG, JPG, WEBP, or BMP frames were found in the Roblox Dataset.") return pick123456788 unmodified lines1718192021222324252627282930313233343536373825 unmodified lines64656667686970713 unmodified lines757677787980818283848586878820 unmodified lines109110111112113114115116117118119120121122123124125126127from __future__ import annotationsimport jsonimport urllib.errorimport urllib.requestfrom typing import Any, Callable8 unmodified linesmodel: str,timeout: float = 2.5,chat_max_tokens: int | None = None,) -> None:self.base_url = base_url.rstrip("/")self.model = modelself.timeout = timeoutself.chat_max_tokens = chat_max_tokensdef _chat_system(self, system: str) -> str:"""Return the application system prompt unchanged."""return systemdef _num_predict(self, default: int, *, chat: bool = True) -> int:"""Qwen3's reasoning commonly needs more than a short-chat token budget."""if chat and self.chat_max_tokens is not None:return self.chat_max_tokensreturn 1024 if self.model.casefold().startswith("qwen3") else defaultdef is_available(self, timeout: float = 0.35) -> bool:request = urllib.request.Request(f"{self.base_url}/api/tags", method="GET")try:25 unmodified linesraise OllamaError("Ollama returned an unsupported plan shape.")return parseddef generate_text(self, system: str, prompt: str) -> str:response = self._generate(system, prompt, json_format=False).strip()if not response:raise OllamaError("Ollama returned an empty response.")return response3 unmodified linessystem: str,prompt: str,on_chunk: Callable[[str], None],) -> str:payload: dict[str, Any] = {"model": self.model,"system": self._chat_system(system),"prompt": prompt,"stream": True,"options": {"temperature": 0.35, "num_predict": self._num_predict(180)},}request = urllib.request.Request(f"{self.base_url}/api/generate",data=json.dumps(payload).encode("utf-8"),20 unmodified linesraise OllamaError("Ollama returned an empty response.")return resultdef _generate(self, system: str, prompt: str, *, json_format: bool) -> str:payload: dict[str, Any] = {"model": self.model,"system": self._chat_system(system),"prompt": prompt,"stream": False,"options": {"temperature": 0.1 if json_format else 0.35,"num_predict": self._num_predict(300 if json_format else 180, chat=not json_format),},}if json_format:payload["format"] = "json"body = json.dumps(payload).encode("utf-8")123456789108 unmodified lines192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737425 unmodified lines1001011021031041051061071081093 unmodified lines11311411511611711811912012112212312412512612712812913013113213320 unmodified lines154155156157158159160161162163164165166167168169170171172173174175176from __future__ import annotationsimport jsonimport base64import urllib.errorimport urllib.requestfrom pathlib import Pathfrom typing import Any, Callable8 unmodified linesmodel: str,timeout: float = 2.5,chat_max_tokens: int | None = None,chat_response_length: str = "automatic",) -> None:self.base_url = base_url.rstrip("/")self.model = modelself.timeout = timeoutself.chat_max_tokens = chat_max_tokensself.chat_response_length = str(chat_response_length or "automatic").casefold()def _chat_system(self, system: str) -> str:"""Return the application system prompt unchanged."""return systemdef _num_predict(self, default: int, *, chat: bool = True, prompt: str = "", image_count: int = 0) -> int:"""Qwen3's reasoning commonly needs more than a short-chat token budget."""if chat and self.chat_max_tokens is not None:limit = max(64, int(self.chat_max_tokens))choices = {"short": 256, "balanced": 512, "detailed": limit}selected = choices.get(self.chat_response_length)if selected is not None:return min(limit, selected)text = prompt.casefold()if image_count:budget = 384elif any(word in text for word in ("compare", "explain", "research", "plan", "review", "why", "how")):budget = 768elif any(word in text for word in ("summarize", "details", "ideas", "examples")):budget = 512else:budget = 256return min(limit, max(128, budget))return 1024 if self.model.casefold().startswith("qwen3") else default@staticmethoddef prepare_image(path: str | Path, *, maximum_side: int = 1536) -> str:"""Return a compact PNG attachment without changing the user's source image."""source = Path(path).expanduser()if not source.is_file():raise OllamaError("The attached image no longer exists.")try:from PIL import Image, ImageOpswith Image.open(source) as opened:image = ImageOps.exif_transpose(opened).convert("RGB")image.thumbnail((maximum_side, maximum_side), Image.Resampling.LANCZOS)from io import BytesIObuffer = BytesIO()image.save(buffer, format="PNG", optimize=True)except (OSError, ValueError) as exc:raise OllamaError(f"ADAM could not read {source.name} as an image.") from excreturn base64.b64encode(buffer.getvalue()).decode("ascii")def is_available(self, timeout: float = 0.35) -> bool:request = urllib.request.Request(f"{self.base_url}/api/tags", method="GET")try:25 unmodified linesraise OllamaError("Ollama returned an unsupported plan shape.")return parseddef generate_text(self, system: str, prompt: str, *, image_paths: list[str | Path] | None = None,) -> str:response = self._generate(system, prompt, json_format=False, image_paths=image_paths).strip()if not response:raise OllamaError("Ollama returned an empty response.")return response3 unmodified linessystem: str,prompt: str,on_chunk: Callable[[str], None],image_paths: list[str | Path] | None = None,) -> str:images = [self.prepare_image(path) for path in (image_paths or [])]payload: dict[str, Any] = {"model": self.model,"system": self._chat_system(system),"prompt": prompt,# Free GPU memory for image generation and other local workloads as# soon as this one-shot text request finishes."keep_alive": 0,"stream": True,"options": {"temperature": 0.35, "num_predict": self._num_predict(180, prompt=prompt, image_count=len(images))},}if images:payload["images"] = imagesrequest = urllib.request.Request(f"{self.base_url}/api/generate",data=json.dumps(payload).encode("utf-8"),20 unmodified linesraise OllamaError("Ollama returned an empty response.")return resultdef _generate(self, system: str, prompt: str, *, json_format: bool, image_paths: list[str | Path] | None = None) -> str:images = [self.prepare_image(path) for path in (image_paths or [])]payload: dict[str, Any] = {"model": self.model,"system": self._chat_system(system),"prompt": prompt,"keep_alive": 0,"stream": False,"options": {"temperature": 0.1 if json_format else 0.35,"num_predict": self._num_predict(300 if json_format else 180, chat=not json_format, prompt=prompt, image_count=len(images)),},}if json_format:payload["format"] = "json"if images:payload["images"] = imagesbody = json.dumps(payload).encode("utf-8")
137 unmodified lines138139140141142143137 unmodified linesfor step in training_steps:args = step.argumentsdataset_key = str(Path(str(args.get("dataset_dir", ""))).expanduser())images = dataset_image_count(args.get("dataset_dir")) or projected_counts.get(dataset_key, 0)epochs = max(1, int(args.get("epochs", 1) or 1))137 unmodified lines138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228137 unmodified linesfor step in training_steps:args = step.argumentsif step.tool_id == "wan_video_trainer":from adam.video_lora import clips_incount = len(clips_in(Path(str(args.get("dataset_dir", "")))))epochs = int(args.get("epochs", 1))findings.append({"level": "warning" if epochs > 100 or count < 20 else "ready", "message": (f"Wan video: {count} clips, {epochs} epochs, frame buckets {args.get('target_frames', '25,49')}. ""Each clip can contribute multiple frame buckets. Inspect motion and captions; video runtime requires a measured run.")})continueif step.tool_id == "oasis_trainer":from adam.oasis_dataset import inspect_oasis_dataset, oasis_pacegap = max(1, int(args.get("frame_gap", 1) or 1))pace = oasis_pace(args.get("dataset_dir", ""), frame_gap=gap)recommended_gap = pace["recommended_frame_gap"]capture_fps = pace["capture_fps"]native_fps = pace["native_ai_fps"]if isinstance(capture_fps, (int, float)) and isinstance(native_fps, (int, float)):message = (f"{step.title or 'Oasis'}: {float(capture_fps):g} FPS capture with "f"prediction gap {gap} trains at a native pace of {float(native_fps):g} AI FPS.")if isinstance(recommended_gap, int) and recommended_gap != gap:message += f" Dataset metadata recommends gap {recommended_gap} for responsive control."findings.append({"level": "warning", "message": message})else:findings.append({"level": "ready", "message": message})report = inspect_oasis_dataset(args.get("dataset_dir", ""), frame_gap=gap)if report.ok and report.valid_transitions:batch = max(1, int(args.get("batch_size", 1) or 1))accumulation = max(1, int(args.get("gradient_accumulation", 1) or 1))requested_chunk = max(0, int(args.get("chunk_size", 0) or 0))transitions_per_epoch = min(report.valid_transitions, requested_chunk) if requested_chunk else report.valid_transitionssteps_per_epoch = math.ceil(transitions_per_epoch / batch / accumulation)epochs = max(1, int(args.get("epochs", 1) or 1))optimizer_steps = steps_per_epoch * epochstotal_steps += optimizer_stepslabel = step.title or "Oasis"findings.append({"level": "ready","message": (f"{label}: {report.valid_transitions:,} valid transitions; "f"{transitions_per_epoch:,} used per epoch; about "f"{steps_per_epoch:,} optimizer steps per epoch."),})if report.valid_transitions >= 7_500 and not requested_chunk:findings.append({"level": "warning","message": (f"{label}: every epoch uses all {report.valid_transitions:,} transitions. ""Use a balanced 5,000-transition chunk or explicitly confirm the longer run."),})if optimizer_steps >= 100_000:findings.append({"level": "warning","message": (f"{label}: this plan schedules about {optimizer_steps:,} optimizer steps. ""Run the short benchmark and inspect rollout previews before committing."),})idle_ratio = report.idle_rows / max(1, report.valid_rows)if idle_ratio < 0.05:findings.append({"level": "warning","message": (f"{label}: only {idle_ratio:.1%} of labelled frames are idle. ""Record more no-input gameplay to improve stable pauses."),})rare_threshold = max(10, math.ceil(report.valid_rows * 0.01))rare_controls = [name for name, count in report.action_counts.items()if 0 < count < rare_threshold]if rare_controls and not bool(args.get("balance_actions", False)):findings.append({"level": "warning","message": ("Rare controls are present (" + ", ".join(rare_controls[:5])+ "); turn on Balance rare actions or record more examples."),})continuedataset_key = str(Path(str(args.get("dataset_dir", ""))).expanduser())images = dataset_image_count(args.get("dataset_dir")) or projected_counts.get(dataset_key, 0)epochs = max(1, int(args.get("epochs", 1) or 1))
6 unmodified lines78910111213141531 unmodified lines47484950515246 unmodified lines9910010110210310410510610710821 unmodified lines13013113213313413513627 unmodified lines1641651661671681694 unmodified lines17417517617717817919 unmodified lines19920020120220320420520620720824 unmodified lines233234235236237238239240241340 unmodified lines58258358458558658713 unmodified lines60160260360460560660711 unmodified lines6196206216226236246251 unmodified line6276286296306316326332 unmodified lines63663763863964064164267 unmodified lines7107117127137147157161 unmodified line71871972072172272372472572672751 unmodified lines7797807817827837847 unmodified lines79279379479579679729 unmodified lines827828829830831832833834835836837838839840128 unmodified lines96997097197297397497597697797897998098146 unmodified lines102810291030103110321033379 unmodified lines141314141415141614171418474 unmodified lines18931894189518961897189818996 unmodified linesfrom typing import Anyfrom collections.abc import Callablefrom adam.assets import Asset, AssetRegistryfrom adam.commands import CommandValidationError, TrainingCommandfrom adam.config import ConfigManagerfrom adam.models import ExecutionPlan, PlanStepfrom adam.ollama import OllamaClient, OllamaErrorfrom adam.registry import RegistryError, ToolRegistry31 unmodified linesreturn {"ddpm": "DDPM","flow": "Flow Matching","lora": "LoRA","oasis": "Oasis Action World Model",}.get(trainer, trainer.replace("_", " ").title())46 unmodified linesif not request:raise PlanningError("Tell ADAM what you want to accomplish.")if self.pending_request and self._looks_like_pending_details(request):return self._continue_pending_request(request)self.assets.discover(self.config)external = self._external_tool_plan(request)if external:self.last_mode = "Validated external tool"21 unmodified linesproject_name="Conversation",)if self.config.get("provider") == "ollama":try:generated = self._ollama_plan(request)self.last_mode = "Ollama + registry validation"27 unmodified linesrequest: str,history: list[dict[str, str]] | None = None,stream_callback: Callable[[str], None] | None = None,) -> str:"""Answer conversationally without creating or executing a workflow."""request = request.strip()4 unmodified linesself.config.get("ollama_model"),timeout=45.0,chat_max_tokens=int(self.config.get("ollama_chat_max_tokens", 1024)),)if self.config.get("provider") != "ollama":raise PlanningError(19 unmodified lines"about AI datasets, captions, LoRA, DDPM, Flow Matching, model training, previews, ""and the workflows registered in ADAM. This is Chat Mode: you cannot run tools, ""change files, start jobs, or claim that work occurred. If the user asks you to ""perform an action, explain that they should switch to Trainer Mode. Never invent ""job results or capabilities. Registered read-only capability summary:\n"+ json.dumps(capabilities, ensure_ascii=False))recent = (history or [])[-10:]transcript = "\n".join(f"{'User' if item.get('role') == 'user' else 'ADAM'}: "24 unmodified lines)try:response = (client.generate_text_stream(system, prompt, stream_callback)if stream_callbackelse client.generate_text(system, prompt))except OllamaError as exc:raise PlanningError(f"Ollama could not answer: {exc}") from exc340 unmodified lines) or ("lora" if re.search(r"\blora\b", lowered)else "ddpm" if re.search(r"\bddpm\b", lowered)else "flow" if re.search(r"\bflow(?:\s+matching)?\b", lowered)else "oasis" if re.search(r"\b(oasis|action[- ]conditioned|playable\s+ai\s+games?|world\s+models?|gameplay[- ]frame|wasd|w/a/s/d)\b",13 unmodified linesmodel_query = ""resume_match = re.search(r"\b(?:fine[- ]?tune|retrain|continue|resume)\s+(?:the\s+)?(.+?)"r"(?:\s+model)?\s+(?:from|on|with)\s+(?:the\s+)?(?:ddpm|lora|oasis)\b",request,re.I,)11 unmodified linesmodel_query = _clean_subject(match.group(1)) if match else ""natural_resume = re.search(r"\b(?:fine[- ]?tune|retrain|continue|resume)\s+(?:the\s+)?(.+?)\s+"r"from\s+(?:my|our|the)\s+(?:ddpm|lora)\s+model\b",request,re.I,)1 unmodified linemodel_query = _clean_subject(natural_resume.group(1))model_of_resume = re.search(r"\b(?:fine[- ]?tune|retrain|continue|resume)\s+(?:the\s+)?"r"(?:ddpm\s+|lora\s+)?model\s+of\s+(.+?)(?:\s+for\b|,|$)",request,re.I,)2 unmodified lines# Natural phrasing such as "fine-tune Hatsune Miku from our DDPM model"# should search for "Hatsune Miku", not the whole explanatory clause.model_query = re.sub(r"\s+from\s+(?:my|our|the)?\s*(?:ddpm|lora)\s+model\s*$","",model_query,flags=re.I,67 unmodified linessteps=[],project_name="Resume training",)resumed_model_name = _friendly_model_name(model)command = TrainingCommand.from_dict({"action": "resume_training",1 unmodified line"dataset": dataset.path,"model_name": resumed_model_name,"epochs": epochs,"output": (str(self._training_output(trainer, f"{resumed_model_name} Fine Tune") or model.path)if trainer == "flow" else model.path),# The DDPM adapter can safely branch from a complete pipeline when# its exact Accelerate checkpoint has been cleaned up."resume_from": model.checkpoint or model.path,51 unmodified linesraise PlanningError(str(exc)) from excreturn self._plan_training_command(request, command)@staticmethoddef _fine_tune_payload(request: str) -> dict[str, Any]:match = re.search(r"\[ADAM_FINE_TUNE:(\{.*\})\]\s*$", request, re.S)7 unmodified linesraise PlanningError("Fine-tune settings must be an object.")return payloaddef _dataset_for_model(self, model: Asset) -> Asset | None:if model.dataset_id:linked = next(29 unmodified linesif dataset_dir.exists():dataset_dir = dataset_dir.with_name(f"{dataset_dir.name} {datetime.now().strftime('%Y%m%d_%H%M%S')}")image_count = max(10, min(int(payload.get("image_count", 60)), 5000))model_name = _friendly_model_name(model)arguments: dict[str, Any] = {"dataset_dir": str(dataset_dir), "model_name": model_name,"epochs": epochs,"output_dir": (str(self._training_output(trainer, f"{model_name} Fine Tune") or model.path)if trainer == "flow" else model.path),"resume_from": model.checkpoint or model.path, **training_options,}if trainer == "lora":128 unmodified linesreturn existingif matches:return matchesreturn self.assets.find("model", raw_query, trainer=trainer)def _plan_training_command(self,request: str,command: TrainingCommand,) -> ExecutionPlan:tool_id = f"{command.trainer}_trainer"spec = self.registry.get(tool_id)capability = (46 unmodified lines) from excif command.resume_from and not Path(command.resume_from).exists():raise PlanningError("The validated resume checkpoint does not exist.")arguments: dict[str, Any] = {"dataset_dir": dataset_argument,"model_name": command.model_name,379 unmodified linesself.config.get("ollama_model"),timeout=30.0,chat_max_tokens=int(self.config.get("ollama_chat_max_tokens", 1024)),)if re.search(r"\bollama\b.*\b(working|online|reachable|running)\b", request, re.I):return (474 unmodified linescatalog = self.registry.safe_llm_catalog()system = ("You are ADAM's planning component. You only plan; you never execute. ""Return strict JSON with summary, project_name, requires_confirmation, ""confirmation_reason, and steps. Each step has tool_id, title, ""description, and arguments. Use only listed tool IDs and only their "6 unmodified lines78910111213141516171831 unmodified lines5051525354555646 unmodified lines10310410510610710810911011111211311411511611711811912021 unmodified lines14214314414514614714827 unmodified lines1761771781791801811824 unmodified lines18718818919019119219319 unmodified lines21321421521621721821922022122222322422522622722822924 unmodified lines254255256257258259260261262340 unmodified lines60360460560660760860913 unmodified lines62362462562662762862911 unmodified lines6416426436446456466471 unmodified line6496506516526536546552 unmodified lines65865966066166266366467 unmodified lines7327337347357367377387397407417427437447457467477487491 unmodified line75175275375475575675775875951 unmodified lines8118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509517 unmodified lines95996096196296396496596696796896997097197297397497597697797829 unmodified lines100810091010101110121013101410151016101710181019102010211022128 unmodified lines1151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119446 unmodified lines12411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263379 unmodified lines164316441645164616471648164916501651474 unmodified lines21262127212821292130213121326 unmodified linesfrom typing import Anyfrom collections.abc import Callablefrom adam.auto_training import profile_from_request, resolve_auto_trainingfrom adam.assets import Asset, AssetRegistryfrom adam.commands import CommandValidationError, TrainingCommandfrom adam.config import ConfigManagerfrom adam.dataset_lab import scan_datasetfrom adam.model_profiles import ModelProfileRegistryfrom adam.models import ExecutionPlan, PlanStepfrom adam.ollama import OllamaClient, OllamaErrorfrom adam.registry import RegistryError, ToolRegistry31 unmodified linesreturn {"ddpm": "DDPM","flow": "Flow Matching","inrflow": "INRFlow","lora": "LoRA","oasis": "Oasis Action World Model",}.get(trainer, trainer.replace("_", " ").title())46 unmodified linesif not request:raise PlanningError("Tell ADAM what you want to accomplish.")if re.search(r"\b(?:wan(?:\s*2[.]1)?|video\s+lora|lora\s+video)\b", request, re.I):self.last_mode = "Video LoRA workspace"return ExecutionPlan(request=request, summary="Open Video LoRA in the sidebar to select captioned clips, review a Wan training pipeline, continue weights, or generate an MP4. Wan settings and checkpoints are separate from SDXL LoRA.", steps=[], project_name="Video LoRA")if self.pending_request and self._looks_like_pending_details(request):return self._continue_pending_request(request)self.assets.discover(self.config)auto_training = self._auto_training_plan(request)if auto_training:self.last_mode = "Intent-based AUTO training"return auto_trainingexternal = self._external_tool_plan(request)if external:self.last_mode = "Validated external tool"21 unmodified linesproject_name="Conversation",)if self.config.get("provider") == "ollama" and self.config.get("ollama_proposed_actions", True):try:generated = self._ollama_plan(request)self.last_mode = "Ollama + registry validation"27 unmodified linesrequest: str,history: list[dict[str, str]] | None = None,stream_callback: Callable[[str], None] | None = None,image_paths: list[str | Path] | None = None,) -> str:"""Answer conversationally without creating or executing a workflow."""request = request.strip()4 unmodified linesself.config.get("ollama_model"),timeout=45.0,chat_max_tokens=int(self.config.get("ollama_chat_max_tokens", 1024)),chat_response_length=str(self.config.get("ollama_chat_response_length", "automatic")),)if self.config.get("provider") != "ollama":raise PlanningError(19 unmodified lines"about AI datasets, captions, LoRA, DDPM, Flow Matching, model training, previews, ""and the workflows registered in ADAM. This is Chat Mode: you cannot run tools, ""change files, start jobs, or claim that work occurred. If the user asks you to ""perform an action, explain that ADAM must create a validated plan before anything ""can happen. Never invent job results, capability status, or a running/completed job. ""Registered read-only capability summary:\n"+ json.dumps(capabilities, ensure_ascii=False))if image_paths:system += (" The user attached image(s). Describe only visible evidence, distinguish ""uncertainty from facts, and offer an editable caption when useful. Do not ""claim the image was added to a dataset or used for training.")recent = (history or [])[-10:]transcript = "\n".join(f"{'User' if item.get('role') == 'user' else 'ADAM'}: "24 unmodified lines)try:response = (client.generate_text_stream(system, prompt, stream_callback, image_paths=image_paths)if stream_callbackelse client.generate_text(system, prompt, image_paths=image_paths))except OllamaError as exc:raise PlanningError(f"Ollama could not answer: {exc}") from exc340 unmodified lines) or ("lora" if re.search(r"\blora\b", lowered)else "ddpm" if re.search(r"\bddpm\b", lowered)else "inrflow" if re.search(r"\binr\s*flow\b", lowered)else "flow" if re.search(r"\bflow(?:\s+matching)?\b", lowered)else "oasis" if re.search(r"\b(oasis|action[- ]conditioned|playable\s+ai\s+games?|world\s+models?|gameplay[- ]frame|wasd|w/a/s/d)\b",13 unmodified linesmodel_query = ""resume_match = re.search(r"\b(?:fine[- ]?tune|retrain|continue|resume)\s+(?:the\s+)?(.+?)"r"(?:\s+model)?\s+(?:from|on|with)\s+(?:the\s+)?(?:ddpm|lora|oasis|inr\s*flow|flow)\b",request,re.I,)11 unmodified linesmodel_query = _clean_subject(match.group(1)) if match else ""natural_resume = re.search(r"\b(?:fine[- ]?tune|retrain|continue|resume)\s+(?:the\s+)?(.+?)\s+"r"from\s+(?:my|our|the)\s+(?:ddpm|lora|inr\s*flow|flow)\s+model\b",request,re.I,)1 unmodified linemodel_query = _clean_subject(natural_resume.group(1))model_of_resume = re.search(r"\b(?:fine[- ]?tune|retrain|continue|resume)\s+(?:the\s+)?"r"(?:(?:ddpm|lora|inr\s*flow|flow)\s+)?model\s+of\s+(.+?)(?:\s+for\b|,|$)",request,re.I,)2 unmodified lines# Natural phrasing such as "fine-tune Hatsune Miku from our DDPM model"# should search for "Hatsune Miku", not the whole explanatory clause.model_query = re.sub(r"\s+from\s+(?:my|our|the)?\s*(?:ddpm|lora|inr\s*flow|flow)\s+model\s*$","",model_query,flags=re.I,67 unmodified linessteps=[],project_name="Resume training",)requested_output_name = self._fine_tune_output_name(request, fine_tune_payload)resumed_model_name = _clean_subject(requested_output_name) if requested_output_name else _friendly_model_name(model)continuation_output = self._training_output(trainer, f"{resumed_model_name} Fine Tune")if not continuation_output:return ExecutionPlan(request=request,summary=f"The {_trainer_label(trainer)} trainer folder is not connected.",steps=[],project_name="Resume training",)command = TrainingCommand.from_dict({"action": "resume_training",1 unmodified line"dataset": dataset.path,"model_name": resumed_model_name,"epochs": epochs,# A continuation is always a new model branch. Never send a# resumed run back to the selected source model's folder."output": str(continuation_output),# The DDPM adapter can safely branch from a complete pipeline when# its exact Accelerate checkpoint has been cleaned up."resume_from": model.checkpoint or model.path,51 unmodified linesraise PlanningError(str(exc)) from excreturn self._plan_training_command(request, command)def _auto_training_plan(self, request: str) -> ExecutionPlan | None:"""Plan a short, clear training request through a named AUTO policy.This is intentionally narrow: a trainer and a subject must both beexplicit. Ambiguous requests continue through the existing planner,which can ask a focused follow-up instead of guessing an architecture."""lowered = request.casefold()if not re.search(r"\b(train|make|create|build|test)\b", lowered):return None# Fully specified legacy requests retain their established planner path.# AUTO is for omitted decisions, not a replacement for explicit control.if re.search(r"\b\d{1,5}\s*epochs?\b", request, re.I):return Nonematch = re.search(r"^\s*(?:(?:can|could|will|would)\s+you\s+(?:please\s+)?)?(?:quickly\s+)?"r"(?:train|make|create|build|test)\s+(?:me\s+)?(?:a|an|the)?\s*"r"(?:(?:quick|high\s+quality|best\s+quality|really\s+good|quality)\s+)?"r"(ddpm|lora|inr\s*flow|flow(?:\s+matching)?)(?:\s+model)?\s+"r"(?:on|of|for|using|with)\s+(?:an?\s+)?(?:dataset\s+(?:of|for)\s+)?(.+?)\s*$",request,re.I,)if not match:return Nonetrainer_token, raw_subject = match.groups()trainer = ("inrflow" if trainer_token.casefold().replace(" ", "") == "inrflow"else "flow" if trainer_token.casefold().startswith("flow")else trainer_token.casefold())# Remove only trailing presentation words/settings; the subject itself# remains ordinary natural language and never becomes a hidden command.subject = re.sub(r"\s+(?:images?|pictures?|screenshots?)(?:\s+(?:for|with|overnight|quickly)\b.*)?$|"r"\s+for\s+\d{1,5}\s+epochs?\b.*$","",raw_subject,flags=re.I,)subject = _clean_subject(subject)if subject == "new subject":return Noneprofile = ModelProfileRegistry(self.registry.model_plugins).get(trainer)if profile is None:return Nonepolicy = profile_from_request(request)options = self._training_options_from_request(request)epoch_match = re.search(r"\b(\d{1,5})\s*epochs?\b", request, re.I)count_match = re.search(r"\b(\d{1,6})\s+(?:images?|pictures?)\b", request, re.I)existing_dataset = self._asset_dataset(subject)expected_items = (scan_dataset(existing_dataset.path, limit=1).image_countif existing_dataset else 0)auto = resolve_auto_training(profile,trainer=trainer,policy=policy,dataset_items=expected_items or (int(count_match.group(1)) if count_match else 400),)epochs = int(epoch_match.group(1)) if epoch_match else auto.epochsimage_count = int(count_match.group(1)) if count_match else auto.dataset_target# Explicit structured/manual settings override AUTO; AUTO supplies every# remaining supported setting, making the final plan reproducible.training_options = {**auto.settings, **options}model_name = self._model_name_from_request(request) or subjectif existing_dataset:output = self._training_output(trainer, model_name)if not output:return Nonetry:command = TrainingCommand.from_dict({"action": "train", "trainer": trainer, "dataset": existing_dataset.path,"model_name": model_name, "epochs": epochs, "output": str(output),"base_model": (str(training_options.get("base_model") or self._lora_base_model())if trainer == "lora" else ""),"training_options": training_options,})except CommandValidationError as exc:raise PlanningError(str(exc)) from excplan = self._plan_training_command(request, command)plan.summary += f" {auto.summary}"return plancollector_root = self._configured_tool_folder("dataset_collector")output = self._training_output(trainer, model_name)if not collector_root or not output:return Noneproject = _project_name(subject, "Dataset")dataset_dir = (Path(collector_root) / "Datasets" / project).resolve()if dataset_dir.exists():dataset_dir = dataset_dir.with_name(f"{dataset_dir.name} {datetime.now().strftime('%Y%m%d_%H%M%S')}")arguments: dict[str, Any] = {"dataset_dir": str(dataset_dir), "model_name": model_name,"epochs": epochs, "output_dir": str(output), **training_options,}if trainer == "lora":base_model = str(training_options.get("base_model") or self._lora_base_model())if not base_model or not Path(base_model).is_file():return ExecutionPlan(request=request,summary="Choose a valid SDXL base model in the LoRA settings before AUTO training.",steps=[], project_name="LoRA training",)arguments["base_model"] = base_modelarguments["trigger_word"] = str(training_options.get("trigger_word") or model_name)return ExecutionPlan(request=request,summary=(f"AUTO plan: collect up to {image_count:,} images for {subject}, then train "f"{model_name} with {_trainer_label(trainer)} for {epochs:,} epochs. {auto.summary}"),steps=[PlanStep("dataset_collector", "Collect dataset", "Collect a reviewable dataset for the requested subject.", {"subject": subject, "image_count": max(10, min(image_count, 100_000)),"collection_mode": _collection_mode(request), "project_name": project,"output_dir": str(dataset_dir),}),PlanStep(f"{trainer}_trainer", f"Train {_trainer_label(trainer)} model", "Train using resolved AUTO settings.", arguments),],requires_confirmation=True,confirmation_reason=("This plan downloads a dataset and starts real GPU training. ""The resolved AUTO settings are included in the training step."),project_name=model_name[:64],)@staticmethoddef _fine_tune_payload(request: str) -> dict[str, Any]:match = re.search(r"\[ADAM_FINE_TUNE:(\{.*\})\]\s*$", request, re.S)7 unmodified linesraise PlanningError("Fine-tune settings must be an object.")return payload@staticmethoddef _fine_tune_output_name(request: str, payload: dict[str, Any]) -> str:"""Return an explicit result name without confusing it with the source model."""requested = str(payload.get("output_model_name", "")).strip()if requested:return requestedmatch = re.search(r"\b(?:name|call)\s+(?:the\s+)?(?:fine[- ]?tuned\s+)?"r"(?:model\s+)?(?:as|to)\s+[\"\u201c]?([^\"\u201d.,]+)",request,re.I,)return _clean_subject(match.group(1)) if match else ""def _dataset_for_model(self, model: Asset) -> Asset | None:if model.dataset_id:linked = next(29 unmodified linesif dataset_dir.exists():dataset_dir = dataset_dir.with_name(f"{dataset_dir.name} {datetime.now().strftime('%Y%m%d_%H%M%S')}")image_count = max(10, min(int(payload.get("image_count", 60)), 5000))requested_output_name = self._fine_tune_output_name(request, payload)model_name = _clean_subject(requested_output_name) if requested_output_name else _friendly_model_name(model)continuation_output = self._training_output(trainer, f"{model_name} Fine Tune")if not continuation_output:return ExecutionPlan(request=request, summary=f"The {_trainer_label(trainer)} trainer folder is not connected.", steps=[], project_name="Resume training")arguments: dict[str, Any] = {"dataset_dir": str(dataset_dir), "model_name": model_name,"epochs": epochs,"output_dir": str(continuation_output),"resume_from": model.checkpoint or model.path, **training_options,}if trainer == "lora":128 unmodified linesreturn existingif matches:return matchesmatches = self.assets.find("model", raw_query, trainer=trainer)# Asset discovery and an in-memory registration can legitimately refer# to the same saved model. One physical path is one continuation# candidate, not an ambiguity the user has to resolve.unique: list[Asset] = []seen_paths: set[str] = set()# Prefer a model folder over a checkpoint file inside that same folder.# Discovery can register both representations of one saved run.ordered = sorted(matches, key=lambda item: (not Path(item.path).is_dir(), len(str(item.path))))for asset in ordered:try:resolved = Path(asset.path).expanduser().resolve()key = str(resolved).casefold()except OSError:resolved = Path(asset.path)key = str(asset.path).casefold()nested_in_known_model = any(key.startswith(parent + "\\") or key.startswith(parent + "/")for parent in seen_paths)if key not in seen_paths and not nested_in_known_model:seen_paths.add(key)unique.append(asset)return uniquedef _plan_training_command(self,request: str,command: TrainingCommand,) -> ExecutionPlan:if command.trainer == "wan_video":from adam.video_lora import training_plantry:return training_plan(self.root, command.dataset, command.model_name, command.epochs,command.training_options or {}, command.resume_from,"" if command.output == "default output" else command.output)except ValueError as exc:raise PlanningError(str(exc)) from exctool_id = f"{command.trainer}_trainer"spec = self.registry.get(tool_id)capability = (46 unmodified lines) from excif command.resume_from and not Path(command.resume_from).exists():raise PlanningError("The validated resume checkpoint does not exist.")if command.resume_from:resume_path = Path(command.resume_from).expanduser().resolve()# A checkpoint may live below its model folder, so protect both# ancestors and descendants rather than checking simple equality.try:output_path.relative_to(resume_path)overlaps_resume = Trueexcept ValueError:try:resume_path.relative_to(output_path)overlaps_resume = Trueexcept ValueError:overlaps_resume = Falseif overlaps_resume:raise PlanningError("Continuation output must be a new folder, separate from the source model.")arguments: dict[str, Any] = {"dataset_dir": dataset_argument,"model_name": command.model_name,379 unmodified linesself.config.get("ollama_model"),timeout=30.0,chat_max_tokens=int(self.config.get("ollama_chat_max_tokens", 1024)),chat_response_length=str(self.config.get("ollama_chat_response_length", "automatic")),)if re.search(r"\bollama\b.*\b(working|online|reachable|running)\b", request, re.I):return (474 unmodified linescatalog = self.registry.safe_llm_catalog()system = ("You are ADAM's proposed-action component. You only propose plans; you never execute. ""Return strict JSON with summary, project_name, requires_confirmation, ""confirmation_reason, and steps. Each step has tool_id, title, ""description, and arguments. Use only listed tool IDs and only their "
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103"""Resolution-curriculum helpers shared by the DDPM and Flow adapters.
The adapters deliberately use conservative batch caps instead of trying anout-of-memory probe in a real training job. A user can still turn the policyoff and enter every batch setting manually."""
from __future__ import annotations
from dataclasses import dataclassfrom typing import Any
from adam.executor import ToolExecutionError
@dataclass(frozen=True, slots=True)class ResolutionStage: resolution: int epochs: int
_BATCH_CAPS = { "ddpm": {64: 16, 128: 12, 256: 4, 384: 2, 512: 1}, "flow": {64: 12, 128: 8, 256: 4, 384: 2, 512: 1},}
def parse_stages(value: Any, *, trainer: str, total_epochs: int) -> list[ResolutionStage]: """Validate a JSON-friendly progressive-resolution schedule.
Stages are intentionally a list of small dictionaries so plans remain easy to inspect and edit in saved job JSON. """ if not isinstance(value, list) or len(value) < 2: raise ToolExecutionError("Progressive training needs at least two resolution stages.") multiple = 16 if trainer == "flow" else 8 stages: list[ResolutionStage] = [] previous = 0 for raw in value: if not isinstance(raw, dict): raise ToolExecutionError("Each progressive stage must include resolution and epochs.") try: resolution = int(raw.get("resolution", 0)) epochs = int(raw.get("epochs", 0)) except (TypeError, ValueError) as exc: raise ToolExecutionError("Progressive stage resolution and epochs must be whole numbers.") from exc if not 64 <= resolution <= 512 or resolution % multiple: raise ToolExecutionError( f"{trainer.upper()} progressive resolutions must be 64–512 and divisible by {multiple}." ) if resolution <= previous: raise ToolExecutionError("Progressive stages must increase from lower to higher resolution.") if epochs < 1: raise ToolExecutionError("Each progressive stage needs at least one epoch.") stages.append(ResolutionStage(resolution, epochs)) previous = resolution if sum(stage.epochs for stage in stages) != int(total_epochs): raise ToolExecutionError( f"Progressive stage epochs total {sum(stage.epochs for stage in stages):,}, " f"but training length is {int(total_epochs):,}." ) return stages
def suggested_stages(final_resolution: int, total_epochs: int) -> list[ResolutionStage]: """Return an editable low-to-high schedule that always matches the budget.""" resolutions = [size for size in (64, 128, 256, 384, 512) if size <= int(final_resolution)] if len(resolutions) < 2: return [ResolutionStage(int(final_resolution), int(total_epochs))] if int(total_epochs) < len(resolutions): resolutions = resolutions[-int(total_epochs):] return [ResolutionStage(resolution, 1) for resolution in resolutions] # Front-load inexpensive structure learning while reserving final-resolution # refinement. Normalizing lets the same policy work for any epoch budget. weights = [0.60, 0.20, 0.10, 0.06, 0.04][-len(resolutions):] allocation = [max(1, round(total_epochs * weight / sum(weights))) for weight in weights] difference = int(total_epochs) - sum(allocation) allocation[0] += difference return [ResolutionStage(resolution, epochs) for resolution, epochs in zip(resolutions, allocation)]
def stage_batch_settings( *, trainer: str, stage_resolution: int, final_resolution: int, final_batch_size: int, base_accumulation: int, auto_batch: bool,) -> tuple[int, int]: """Choose a conservative physical batch and matching accumulation count.""" requested_batch = max(1, min(64, int(final_batch_size))) requested_accumulation = max(1, min(64, int(base_accumulation))) if not auto_batch: return requested_batch, requested_accumulation caps = _BATCH_CAPS[trainer] cap = caps[min(caps, key=lambda size: abs(size - int(stage_resolution)))] # Scale from the user's final-stage batch according to image area, then # enforce a trainer-specific safe cap. This never raises the 512px batch. scaled = round(requested_batch * (int(final_resolution) / int(stage_resolution)) ** 2) batch_size = max(1, min(cap, 64, scaled)) effective_batch = requested_batch * requested_accumulation accumulation = max(1, min(64, -(-effective_batch // batch_size))) return batch_size, accumulation
def stage_summary(stages: list[ResolutionStage]) -> str: return ", ".join(f"{stage.resolution}px × {stage.epochs}" for stage in stages)73 unmodified lines7475767778795 unmodified lines8586878889901 unmodified line92939495969798991001011021036 unmodified lines11011111211311411520 unmodified lines1361371381391401411422 unmodified lines14514614714814915015115215315415515615715815916016116216316416516611 unmodified lines17817918018118218318418518618718873 unmodified linesprofile: ModelProfile,*,dataset_items: int,resolution: int | str | None = None,snapshot: SystemSnapshot | None = None,base_model_gb: float = 0.0,5 unmodified lineselse:resolution = int(raw_resolution)reasons: list[str] = []vram_total = snapshot.vram_total_gb if snapshot and snapshot.vram_total_gb else Noneavailable_vram = (max(0.0, snapshot.vram_total_gb - snapshot.vram_used_gb)1 unmodified lineelse vram_total)architecture = profile.architecture.casefold()target_exposures = 80_000 if profile.id == "lora" else 180_000 if "diffusion" in architecture else 120_000max_epochs = 220 if profile.id == "lora" else 600 if "diffusion" in architecture else 300epochs = max(10 if profile.id == "lora" else 25, min(max_epochs, round(target_exposures / images)))reasons.append(f"Epochs target roughly {target_exposures:,} image exposures, then clamp to the profile's safe range.")batch_defaults = {64: 16,6 unmodified lines}if profile.id == "flow":batch_defaults.update({64: 12, 128: 8, 256: 4})if profile.id == "oasis":batch_defaults.update({128: 4, 256: 2, 384: 1, 512: 1})if profile.id == "lora":20 unmodified linessettings["learning_rate"] = _clamp_to_schema(profile,"learning_rate",0.00002 if profile.id == "oasis" else 0.0001 if profile.id in {"ddpm", "lora"} else 0.0002,)workers = max(1, min(8, (os.cpu_count() or 4) // 2))for key in ("dataloader_num_workers", "workers"):2 unmodified linesfor key, value in {"gradient_accumulation_steps": 1,"gradient_accumulation": 1,"mixed_precision": "fp32" if profile.id == "oasis" else "fp16","save_every": max(5, min(25, max(1, epochs // 10))),"preview_every": max(5, min(50, max(1, epochs // 10))),"training_intensity": 100,"gradient_checkpointing": resolution >= 384 or (available_vram is not None and available_vram < 8),"rank": 16,"alpha": 16,"frame_gap": 3,"sequence_context": 1,"preview_steps": 1 if profile.id == "oasis" else 50 if profile.id == "ddpm" else 10,}.items():if key in profile.training:settings[key] = _clamp_to_schema(profile, key, value)estimated = estimate_vram_gb(profile, resolution, int(settings.get("batch_size", batch_size)), base_model_gb)warnings: list[str] = []if available_vram is not None and estimated > available_vram * 0.9:warnings.append(f"Estimated VRAM need is about {estimated:.1f} GB, above the conservative {available_vram * 0.9:.1f} GB working limit."11 unmodified linesmemory_note = (f" using about {available_vram:.1f} GB available VRAM" if available_vram is not None else " without detected VRAM")summary = (f"Recommended {epochs:,} epochs for {images:,} item(s), "f"batch {settings.get('batch_size', batch_size)} at {resolution}px{memory_note}. ""Treat this as a starting recipe, not a guarantee.")return SettingsRecommendation(profile_id=profile.id,epochs=epochs,73 unmodified lines747576777879805 unmodified lines868788899091921 unmodified line9495969798991001011021031041051061071081091101116 unmodified lines11811912012112212312412520 unmodified lines1461471481491501511522 unmodified lines15515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625711 unmodified lines26927027127227327427527627727827928028128228328428528673 unmodified linesprofile: ModelProfile,*,dataset_items: int,dataset_path: str = "",resolution: int | str | None = None,snapshot: SystemSnapshot | None = None,base_model_gb: float = 0.0,5 unmodified lineselse:resolution = int(raw_resolution)reasons: list[str] = []warnings: list[str] = []vram_total = snapshot.vram_total_gb if snapshot and snapshot.vram_total_gb else Noneavailable_vram = (max(0.0, snapshot.vram_total_gb - snapshot.vram_used_gb)1 unmodified lineelse vram_total)architecture = profile.architecture.casefold()if profile.id == "oasis":# Oasis learns labelled transitions rather than independent images. A real# dataset inspection below replaces this fallback whenever one is selected.epochs = 20reasons.append("Oasis starts from a transition-step budget, not an image-exposure target.")else:target_exposures = 80_000 if profile.id == "lora" else 180_000 if "diffusion" in architecture else 120_000max_epochs = 220 if profile.id == "lora" else 600 if "diffusion" in architecture else 300epochs = max(10 if profile.id == "lora" else 25, min(max_epochs, round(target_exposures / images)))reasons.append(f"Epochs target roughly {target_exposures:,} image exposures, then clamp to the profile's safe range.")batch_defaults = {64: 16,6 unmodified lines}if profile.id == "flow":batch_defaults.update({64: 12, 128: 8, 256: 4})if profile.id == "inrflow":batch_defaults.update({64: 4, 128: 2, 256: 1})if profile.id == "oasis":batch_defaults.update({128: 4, 256: 2, 384: 1, 512: 1})if profile.id == "lora":20 unmodified linessettings["learning_rate"] = _clamp_to_schema(profile,"learning_rate",0.00002 if profile.id == "oasis" else 0.0001 if profile.id in {"ddpm", "lora", "inrflow"} else 0.0002,)workers = max(1, min(8, (os.cpu_count() or 4) // 2))for key in ("dataloader_num_workers", "workers"):2 unmodified linesfor key, value in {"gradient_accumulation_steps": 1,"gradient_accumulation": 1,"mixed_precision": "fp16","save_every": max(5, min(25, max(1, epochs // 10))),"preview_every": max(5, min(50, max(1, epochs // 10))),"training_intensity": 100,"gradient_checkpointing": resolution >= 384 or (available_vram is not None and available_vram < 8),"rank": 16,"alpha": 16,"frame_gap": 1,"sequence_context": 1,"preview_steps": 1 if profile.id == "oasis" else 50 if profile.id == "ddpm" else 10,}.items():if key in profile.training:settings[key] = _clamp_to_schema(profile, key, value)if profile.id == "inrflow" and "query_points" in profile.training:settings["query_points"] = _clamp_to_schema(profile, "query_points", min(1024, resolution * resolution))reasons.append("INRFlow starts with at most 1,024 decoded pixel queries per image to keep training memory practical.")if profile.id == "oasis" and dataset_path:from adam.oasis_dataset import dataset_directories, inspect_oasis_dataset, oasis_pacepace = oasis_pace(dataset_path, frame_gap=int(settings.get("frame_gap", 1)))recommended_gap = pace["recommended_frame_gap"]capture_fps = pace["capture_fps"]if isinstance(recommended_gap, int) and isinstance(capture_fps, (int, float)):settings["frame_gap"] = _clamp_to_schema(profile, "frame_gap", recommended_gap)native_fps = float(capture_fps) / int(settings["frame_gap"])reasons.append(f"The dataset records at {float(capture_fps):g} FPS, so prediction gap "f"{settings['frame_gap']} gives a native trained pace of {native_fps:g} AI FPS.")report = inspect_oasis_dataset(dataset_path, frame_gap=int(settings.get("frame_gap", 1)))if report.ok and report.valid_transitions:transition_count = report.valid_transitions# Large datasets need bounded epochs and a rotating, balanced sample.# This keeps the recommendation in tens of thousands of updates rather# than silently turning 10K captured frames into a multi-day run.chunk_size = 5_000 if transition_count >= 7_500 else 0transitions_per_epoch = min(transition_count, chunk_size) if chunk_size else transition_countoptimizer_steps_per_epoch = math.ceil(transitions_per_epoch/ max(1, int(settings.get("batch_size", batch_size)))/ max(1, int(settings.get("gradient_accumulation", 1))))target_updates = 50_000 if transition_count >= 7_500 else 30_000epochs = max(5, min(45, math.ceil(target_updates / max(1, optimizer_steps_per_epoch))))for key, value in {"chunk_size": chunk_size,"chunk_mode": "balanced","chunk_offset": 0,"balance_actions": True,"tf32": True,"contrast_every": 4,"contrast_samples": 2,"recovery_minutes": 30,"save_every": max(5, min(10, max(1, epochs // 4))),"preview_every": max(2, min(10, max(1, epochs // 5))),}.items():if key in profile.training:settings[key] = _clamp_to_schema(profile, key, value)if len(dataset_directories(dataset_path)) > 1:for key, value in {"include_older_data": True, "replay_older_percent": 50.0}.items():if key in profile.training:settings[key] = _clamp_to_schema(profile, key, value)reasons.append(f"{transition_count:,} valid transitions use "f"{transitions_per_epoch:,} transition(s) per epoch, about "f"{optimizer_steps_per_epoch:,} optimizer steps per epoch, and a "f"{target_updates:,}-step initial budget.")if chunk_size:reasons.append("A balanced 5,000-transition chunk keeps rare controls represented; ""increase the chunk offset on a later continuation to rotate the sample.")idle_ratio = report.idle_rows / max(1, report.valid_rows)if idle_ratio < 0.05:warnings.append(f"Only {idle_ratio:.1%} of labelled frames are idle. Record more no-input gameplay ""so the world can stay stable when the player releases controls.")rare_threshold = max(10, math.ceil(report.valid_rows * 0.01))rare_controls = [name for name, count in report.action_counts.items()if 0 < count < rare_threshold]if rare_controls:warnings.append("Rare recorded controls: " + ", ".join(rare_controls[:5])+ ". Action balancing is enabled, but more examples are still safer.")estimated = estimate_vram_gb(profile, resolution, int(settings.get("batch_size", batch_size)), base_model_gb)if available_vram is not None and estimated > available_vram * 0.9:warnings.append(f"Estimated VRAM need is about {estimated:.1f} GB, above the conservative {available_vram * 0.9:.1f} GB working limit."11 unmodified linesmemory_note = (f" using about {available_vram:.1f} GB available VRAM" if available_vram is not None else " without detected VRAM")if profile.id == "oasis":summary = (f"Recommended {epochs:,} Oasis epochs, batch {settings.get('batch_size', batch_size)}, "f"prediction gap {settings.get('frame_gap', 1)}{memory_note}. ""The recipe uses labelled transitions and is a starting point, not a guarantee.")else:summary = (f"Recommended {epochs:,} epochs for {images:,} item(s), "f"batch {settings.get('batch_size', batch_size)} at {resolution}px{memory_note}. ""Treat this as a starting recipe, not a guarantee.")return SettingsRecommendation(profile_id=profile.id,epochs=epochs,
23 unmodified lines2425262728292383 unmodified lines24132414241524162417241824192420242121 unmodified lines244324442445244624472448244984 unmodified lines2534253525362537253825392540254126 unmodified lines25682569257025712572257323 unmodified linesload_generation_history,parse_chat_generation_request,)from adam.remote_dispatcher import RemoteCommandDispatcherfrom adam.remote_media import OpaqueIdCodec, RemoteMediaStorefrom adam.remote_v1 import RemoteV1Service2383 unmodified linespreferred_id = {"ddpm": "ddpm_generator","flow": "flow_generator","lora": "lora_generator",}.get(parsed.provider_hint, "")if stable_diffusion_request and parsed.provider_hint not in {"ddpm", "flow"}:preferred_id = "lora_generator"preferred_tool = next((item for item in tools if item.id == preferred_id), None)if parsed.provider_hint and preferred_tool is None:21 unmodified lineskey=lambda item: item[0],reverse=True,)model = scored[0][1] if scored and scored[0][0] > 0 else Noneif model is None and not model_query and len(candidates) == 1:model = candidates[0]if model is None and plain_model_search:84 unmodified linesextra_arguments = {"negative_prompt": parsed.negative_prompt or str(saved_generation.get("negative_prompt", "")),"base_model_path": base_model_path,"width": 0,"height": 0,"cfg_scale": parsed.cfg_scale if parsed.cfg_scale is not None else float(saved_generation.get("cfg_scale", 0) or 0),"lora_strength": 0.0 if base_only else (parsed.lora_strength if parsed.lora_strength is not None else float(saved_generation.get("lora_strength", 0) or 0)26 unmodified linesfor asset in getattr(self.planner.assets, "assets", [])if asset.kind == "base_model" and Path(asset.path).exists()]if parsed.base_model_query:scored_bases = sorted((23 unmodified lines242526272829302383 unmodified lines2414241524162417241824192420242124222423242421 unmodified lines2446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246884 unmodified lines2553255425552556255725582559256026 unmodified lines2587258825892590259125922593259423 unmodified linesload_generation_history,parse_chat_generation_request,)from adam.assets import Assetfrom adam.remote_dispatcher import RemoteCommandDispatcherfrom adam.remote_media import OpaqueIdCodec, RemoteMediaStorefrom adam.remote_v1 import RemoteV1Service2383 unmodified linespreferred_id = {"ddpm": "ddpm_generator","flow": "flow_generator","inrflow": "inrflow_generator","pixelrow": "pixelrow_generator","lora": "lora_generator",}.get(parsed.provider_hint, "")if stable_diffusion_request and parsed.provider_hint not in {"ddpm", "flow", "inrflow", "pixelrow"}:preferred_id = "lora_generator"preferred_tool = next((item for item in tools if item.id == preferred_id), None)if parsed.provider_hint and preferred_tool is None:21 unmodified lineskey=lambda item: item[0],reverse=True,)model = next((asset for asset in candidatesif parsed.metadata_model_pathand Path(asset.path).resolve() == Path(parsed.metadata_model_path).expanduser().resolve()),None,)if model is None and parsed.metadata_model_path:direct_path = Path(parsed.metadata_model_path).expanduser()if direct_path.is_file() and direct_path.suffix.casefold() == ".safetensors":model = Asset(id="pasted-metadata", kind="model", name=direct_path.stem,path=str(direct_path.resolve()), trainer="lora",)if model is None:model = scored[0][1] if scored and scored[0][0] > 0 else Noneif model is None and not model_query and len(candidates) == 1:model = candidates[0]if model is None and plain_model_search:84 unmodified linesextra_arguments = {"negative_prompt": parsed.negative_prompt or str(saved_generation.get("negative_prompt", "")),"base_model_path": base_model_path,"width": parsed.width or 0,"height": parsed.height or 0,"cfg_scale": parsed.cfg_scale if parsed.cfg_scale is not None else float(saved_generation.get("cfg_scale", 0) or 0),"lora_strength": 0.0 if base_only else (parsed.lora_strength if parsed.lora_strength is not None else float(saved_generation.get("lora_strength", 0) or 0)26 unmodified linesfor asset in getattr(self.planner.assets, "assets", [])if asset.kind == "base_model" and Path(asset.path).exists()]if parsed.metadata_base_model_path and Path(parsed.metadata_base_model_path).expanduser().is_file():return str(Path(parsed.metadata_base_model_path).expanduser().resolve())if parsed.base_model_query:scored_bases = sorted((
21 unmodified lines2223242526272833 unmodified lines6263646566676869707172737475767715 unmodified lines939495969798991001011021031041051061071081091106 unmodified lines11711811912012112212312412512612712812913013113213313413513613721 unmodified lines<div class="grid wide"><article class="card"><div class="section">Active Job</div><div id="activeJob">Checking ADAM...</div><div class="progress"><div id="activeBar" class="bar"></div></div><div class="row" style="margin-top:10px"><span class="pill">Time Left <b id="timeLeft">-</b></span><span class="pill">Finish <b id="finishTime">-</b></span></div><div class="row" style="margin-top:10px"><button data-action="pause">Pause</button><button data-action="resume">Resume</button><button class="bad" data-action="cancel">Cancel</button></div></article><article class="card"><div class="section">Live Preview</div><img id="preview" class="preview" alt="Live preview" style="display:none"><div id="previewNote" class="status">Waiting for a preview.</div></article><article class="card"><div class="section">Prompt ADAM</div><textarea id="prompt" placeholder="Ask ADAM naturally."></textarea><div class="row"><button class="primary" id="sendPrompt">Send</button><button class="ghost" id="askCreate">Create Model</button><button class="ghost" id="askDataset">Collect Dataset</button><button class="ghost" id="askQuick">Quick</button></div><div id="promptStatus" class="status"></div></article><article class="card"><div class="section">Latest Generation</div><div id="latestGeneration" class="thumbs"></div></article></div></section>33 unmodified lines<pre id="trainingReview" class="status"></pre></div></article></section><section id="jobsView" class="view"><article class="card"><div class="section">Jobs</div><div id="queues" class="grid"></div></article></section><section id="settingsView" class="view"><div class="grid"><article class="card"><div class="section">Remote Control</div><label class="toggle"><span>Auto-approve remote training</span><input id="autoApproveTraining" type="checkbox"></label><label class="toggle"><span>Keep screen updated</span><input id="keepAwake" type="checkbox"></label><div id="settingsStatus" class="status"></div></article><article class="card"><div class="section">Remembered Locations</div><div id="locationsList" class="dataset-list"></div></article><article class="card"><div class="section">System</div><div id="system" class="grid two"></div></article></div></section></main><nav class="tabs"><button class="active" data-view="home"><b>^</b>Home</button><button data-view="datasetsView"><b>O</b>Datasets</button><button data-view="createView"><b>+</b>Create</button><button data-view="jobsView"><b>/</b>Jobs</button><button data-view="settingsView"><b>*</b>Settings</button></nav><script>(function(){var queryString=window.location.search||"";var state={datasets:[],locations:[],trainingSchema:{trainers:[],base_models:[],presets:[]},selectedDataset:"",datasetPage:1,selectedItem:null,activeJobId:"",refreshMs:3000,locationFilter:""};var timer=null;function $(id){return document.getElementById(id)}function list(v){return Array.isArray(v)?v:[]}15 unmodified lineswindow.addEventListener("unhandledrejection",function(e){text("connection","Remote request error: "+errorMessage(e.reason))});function img(src,alt,note){var im=document.createElement("img");im.alt=alt||"";if(src)im.src=authUrl(src);im.onerror=function(){im.style.display="none";if(note)note.textContent="Preview unavailable"};return im}function renderStatus(p){p=p||{};text("connection",(p.app||"ADAM")+" online - "+(p.scope||"remote"));var perms=p.permissions||{};var job=p.active_job||null;state.activeJobId=job&&job.id?job.id:"";if(job){text("activeJob",(job.project||"Active job")+" - "+(job.status||"")+" - "+String(job.progress||0)+"% - Time left "+((job.timing||{}).remaining_label||""));text("timeLeft",(job.timing||{}).remaining_label||"-");text("finishTime",(job.timing||{}).finish_label||"-");$("activeBar").style.width=String(job.progress||0)+"%"}else{text("activeJob","No active job.");text("timeLeft","-");text("finishTime","-");$("activeBar").style.width="0%"}var buttons=document.querySelectorAll("[data-action]");for(var i=0;i<buttons.length;i++)buttons[i].disabled=!job||!perms.job_control;$("autoApproveTraining").checked=!!perms.auto_approve_training;$("autoApproveTraining").disabled=!perms.job_control&&!perms.auto_approve_training;renderPreview(p.preview||{});renderLatest(p.latest_generation||{});renderSystem(p.system||{});renderQueues(p)}function renderPreview(info){var p=$("preview");if(info.available){p.style.display="block";p.src=authUrl("/api/preview","t="+Date.now());text("previewNote",(info.kind||"preview")+" "+(info.current||info.epoch||"")+"/"+(info.total||""))}else{p.style.display="none";p.removeAttribute("src");text("previewNote","Waiting for a preview.")}}function renderLatest(latest){var root=$("latestGeneration");clear(root);var images=list(latest.images).slice(0,8);if(!latest.available||!images.length){var d=document.createElement("div");d.className="status";d.textContent="Finished generated images will appear here.";root.appendChild(d);return}images.forEach(function(item){var b=document.createElement("button");b.className="thumb";b.type="button";var n=document.createElement("div");n.textContent=latest.model_name||"Generated image";b.appendChild(img(item.url,"Generated image",n));b.appendChild(n);b.onclick=function(){window.open(authUrl(item.url,"t="+Date.now()),"_blank","noopener,noreferrer")};root.appendChild(b)})}function renderSystem(sys){var root=$("system");clear(root);[["CPU",sys.cpu_percent],["RAM",sys.memory_percent],["GPU",sys.gpu_percent],["VRAM",sys.vram_percent]].forEach(function(m){var d=document.createElement("div");d.className="card";appendText(d,"div",m[0],"meta");appendText(d,"b",m[1]==null?"-":m[1]+"%");root.appendChild(d)})}function renderQueues(p){var root=$("queues");clear(root);var jobs=list(p.queue).concat(list(p.completed_jobs),list(p.failed_jobs)).slice(0,40);if(!jobs.length){text("queues","No jobs yet.");return}jobs.forEach(function(job){var d=document.createElement("div");d.className="queue-item";appendText(d,"b",job.project||"ADAM Job");appendText(d,"div",(job.status||"")+" - "+String(job.progress||0)+"%","meta");if(job.current_step_title){var s=document.createElement("div");s.className="meta";s.textContent=job.current_step_title;d.appendChild(s)}if(job.error){var e=document.createElement("div");e.className="bad-text";e.textContent=job.error;d.appendChild(e)}root.appendChild(d)})}function load(){return getJson("/api/status").then(renderStatus).catch(function(e){text("connection","Offline: "+errorMessage(e))})}function loadData(){return Promise.all([getJson("/api/v1/datasets").then(function(p){state.datasets=list(p.datasets);renderDatasets();fillDatasets()}),getJson("/api/v1/datasets/locations").then(function(p){state.locations=list(p.locations);renderLocations()}),getJson("/api/v1/training/schema").then(function(p){state.trainingSchema=p||{trainers:[]};fillCreate()})]).catch(function(e){text("trainingReview",errorMessage(e))})}function datasetMatches(d){var q=($("datasetSearch").value||"").toLowerCase();if(q&&(d.name||"").toLowerCase().indexOf(q)<0)return false;if(state.locationFilter&&d.location_id!==state.locationFilter)return false;return true}function datasetImage(d){return d.thumbnail_url?img(d.thumbnail_url,"Dataset thumbnail"):document.createElement("span")}function useDataset(id){if(!id)return;postJson("/api/v1/datasets/"+encodeURIComponent(id)+"/use",{}).then(function(p){var d=p.dataset||{};state.selectedDataset=d.id||id;fillDatasets();if(!$("modelName").value)$("modelName").value=d.name||"";updateSelectedDatasetNote();switchView("createView");loadData()}).catch(function(e){text("datasetStats",errorMessage(e))})}6 unmodified linesfunction openDataset(id,page){state.selectedDataset=id;state.datasetPage=page;text("datasetStats","Loading preview...");$("datasetDetail").style.display="block";getJson("/api/v1/datasets/"+encodeURIComponent(id)+"/items?page="+encodeURIComponent(page)+"&page_size=24").then(function(p){var d=p.dataset||{};text("datasetTitle",d.name||"Dataset");text("datasetStats",String(d.image_count||d.item_count||0)+" items - "+String(d.caption_count||0)+" captions - "+String(d.missing_caption_count||0)+" missing captions - "+(d.dataset_format||"Dataset"));text("pageLabel","Page "+String((p.pagination||{}).page||page));$("prevPage").disabled=page<=1;$("nextPage").disabled=!(p.pagination||{}).has_next;var grid=$("datasetGrid");clear(grid);list(p.items).forEach(function(item){var b=document.createElement("button");b.type="button";b.className="thumb";var note=document.createElement("div");note.textContent=(item.display_name||"Image")+"\\n"+(item.decision||"unreviewed");b.appendChild(img(item.thumbnail_url,"Dataset image",note));b.appendChild(note);b.onclick=function(){showImage(item)};grid.appendChild(b)})}).catch(function(e){text("datasetStats",errorMessage(e))})}function showImage(item){state.selectedItem=item;$("imageDetail").style.display="block";$("detailImage").src=authUrl(item.preview_url);text("detailName",item.display_name||"Image");text("detailDims",String((item.dimensions||{}).width||0)+" x "+String((item.dimensions||{}).height||0));$("captionEditor").value=item.caption||"";text("imageStatus",item.decision||"unreviewed")}function fillCreate(){clear($("trainer"));list(state.trainingSchema.trainers).forEach(function(t){option($("trainer"),t.name,t.id)});clear($("preset"));option($("preset"),"Custom","");list(state.trainingSchema.presets).forEach(function(p){option($("preset"),p.name,p.id)});clear($("baseModel"));list(state.trainingSchema.base_models).forEach(function(m){option($("baseModel"),m.name,m.id)});fillDatasets();renderSettings();ensureEpochField()}function makeSetting(key,spec,advanced){if(key==="base_model")return null;var wrap=document.createElement("div");wrap.className=spec.type==="bool"?"toggle":"form-row";var input;if(spec.type==="bool"){var label=document.createElement("div");appendText(label,"b",spec.label||key);appendText(label,"div",spec.description||"Enable this setting","hint");input=document.createElement("input");input.type="checkbox";input.checked=spec.default!==false;wrap.appendChild(label);wrap.appendChild(input)}else{var label=document.createElement("label");label.textContent=spec.label||key;wrap.appendChild(label);if(spec.type==="choice"){input=document.createElement("select");list(spec.options).forEach(function(v){option(input,String(v),String(v))})}else{input=document.createElement("input");input.type=(spec.type==="int"||spec.type==="float"||spec.type==="slider")?"number":"text";if(spec.min!==undefined)input.min=spec.min;if(spec.max!==undefined)input.max=spec.max;if(spec.step!==undefined)input.step=spec.step}input.value=spec.default!==undefined?String(spec.default):"";wrap.appendChild(input)}input.id=fieldId(key);input.setAttribute("data-setting-key",key);input.setAttribute("data-setting-type",spec.type||"text");input.setAttribute("data-advanced",advanced?"1":"0");return wrap}function renderSettings(){var t=activeTrainer();var schema=t.settings||{};var basic=$("basicSettings"),advanced=$("advancedSettings");clear(basic);clear(advanced);var basicKeys=["resolution","batch_size","preview_enabled"];Object.keys(schema).forEach(function(key){var spec=schema[key]||{};var isAdvanced=!!spec.advanced||basicKeys.indexOf(key)<0;var node=makeSetting(key,spec,isAdvanced);if(!node)return;(isAdvanced?advanced:basic).appendChild(node)});$("baseModelWrap").style.display=schema.base_model?"grid":"none"}function settingValue(node){var type=node.getAttribute("data-setting-type");if(type==="bool")return !!node.checked;if(type==="int"||type==="slider")return Number(node.value||0);if(type==="float")return Number(node.value||0);var spec=schemaFor(node.getAttribute("data-setting-key"));if(spec.type==="choice"){var sample=list(spec.options)[0];if(typeof sample==="number")return Number(node.value)}return node.value}function trainingPayload(){var settings={};var nodes=document.querySelectorAll("[data-setting-key]");for(var i=0;i<nodes.length;i++){var key=nodes[i].getAttribute("data-setting-key");if(key==="epochs")continue;settings[key]=settingValue(nodes[i])}return{trainer:$("trainer").value,dataset_id:state.selectedDataset||$("trainDataset").value,base_model_id:$("baseModel").value,model_name:$("modelName").value,trigger_word:settings.trigger_word||"",epochs:Number($(fieldId("epochs"))&&$(fieldId("epochs")).value||10),settings:settings}}function applyPreset(){var id=$("preset").value;var preset=list(state.trainingSchema.presets).filter(function(p){return p.id===id})[0];if(!preset)return;if(preset.trainer){$("trainer").value=preset.trainer;renderSettings();ensureEpochField()}if(preset.epochs&&$(fieldId("epochs")))$(fieldId("epochs")).value=preset.epochs;Object.keys(preset.settings||{}).forEach(function(key){var n=$(fieldId(key));if(!n)return;if(n.type==="checkbox")n.checked=!!preset.settings[key];else n.value=String(preset.settings[key])})}function ensureEpochField(){if(!$(fieldId("epochs"))){var node=makeSetting("epochs",{label:"Epochs",type:"int",default:10,min:1,max:100000},false);$("basicSettings").appendChild(node)}}$("trainer").onchange=function(){renderSettings();ensureEpochField()};$("preset").onchange=applyPreset;$("datasetSearch").oninput=renderDatasets;$("filterDatasets").onclick=function(){var chips=$("locationChips");chips.style.display=chips.style.display==="none"?"flex":"none"};$("chooseDataset").onclick=function(){switchView("datasetsView")};$("createBack").onclick=function(){switchView("home")};$("createHelp").onclick=function(){text("trainingReview","Choose a preset, trainer, model name, and dataset. Advanced settings come from ADAM's trainer registry.")};$("askInstead").onclick=function(){switchView("home");$("prompt").focus()};$("useDataset").onclick=function(){useDataset(state.selectedDataset)};$("selectDatasetForCreate").onclick=$("useDataset").onclick;$("reviewPlan").onclick=function(){postJson("/api/v1/training/plan",trainingPayload()).then(function(p){$("trainingReview").textContent=JSON.stringify(p.plan||p,null,2)}).catch(function(e){text("trainingReview",errorMessage(e))})};$("startTraining").onclick=function(){if(!state.selectedDataset&&!$("trainDataset").value){text("trainingReview","Choose a dataset first.");return}if(!confirm("Start this training job on the PC?"))return;postJson("/api/v1/training/start",trainingPayload()).then(function(p){text("trainingReview",p.message||"Training queued.");load();loadData()}).catch(function(e){text("trainingReview",errorMessage(e))})};$("prevPage").onclick=function(){openDataset(state.selectedDataset,Math.max(1,state.datasetPage-1))};$("nextPage").onclick=function(){openDataset(state.selectedDataset,state.datasetPage+1)};$("saveCaption").onclick=function(){if(!state.selectedDataset||!state.selectedItem)return;postJson("/api/v1/datasets/"+encodeURIComponent(state.selectedDataset)+"/items/"+encodeURIComponent(state.selectedItem.id)+"/caption",{caption:$("captionEditor").value}).then(function(p){text("imageStatus",p.message||"Saved.")}).catch(function(e){text("imageStatus",errorMessage(e))})};function decide(decision){if(!state.selectedDataset||!state.selectedItem)return;postJson("/api/v1/datasets/"+encodeURIComponent(state.selectedDataset)+"/items/"+encodeURIComponent(state.selectedItem.id)+"/decision",{decision:decision}).then(function(p){text("imageStatus",p.message||decision);openDataset(state.selectedDataset,state.datasetPage)}).catch(function(e){text("imageStatus",errorMessage(e))})}$("keepImage").onclick=function(){decide("keep")};$("rejectImage").onclick=function(){decide("reject")};$("unreviewImage").onclick=function(){decide("unreviewed")};$("sendPrompt").onclick=function(){postJson("/api/prompt",{prompt:$("prompt").value}).then(function(p){text("promptStatus",p.message||"Sent.");$("prompt").value="";load()}).catch(function(e){text("promptStatus",errorMessage(e))})};$("askCreate").onclick=function(){switchView("createView")};$("askDataset").onclick=function(){$("prompt").value="Collect a new dataset for Example."};$("askQuick").onclick=function(){$("prompt").value="Generate an image of Example."};$("refresh").onclick=function(){load();loadData()};$("autoApproveTraining").onchange=function(e){postJson("/api/remote-settings",{auto_approve_training:e.target.checked}).then(function(p){text("settingsStatus",p.message||"Saved.");load()}).catch(function(err){text("settingsStatus",errorMessage(err))})};$("keepAwake").onchange=function(e){state.refreshMs=e.target.checked?1500:5000;startTimer();text("settingsStatus",e.target.checked?"Fast refresh is on.":"Quiet refresh is on.")};function startTimer(){if(timer)clearInterval(timer);timer=setInterval(load,state.refreshMs)}load();loadData();startTimer();21 unmodified lines222324252627282933 unmodified lines63646566676869707172737475767778798015 unmodified lines969798991001011021031041051061071081091101111121131146 unmodified lines12112212312412512612712812913013113213313413513613713813914014114214314414514621 unmodified lines<div class="grid wide"><article class="card"><div class="section">Active Job</div><div id="activeJob">Checking ADAM...</div><div class="progress"><div id="activeBar" class="bar"></div></div><div class="row" style="margin-top:10px"><span class="pill">Time Left <b id="timeLeft">-</b></span><span class="pill">Finish <b id="finishTime">-</b></span></div><div class="row" style="margin-top:10px"><button data-action="pause">Pause</button><button data-action="resume">Resume</button><button class="bad" data-action="cancel">Cancel</button></div></article><article class="card"><div class="section">Live Preview</div><img id="preview" class="preview" alt="Live preview" style="display:none"><div id="previewNote" class="status">Waiting for a preview.</div></article><article class="card"><div class="section">Prompt ADAM</div><textarea id="prompt" placeholder="Ask ADAM naturally."></textarea><div class="row"><button class="primary" id="sendPrompt">Send</button><button class="ghost" id="askCreate">Create Model</button><button class="ghost" id="askDataset">Collect Dataset</button><button class="ghost" id="askQuick">Quick</button></div><div id="promptStatus" class="status"></div></article><article class="card"><div class="section">Image Generation</div><div class="status">Choose the model directly instead of describing a LoRA in a prompt.</div><button id="openGeneration" class="primary" style="margin-top:10px">Generate an Image</button></article><article class="card"><div class="section">Latest Generation</div><div id="latestGeneration" class="thumbs"></div></article></div></section>33 unmodified lines<pre id="trainingReview" class="status"></pre></div></article></section><section id="generationView" class="view"><div class="titlebar"><button id="generationBack" class="icon" title="Back"><</button><h1>Generate Image</h1><span></span></div><article class="panel"><div class="form"><div class="form-row"><label>Provider</label><select id="generationProvider"></select></div><div class="form-row stack"><label>Model</label><select id="generationModel"></select><div id="generationModelNote" class="hint"></div></div><div id="generationBaseWrap" class="form-row stack"><label>Base model</label><select id="generationBase"></select></div><div class="form-row stack"><label>Prompt</label><textarea id="generationPrompt" placeholder="Describe the image you want."></textarea></div><div class="form-row stack"><label>Negative prompt</label><textarea id="generationNegative" placeholder="Optional"></textarea></div><div class="settings-grid"><div class="form-row"><label>Images</label><input id="generationCount" type="number" min="1" max="8" value="1"></div><div class="form-row"><label>Steps</label><input id="generationSteps" type="number" min="1" value="30"></div><div class="form-row"><label>Seed</label><input id="generationSeed" type="number" min="0" value="0"></div><div class="form-row"><label>LoRA strength</label><input id="generationStrength" type="number" min="0" max="3" step="0.05" value="1"></div></div><button id="startGeneration" class="primary big-action">Generate</button><div id="generationStatus" class="status"></div></div></article></section><section id="jobsView" class="view"><article class="card"><div class="section">Jobs</div><div id="queues" class="grid"></div></article></section><section id="settingsView" class="view"><div class="grid"><article class="card"><div class="section">Remote Control</div><label class="toggle"><span>Auto-approve remote training</span><input id="autoApproveTraining" type="checkbox"></label><label class="toggle"><span>Keep screen updated</span><input id="keepAwake" type="checkbox"></label><div id="settingsStatus" class="status"></div></article><article class="card"><div class="section">Remembered Locations</div><div id="locationsList" class="dataset-list"></div></article><article class="card"><div class="section">System</div><div id="system" class="grid two"></div></article></div></section></main><nav class="tabs"><button class="active" data-view="home"><b>^</b>Home</button><button data-view="datasetsView"><b>O</b>Datasets</button><button data-view="createView"><b>+</b>Create</button><button data-view="jobsView"><b>/</b>Jobs</button><button data-view="settingsView"><b>*</b>Settings</button></nav><script>(function(){var queryString=window.location.search||"";var state={datasets:[],locations:[],trainingSchema:{trainers:[],base_models:[],presets:[]},generationSchema:{providers:[],models:[],base_models:[]},selectedDataset:"",datasetPage:1,selectedItem:null,activeJobId:"",promptJobId:"",promptLocked:false,refreshMs:3000,locationFilter:""};var timer=null;function $(id){return document.getElementById(id)}function list(v){return Array.isArray(v)?v:[]}15 unmodified lineswindow.addEventListener("unhandledrejection",function(e){text("connection","Remote request error: "+errorMessage(e.reason))});function img(src,alt,note){var im=document.createElement("img");im.alt=alt||"";if(src)im.src=authUrl(src);im.onerror=function(){im.style.display="none";if(note)note.textContent="Preview unavailable"};return im}function renderStatus(p){p=p||{};text("connection",(p.app||"ADAM")+" online - "+(p.scope||"remote"));var perms=p.permissions||{};var job=p.active_job||null;state.activeJobId=job&&job.id?job.id:"";if(state.promptLocked&&state.promptJobId&&job&&job.id===state.promptJobId){state.promptLocked=false;state.promptJobId="";$("sendPrompt").disabled=false;text("promptStatus","Job started. You can send another prompt.")}if(job){text("activeJob",(job.project||"Active job")+" - "+(job.status||"")+" - "+String(job.progress||0)+"% - Time left "+((job.timing||{}).remaining_label||""));text("timeLeft",(job.timing||{}).remaining_label||"-");text("finishTime",(job.timing||{}).finish_label||"-");$("activeBar").style.width=String(job.progress||0)+"%"}else{text("activeJob","No active job.");text("timeLeft","-");text("finishTime","-");$("activeBar").style.width="0%"}var buttons=document.querySelectorAll("[data-action]");for(var i=0;i<buttons.length;i++)buttons[i].disabled=!job||!perms.job_control;$("autoApproveTraining").checked=!!perms.auto_approve_training;$("autoApproveTraining").disabled=!perms.job_control&&!perms.auto_approve_training;renderPreview(p.preview||{});renderLatest(p.latest_generation||{});renderSystem(p.system||{});renderQueues(p,perms)}function renderPreview(info){var p=$("preview");if(info.available){p.style.display="block";p.src=authUrl("/api/preview","t="+Date.now());text("previewNote",(info.kind||"preview")+" "+(info.current||info.epoch||"")+"/"+(info.total||""))}else{p.style.display="none";p.removeAttribute("src");text("previewNote","Waiting for a preview.")}}function renderLatest(latest){var root=$("latestGeneration");clear(root);var images=list(latest.images).slice(0,8);if(!latest.available||!images.length){var d=document.createElement("div");d.className="status";d.textContent="Finished generated images will appear here.";root.appendChild(d);return}images.forEach(function(item){var b=document.createElement("button");b.className="thumb";b.type="button";var n=document.createElement("div");n.textContent=latest.model_name||"Generated image";b.appendChild(img(item.url,"Generated image",n));b.appendChild(n);b.onclick=function(){window.open(authUrl(item.url,"t="+Date.now()),"_blank","noopener,noreferrer")};root.appendChild(b)})}function renderSystem(sys){var root=$("system");clear(root);[["CPU",sys.cpu_percent],["RAM",sys.memory_percent],["GPU",sys.gpu_percent],["VRAM",sys.vram_percent]].forEach(function(m){var d=document.createElement("div");d.className="card";appendText(d,"div",m[0],"meta");appendText(d,"b",m[1]==null?"-":m[1]+"%");root.appendChild(d)})}function renderQueues(p,perms){var root=$("queues");clear(root);var jobs=list(p.queue).concat(list(p.completed_jobs),list(p.failed_jobs)).slice(0,40);if(!jobs.length){text("queues","No jobs yet.");return}jobs.forEach(function(job){var d=document.createElement("div");d.className="queue-item";appendText(d,"b",job.project||"ADAM Job");appendText(d,"div",(job.status||"")+" - "+String(job.progress||0)+"%","meta");if(job.current_step_title){var s=document.createElement("div");s.className="meta";s.textContent=job.current_step_title;d.appendChild(s)}if(job.error){var e=document.createElement("div");e.className="bad-text";e.textContent=job.error;d.appendChild(e)}if(perms&&perms.job_control&&["Queued","Scheduled","Awaiting confirmation","Running","Paused","Interrupted"].indexOf(job.status)>=0){var cancel=document.createElement("button");cancel.className="bad";cancel.textContent="Cancel job";cancel.style.marginTop="8px";cancel.onclick=function(){cancel.disabled=true;postJson("/api/job",{job_id:job.id,action:"cancel"}).then(function(){load()}).catch(function(e){text("promptStatus",errorMessage(e));cancel.disabled=false})};d.appendChild(cancel)}root.appendChild(d)})}function load(){return getJson("/api/status").then(renderStatus).catch(function(e){text("connection","Offline: "+errorMessage(e))})}function loadData(){return Promise.all([getJson("/api/v1/datasets").then(function(p){state.datasets=list(p.datasets);renderDatasets();fillDatasets()}),getJson("/api/v1/datasets/locations").then(function(p){state.locations=list(p.locations);renderLocations()}),getJson("/api/v1/training/schema").then(function(p){state.trainingSchema=p||{trainers:[]};fillCreate()}),getJson("/api/v1/generation/schema").then(function(p){state.generationSchema=p||{providers:[],models:[],base_models:[]};fillGeneration()})]).catch(function(e){text("trainingReview",errorMessage(e))})}function datasetMatches(d){var q=($("datasetSearch").value||"").toLowerCase();if(q&&(d.name||"").toLowerCase().indexOf(q)<0)return false;if(state.locationFilter&&d.location_id!==state.locationFilter)return false;return true}function datasetImage(d){return d.thumbnail_url?img(d.thumbnail_url,"Dataset thumbnail"):document.createElement("span")}function useDataset(id){if(!id)return;postJson("/api/v1/datasets/"+encodeURIComponent(id)+"/use",{}).then(function(p){var d=p.dataset||{};state.selectedDataset=d.id||id;fillDatasets();if(!$("modelName").value)$("modelName").value=d.name||"";updateSelectedDatasetNote();switchView("createView");loadData()}).catch(function(e){text("datasetStats",errorMessage(e))})}6 unmodified linesfunction openDataset(id,page){state.selectedDataset=id;state.datasetPage=page;text("datasetStats","Loading preview...");$("datasetDetail").style.display="block";getJson("/api/v1/datasets/"+encodeURIComponent(id)+"/items?page="+encodeURIComponent(page)+"&page_size=24").then(function(p){var d=p.dataset||{};text("datasetTitle",d.name||"Dataset");text("datasetStats",String(d.image_count||d.item_count||0)+" items - "+String(d.caption_count||0)+" captions - "+String(d.missing_caption_count||0)+" missing captions - "+(d.dataset_format||"Dataset"));text("pageLabel","Page "+String((p.pagination||{}).page||page));$("prevPage").disabled=page<=1;$("nextPage").disabled=!(p.pagination||{}).has_next;var grid=$("datasetGrid");clear(grid);list(p.items).forEach(function(item){var b=document.createElement("button");b.type="button";b.className="thumb";var note=document.createElement("div");note.textContent=(item.display_name||"Image")+"\\n"+(item.decision||"unreviewed");b.appendChild(img(item.thumbnail_url,"Dataset image",note));b.appendChild(note);b.onclick=function(){showImage(item)};grid.appendChild(b)})}).catch(function(e){text("datasetStats",errorMessage(e))})}function showImage(item){state.selectedItem=item;$("imageDetail").style.display="block";$("detailImage").src=authUrl(item.preview_url);text("detailName",item.display_name||"Image");text("detailDims",String((item.dimensions||{}).width||0)+" x "+String((item.dimensions||{}).height||0));$("captionEditor").value=item.caption||"";text("imageStatus",item.decision||"unreviewed")}function fillCreate(){clear($("trainer"));list(state.trainingSchema.trainers).forEach(function(t){option($("trainer"),t.name,t.id)});clear($("preset"));option($("preset"),"Custom","");list(state.trainingSchema.presets).forEach(function(p){option($("preset"),p.name,p.id)});clear($("baseModel"));list(state.trainingSchema.base_models).forEach(function(m){option($("baseModel"),m.name,m.id)});fillDatasets();renderSettings();ensureEpochField()}function activeGenerationProvider(){return list(state.generationSchema.providers).filter(function(p){return p.id===$("generationProvider").value})[0]||{model_trainers:[],options:{}}}function fillGeneration(){var current=$("generationProvider").value;clear($("generationProvider"));list(state.generationSchema.providers).forEach(function(p){option($("generationProvider"),p.name,p.id)});if(current)$("generationProvider").value=current;fillGenerationModels()}function fillGenerationModels(){var provider=activeGenerationProvider(),current=$("generationModel").value,trainers=list(provider.model_trainers);clear($("generationModel"));list(state.generationSchema.models).filter(function(m){return !trainers.length||trainers.indexOf(m.trainer)>=0}).forEach(function(m){option($("generationModel"),m.name+(m.trigger_word?" · trigger: "+m.trigger_word:""),m.id)});if(current)$("generationModel").value=current;clear($("generationBase"));list(state.generationSchema.base_models).forEach(function(m){option($("generationBase"),m.name,m.id)});var isLora=provider.id==="lora_generator";$("generationBaseWrap").style.display=isLora?"grid":"none";$("generationStrength").parentNode.style.display=isLora?"grid":"none";var selected=list(state.generationSchema.models).filter(function(m){return m.id===$("generationModel").value})[0];text("generationModelNote",selected&&selected.trigger_word?"LoRA trigger word: "+selected.trigger_word:"Choose a completed model.");var opts=provider.options||{};if(opts.step_default)$("generationSteps").value=String(opts.step_default)}function generationPayload(){var provider=activeGenerationProvider();return{provider_id:$("generationProvider").value,model_id:$("generationModel").value,base_model_id:$("generationBase").value,prompt:$("generationPrompt").value,negative_prompt:$("generationNegative").value,image_count:Number($("generationCount").value||1),steps:Number($("generationSteps").value||30),seed:Number($("generationSeed").value||0),sampler:(provider.options&&list(provider.options.samplers)[0])||"DDIM",aspect_ratio:(provider.options&&list(provider.options.aspect_ratios)[0])||"1:1 (Square)",lora_strength:Number($("generationStrength").value||1),prompt_weighting:true}}function makeSetting(key,spec,advanced){if(key==="base_model")return null;var wrap=document.createElement("div");wrap.className=spec.type==="bool"?"toggle":"form-row";var input;if(spec.type==="bool"){var label=document.createElement("div");appendText(label,"b",spec.label||key);appendText(label,"div",spec.description||"Enable this setting","hint");input=document.createElement("input");input.type="checkbox";input.checked=spec.default!==false;wrap.appendChild(label);wrap.appendChild(input)}else{var label=document.createElement("label");label.textContent=spec.label||key;wrap.appendChild(label);if(spec.type==="choice"){input=document.createElement("select");list(spec.options).forEach(function(v){option(input,String(v),String(v))})}else{input=document.createElement("input");input.type=(spec.type==="int"||spec.type==="float"||spec.type==="slider")?"number":"text";if(spec.min!==undefined)input.min=spec.min;if(spec.max!==undefined)input.max=spec.max;if(spec.step!==undefined)input.step=spec.step}input.value=spec.default!==undefined?String(spec.default):"";wrap.appendChild(input)}input.id=fieldId(key);input.setAttribute("data-setting-key",key);input.setAttribute("data-setting-type",spec.type||"text");input.setAttribute("data-advanced",advanced?"1":"0");return wrap}function renderSettings(){var t=activeTrainer();var schema=t.settings||{};var basic=$("basicSettings"),advanced=$("advancedSettings");clear(basic);clear(advanced);var basicKeys=["resolution","batch_size","preview_enabled"];Object.keys(schema).forEach(function(key){var spec=schema[key]||{};var isAdvanced=!!spec.advanced||basicKeys.indexOf(key)<0;var node=makeSetting(key,spec,isAdvanced);if(!node)return;(isAdvanced?advanced:basic).appendChild(node)});$("baseModelWrap").style.display=schema.base_model?"grid":"none"}function settingValue(node){var type=node.getAttribute("data-setting-type");if(type==="bool")return !!node.checked;if(type==="int"||type==="slider")return Number(node.value||0);if(type==="float")return Number(node.value||0);var spec=schemaFor(node.getAttribute("data-setting-key"));if(spec.type==="choice"){var sample=list(spec.options)[0];if(typeof sample==="number")return Number(node.value)}return node.value}function trainingPayload(){var settings={};var nodes=document.querySelectorAll("[data-setting-key]");for(var i=0;i<nodes.length;i++){var key=nodes[i].getAttribute("data-setting-key");if(key==="epochs")continue;settings[key]=settingValue(nodes[i])}return{trainer:$("trainer").value,dataset_id:state.selectedDataset||$("trainDataset").value,base_model_id:$("baseModel").value,model_name:$("modelName").value,trigger_word:settings.trigger_word||"",epochs:Number($(fieldId("epochs"))&&$(fieldId("epochs")).value||10),settings:settings}}function applyPreset(){var id=$("preset").value;var preset=list(state.trainingSchema.presets).filter(function(p){return p.id===id})[0];if(!preset)return;if(preset.trainer){$("trainer").value=preset.trainer;renderSettings();ensureEpochField()}if(preset.epochs&&$(fieldId("epochs")))$(fieldId("epochs")).value=preset.epochs;Object.keys(preset.settings||{}).forEach(function(key){var n=$(fieldId(key));if(!n)return;if(n.type==="checkbox")n.checked=!!preset.settings[key];else n.value=String(preset.settings[key])})}function ensureEpochField(){if(!$(fieldId("epochs"))){var node=makeSetting("epochs",{label:"Epochs",type:"int",default:10,min:1,max:100000},false);$("basicSettings").appendChild(node)}}$("trainer").onchange=function(){renderSettings();ensureEpochField()};$("preset").onchange=applyPreset;$("datasetSearch").oninput=renderDatasets;$("filterDatasets").onclick=function(){var chips=$("locationChips");chips.style.display=chips.style.display==="none"?"flex":"none"};$("chooseDataset").onclick=function(){switchView("datasetsView")};$("createBack").onclick=function(){switchView("home")};$("createHelp").onclick=function(){text("trainingReview","Choose a preset, trainer, model name, and dataset. Advanced settings come from ADAM's trainer registry.")};$("askInstead").onclick=function(){switchView("home");$("prompt").focus()};$("useDataset").onclick=function(){useDataset(state.selectedDataset)};$("selectDatasetForCreate").onclick=$("useDataset").onclick;$("openGeneration").onclick=function(){switchView("generationView")};$("generationBack").onclick=function(){switchView("home")};$("generationProvider").onchange=fillGenerationModels;$("generationModel").onchange=fillGenerationModels;$("reviewPlan").onclick=function(){postJson("/api/v1/training/plan",trainingPayload()).then(function(p){$("trainingReview").textContent=JSON.stringify(p.plan||p,null,2)}).catch(function(e){text("trainingReview",errorMessage(e))})};$("startTraining").onclick=function(){if(!state.selectedDataset&&!$("trainDataset").value){text("trainingReview","Choose a dataset first.");return}if(!confirm("Start this training job on the PC?"))return;postJson("/api/v1/training/start",trainingPayload()).then(function(p){text("trainingReview",p.message||"Training queued.");load();loadData()}).catch(function(e){text("trainingReview",errorMessage(e))})};$("startGeneration").onclick=function(){var button=this;button.disabled=true;postJson("/api/v1/generation/start",generationPayload()).then(function(p){text("generationStatus",p.message||"Generation queued.");load()}).catch(function(e){text("generationStatus",errorMessage(e))}).then(function(){button.disabled=false})};$("prevPage").onclick=function(){openDataset(state.selectedDataset,Math.max(1,state.datasetPage-1))};$("nextPage").onclick=function(){openDataset(state.selectedDataset,state.datasetPage+1)};$("saveCaption").onclick=function(){if(!state.selectedDataset||!state.selectedItem)return;postJson("/api/v1/datasets/"+encodeURIComponent(state.selectedDataset)+"/items/"+encodeURIComponent(state.selectedItem.id)+"/caption",{caption:$("captionEditor").value}).then(function(p){text("imageStatus",p.message||"Saved.")}).catch(function(e){text("imageStatus",errorMessage(e))})};function decide(decision){if(!state.selectedDataset||!state.selectedItem)return;postJson("/api/v1/datasets/"+encodeURIComponent(state.selectedDataset)+"/items/"+encodeURIComponent(state.selectedItem.id)+"/decision",{decision:decision}).then(function(p){text("imageStatus",p.message||decision);openDataset(state.selectedDataset,state.datasetPage)}).catch(function(e){text("imageStatus",errorMessage(e))})}$("keepImage").onclick=function(){decide("keep")};$("rejectImage").onclick=function(){decide("reject")};$("unreviewImage").onclick=function(){decide("unreviewed")};$("sendPrompt").onclick=function(){var button=this;if(state.promptLocked)return;button.disabled=true;postJson("/api/prompt",{prompt:$("prompt").value}).then(function(p){state.promptJobId=p.job_id||"";state.promptLocked=!!state.promptJobId;text("promptStatus",state.promptLocked?"Queued. Sending is available again when this job starts.":(p.message||"Sent."));$("prompt").value="";if(!state.promptLocked)button.disabled=false;load()}).catch(function(e){text("promptStatus",errorMessage(e));button.disabled=false})};$("askCreate").onclick=function(){switchView("createView")};$("askDataset").onclick=function(){$("prompt").value="Collect a new dataset for Example."};$("askQuick").onclick=function(){$("prompt").value="Generate an image of Example."};$("refresh").onclick=function(){load();loadData()};$("autoApproveTraining").onchange=function(e){postJson("/api/remote-settings",{auto_approve_training:e.target.checked}).then(function(p){text("settingsStatus",p.message||"Saved.");load()}).catch(function(err){text("settingsStatus",errorMessage(err))})};$("keepAwake").onchange=function(e){state.refreshMs=e.target.checked?1500:5000;startTimer();text("settingsStatus",e.target.checked?"Fast refresh is on.":"Quiet refresh is on.")};function startTimer(){if(timer)clearInterval(timer);timer=setInterval(load,state.refreshMs)}load();loadData();startTimer();
2 unmodified lines34567846 unmodified lines555657585960363 unmodified lines424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463177 unmodified lines6416426436446456466472 unmodified linesfrom pathlib import Pathimport osimport tempfilefrom typing import Anyfrom urllib.parse import parse_qs46 unmodified linesself.auto_approve_training = auto_approve_trainingself._asset_fallback: AssetRegistry | None = Noneself._studio: StudioStore | None = Nonedef route(self,363 unmodified linesreturn self._dataset_summary(asset, record)def models(self) -> list[dict[str, Any]]:assets = self._assets()experiment_by_model: dict[str, Any] = {}try:for run in getattr(getattr(self.jobs, "experiments", None), "list_runs", lambda limit=100: [])(limit=100):experiment_by_model.setdefault(run.model_name, run)except Exception:experiment_by_model = {}rows = []for asset in assets.assets:if asset.kind not in {"model", "base_model"} or not Path(asset.path).exists():continuedataset = next((item for item in assets.assets if item.id == asset.dataset_id), None)metadata = dict(asset.metadata or {})trigger_word = str(metadata.get("trigger_word") or (asset.name if asset.trainer == "lora" else ""))latest = experiment_by_model.get(asset.name)rows.append({"id": self._asset_public_id(asset),"name": asset.name,"kind": asset.kind,"architecture": asset.trainer or ("stable_diffusion" if asset.kind == "base_model" else ""),"trainer": asset.trainer,"checkpoint_name": Path(asset.checkpoint or asset.path).name,"dataset": None if dataset is None else {"id": self._asset_public_id(dataset), "name": dataset.name},"epochs": asset.epochs,"trigger_word": trigger_word,"latest_experiment": None if latest is None else {"id": latest.id,"status": latest.status,"resolution": latest.resolution,"dataset_name": latest.dataset_name,"trigger_word": getattr(latest, "trigger_word", ""),},})return rows[:300]def training_schema(self) -> dict[str, Any]:registry = self._registry()177 unmodified lines"options": tool.generation_options,"settings": registry.model_plugins.generation_schema_for_tool(tool.id),})return {"providers": providers, "models": [item for item in self.models() if item["kind"] == "model"], "base_models": [item for item in self.models() if item["kind"] == "base_model"]}def start_generation(self, payload: dict[str, Any]) -> dict[str, Any]:if self.jobs is None:2 unmodified lines34567891046 unmodified lines575859606162636465666768363 unmodified lines432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476177 unmodified lines6546556566576586596606616626636646652 unmodified linesfrom pathlib import Pathimport osimport tempfileimport threadingimport timefrom typing import Anyfrom urllib.parse import parse_qs46 unmodified linesself.auto_approve_training = auto_approve_trainingself._asset_fallback: AssetRegistry | None = Noneself._studio: StudioStore | None = None# The dashboard requests both schemas at once. They share an asset# registry, so build one short-lived catalog instead of asking two# request threads to rediscover and rewrite it concurrently.self._model_catalog_lock = threading.RLock()self._model_catalog: list[dict[str, Any]] = []self._model_catalog_at = 0.0def route(self,363 unmodified linesreturn self._dataset_summary(asset, record)def models(self) -> list[dict[str, Any]]:with self._model_catalog_lock:if time.monotonic() - self._model_catalog_at < 1.0:return list(self._model_catalog)assets = self._assets()experiment_by_model: dict[str, Any] = {}try:for run in getattr(getattr(self.jobs, "experiments", None), "list_runs", lambda limit=100: [])(limit=100):experiment_by_model.setdefault(run.model_name, run)except Exception:experiment_by_model = {}rows = []for asset in assets.assets:if asset.kind not in {"model", "base_model"} or not Path(asset.path).exists():continuedataset = next((item for item in assets.assets if item.id == asset.dataset_id), None)metadata = dict(asset.metadata or {})trigger_word = str(metadata.get("trigger_word") or (asset.name if asset.trainer == "lora" else ""))latest = experiment_by_model.get(asset.name)rows.append({"id": self._asset_public_id(asset),"name": asset.name,"kind": asset.kind,"architecture": asset.trainer or ("stable_diffusion" if asset.kind == "base_model" else ""),"trainer": asset.trainer,"checkpoint_name": Path(asset.checkpoint or asset.path).name,"dataset": None if dataset is None else {"id": self._asset_public_id(dataset), "name": dataset.name},"epochs": asset.epochs,"trigger_word": trigger_word,"latest_experiment": None if latest is None else {"id": latest.id,"status": latest.status,"resolution": latest.resolution,"dataset_name": latest.dataset_name,"trigger_word": getattr(latest, "trigger_word", ""),},})self._model_catalog = rows[:300]self._model_catalog_at = time.monotonic()return list(self._model_catalog)def training_schema(self) -> dict[str, Any]:registry = self._registry()177 unmodified lines"options": tool.generation_options,"settings": registry.model_plugins.generation_schema_for_tool(tool.id),})models = self.models()return {"providers": providers,"models": [item for item in models if item["kind"] == "model"],"base_models": [item for item in models if item["kind"] == "base_model"],}def start_generation(self, payload: dict[str, Any]) -> dict[str, Any]:if self.jobs is None:
25 unmodified lines262728293031123 unmodified lines15515615715815916025 unmodified linesTOOL_FOLDER_DEFINITIONS = (ToolFolderDefinition("dataset_collector","Dataset Collector",123 unmodified linesdef parse_assignments(self, text: str) -> dict[str, str]:"""Recognize folder assignments pasted into chat without executing them."""patterns = {"ddpm_trainer": r"(?im)^\s*DDPM(?:\s+Trainer)?\s*:\s*(.+?)\s*$","flow_trainer": (r"(?im)^\s*Flow(?:\s+Matching)?(?:\s+Trainer)?\s*:\s*(.+?)\s*$"25 unmodified lines26272829303132333435123 unmodified lines15916016116216316416525 unmodified linesTOOL_FOLDER_DEFINITIONS = (ToolFolderDefinition("wan_video_trainer", "Wan Video LoRA Trainer",("trainer-engine/src/musubi_tuner/wan_train_network.py",),),ToolFolderDefinition("dataset_collector","Dataset Collector",123 unmodified linesdef parse_assignments(self, text: str) -> dict[str, str]:"""Recognize folder assignments pasted into chat without executing them."""patterns = {"wan_video_trainer": r"(?im)^\s*(?:Wan(?:\s+Video)?(?:\s+LoRA)?(?:\s+Trainer)?|LoRA\s*Video\s*Trainer)\s*:\s*(.+?)\s*$","ddpm_trainer": r"(?im)^\s*DDPM(?:\s+Trainer)?\s*:\s*(.+?)\s*$","flow_trainer": (r"(?im)^\s*Flow(?:\s+Matching)?(?:\s+Trainer)?\s*:\s*(.+?)\s*$"
6 unmodified lines7891011122 unmodified lines1516171819201 unmodified line222324252627282 unmodified lines313233343536373839404142434454 unmodified lines991001011021031041056 unmodified lines1121131141151161175 unmodified lines12312412512612712812913013113213313435 unmodified lines1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022035 unmodified lines2092102112122132142152162172182192202212222232242252268 unmodified lines23523623723823924024197 unmodified lines3393403416 unmodified linesimport mathimport queueimport reimport subprocessimport sysimport threading2 unmodified linesfrom adam.config import ConfigManagerfrom adam.executor import ToolAdjustmentRequested, ToolCancelled, ToolContext, ToolExecutionErrorfrom adam.process_control import set_process_tree_paused, terminate_process_tree1 unmodified lineFORCE_STOP_TIMEOUT_SECONDS = 30def _saved_unet_resolution(path: Path) -> int | None:config_path = path / "unet" / "config.json"if not config_path.is_file():return None2 unmodified linesexcept (OSError, json.JSONDecodeError):return Nonesample_size = data.get("sample_size")if isinstance(sample_size, list):sample_size = sample_size[0] if sample_size else Nonetry:return int(sample_size) if sample_size is not None else Noneexcept (TypeError, ValueError):return Nonedef _latest_preview(folder: Path) -> Path | None:try:images = [54 unmodified linescontext.progress(100, "DDPM training completed")def train_ddpm(context: ToolContext,dataset_dir: str,model_name: str,6 unmodified linestraining_intensity: int = 100, preview_enabled: bool = True,preview_every: int = 5, preview_prompt: str = "", preview_seed: int = 123456789,completed_epochs: int = 0,) -> dict[str, object]:"""Run the registered DDPM project without shell interpolation or overwrites."""trainer_root = Path(str(ConfigManager(context.root).get("tool_folders", {}).get("ddpm_trainer", ""))).expanduser()5 unmodified linesraise ToolExecutionError("DDPM train.py was not found. Re-scan the DDPM folder in Settings.")if not dataset.is_dir():raise ToolExecutionError("The selected DDPM dataset folder no longer exists.")image_count = sum(1 for item in dataset.iterdir() if item.is_file() and item.suffix.lower() in IMAGE_EXTENSIONS)if image_count < 2:raise ToolExecutionError("The DDPM dataset needs at least two image files before training can start.")requested_epochs = int(epochs)if not 64 <= int(resolution) <= 512 or int(resolution) % 8 or not 1 <= int(batch_size) <= 64:raise ToolExecutionError("DDPM resolution must be a multiple of 8 (64–512) and batch size 1–64.")if not 1e-7 <= float(learning_rate) <= 0.1 or not 1 <= int(gradient_accumulation_steps) <= 64:raise ToolExecutionError("DDPM learning rate or gradient accumulation is outside ADAM's safe range.")if not 0 <= int(dataloader_num_workers) <= 16 or not 1 <= int(save_every) <= 1000 or not 1 <= int(preview_steps) <= 500 or not 1 <= int(preview_every) <= 100_000 or not 10 <= int(training_intensity) <= 100 or mixed_precision not in {"fp16", "no"}:35 unmodified linesand (resume / "scheduler.bin").is_file())standalone_checkpoint = (resume / "pytorch_model.bin").is_file() or (resume / "model.safetensors").is_file()if not accelerate_checkpoint and not standalone_checkpoint:if not (output / "model_index.json").is_file():raise ToolExecutionError("The saved DDPM model is incomplete and cannot be fine-tuned safely.")pretrained_model = outputtimestamp = time.strftime("%Y%m%d_%H%M%S")output = output.with_name(f"{output.name}_finetuned_{timestamp}")resume = Nonecontext.log("The exact resume checkpoint is incomplete. Creating a new fine-tuned model ""from the saved DDPM pipeline instead.")else:if not output.is_dir():raise ToolExecutionError("The DDPM model folder for resume no longer exists.")try:resume.relative_to(output)except ValueError as exc:raise ToolExecutionError("The DDPM checkpoint must be inside its model folder.") from excif not resume.is_dir() or not resume.name.startswith("checkpoint-"):raise ToolExecutionError("A valid DDPM checkpoint-* folder is required to resume.")checkpoint_resolution = _saved_unet_resolution(resume)if checkpoint_resolution and checkpoint_resolution != int(resolution) and (output / "model_index.json").is_file():pretrained_model = outputtimestamp = time.strftime("%Y%m%d_%H%M%S")output = output.with_name(f"{output.name}_finetuned_{timestamp}")resume = Nonecontext.log(f"Changing DDPM resolution from {checkpoint_resolution}px to {int(resolution)}px. ""Starting a fresh fine-tune from the saved model weights instead of resuming the old optimizer schedule.")if resume is not None:5 unmodified linesf"Continuing after approximately {prior_epochs} completed epochs "f"for {int(epochs) - prior_epochs} additional epochs.")if not resume:if output.exists():raise ToolExecutionError("The chosen DDPM output folder already exists; ADAM will not overwrite it.")output.mkdir(parents=True, exist_ok=False)# The connected trainer asks Accelerate/TensorBoard to write directly to# output/logs/train. Create it up front because its writer does not always# create the nested directory on Windows.(output / "logs" / "train").mkdir(parents=True, exist_ok=True)stop_file = output / ".adam_stop_training.flag"command = [sys.executable, str(script), "--train_data_dir", str(dataset), "--output_dir", str(output),"--model_name", model_name, "--resolution", str(int(resolution)), "--train_batch_size", str(int(batch_size)),"--num_epochs", str(int(epochs)), "--learning_rate", str(float(learning_rate)), "--mixed_precision", mixed_precision,"--ddpm_beta_schedule", "linear", "--tf32", "true", "--save_images_epochs", str(int(preview_every) if preview_enabled else int(epochs) + 1),"--save_model_epochs", str(int(save_every)), "--training_intensity", str(int(training_intensity)), "--dataloader_num_workers", str(int(dataloader_num_workers)),8 unmodified linescommand.extend(["--resume_completed_epochs", str(int(completed_epochs))])if pretrained_model:command.extend(["--pretrained_model_path", str(pretrained_model)])context.log(f"Starting real DDPM training with {image_count} images at {resolution}px, batch {batch_size}, lr {learning_rate}.")context.log(f"Output folder: {output}")process = subprocess.Popen(command, cwd=str(trainer_root), stdout=subprocess.PIPE, stderr=subprocess.STDOUT,text=True, encoding="utf-8", errors="replace", shell=False)97 unmodified lines}],}6 unmodified lines78910111213142 unmodified lines171819202122231 unmodified line252627282930313233343536373839404142434445464748495051525354555657582 unmodified lines61626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611754 unmodified lines1721731741751761771786 unmodified lines1851861871881891901915 unmodified lines19719819920020120220320420520620720820921021135 unmodified lines2472482492502512522532542552562572582592602612622632642652662672682692702712722735 unmodified lines2792802812822832842852862872882892902912922932942952962972982993003013023038 unmodified lines31231331431531631731831932032197 unmodified lines4194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565576 unmodified linesimport mathimport queueimport reimport shutilimport statisticsimport subprocessimport sysimport threading2 unmodified linesfrom adam.config import ConfigManagerfrom adam.executor import ToolAdjustmentRequested, ToolCancelled, ToolContext, ToolExecutionErrorfrom adam.progressive_training import parse_stages, stage_batch_settings, stage_summaryfrom adam.process_control import set_process_tree_paused, terminate_process_tree1 unmodified lineFORCE_STOP_TIMEOUT_SECONDS = 30def _image_files(folder: Path):"""Yield training images below a dataset folder without loading them into memory."""try:yield from (path for path in folder.rglob("*")if path.is_file() and path.suffix.casefold() in IMAGE_EXTENSIONS)except OSError:returndef _training_image_folder(dataset: Path) -> tuple[Path, int]:"""Choose the accepted-frame tree for video datasets, or the dataset itself.YouTube collections retain their provenance by storing accepted frames in``frames/<source>/`` and rejected candidates separately. Passing the rootto a recursive trainer would include rejected images, while only checkingthe root makes the collection appear empty."""frames = dataset / "frames"if frames.is_dir():frame_count = sum(1 for _ in _image_files(frames))if frame_count:return frames, frame_countreturn dataset, sum(1 for _ in _image_files(dataset))def _saved_unet_size(path: Path) -> tuple[int, int] | None:config_path = path / "unet" / "config.json"if not config_path.is_file():return None2 unmodified linesexcept (OSError, json.JSONDecodeError):return Nonesample_size = data.get("sample_size")try:if isinstance(sample_size, list) and len(sample_size) >= 2:return int(sample_size[0]), int(sample_size[1])if sample_size is not None:size = int(sample_size)return size, sizereturn Noneexcept (TypeError, ValueError):return Nonedef _snap_dimension(value: float, *, multiple: int = 16) -> int:return max(64, min(512, int(round(value / multiple)) * multiple))def _dataset_aspect_ratio(dataset: Path) -> float:from PIL import Imageratios: list[float] = []for path in _image_files(dataset):try:with Image.open(path) as image:if image.width > 0 and image.height > 0:ratios.append(image.width / image.height)except OSError:continuereturn statistics.median(ratios) if ratios else 1.0def _training_canvas(dataset: Path, resolution: int, aspect_ratio: str) -> tuple[int, int]:ratios = {"1:1 (Square)": 1.0,"16:9 (Widescreen)": 16 / 9,"9:16 (Portrait)": 9 / 16,"4:3 (Classic)": 4 / 3,"3:4 (Portrait Classic)": 3 / 4,"3:2 (Photo)": 3 / 2,"2:3 (Portrait Photo)": 2 / 3,}ratio = _dataset_aspect_ratio(dataset) if aspect_ratio == "Dataset (Auto)" else ratios.get(aspect_ratio)if ratio is None or ratio <= 0:raise ToolExecutionError("Choose a supported DDPM training aspect ratio.")if abs(ratio - 1.0) < 0.01:return resolution, resolutionif ratio > 1:width, height = resolution, _snap_dimension(resolution / ratio)else:width, height = _snap_dimension(resolution * ratio), resolutionreturn width, heightdef _latest_preview(folder: Path) -> Path | None:try:images = [54 unmodified linescontext.progress(100, "DDPM training completed")def _train_ddpm_stage(context: ToolContext,dataset_dir: str,model_name: str,6 unmodified linestraining_intensity: int = 100, preview_enabled: bool = True,preview_every: int = 5, preview_prompt: str = "", preview_seed: int = 123456789,completed_epochs: int = 0,training_aspect_ratio: str = "Dataset (Auto)", resize_mode: str = "fit",) -> dict[str, object]:"""Run the registered DDPM project without shell interpolation or overwrites."""trainer_root = Path(str(ConfigManager(context.root).get("tool_folders", {}).get("ddpm_trainer", ""))).expanduser()5 unmodified linesraise ToolExecutionError("DDPM train.py was not found. Re-scan the DDPM folder in Settings.")if not dataset.is_dir():raise ToolExecutionError("The selected DDPM dataset folder no longer exists.")training_dataset, image_count = _training_image_folder(dataset)if image_count < 2:raise ToolExecutionError("The DDPM dataset needs at least two image files before training can start.")requested_epochs = int(epochs)if not 64 <= int(resolution) <= 512 or int(resolution) % 8 or not 1 <= int(batch_size) <= 64:raise ToolExecutionError("DDPM resolution must be a multiple of 8 (64–512) and batch size 1–64.")canvas_width, canvas_height = _training_canvas(training_dataset, int(resolution), str(training_aspect_ratio))if resize_mode not in {"fit", "fill", "stretch"}:raise ToolExecutionError("DDPM resize mode must be fit, fill, or stretch.")if not 1e-7 <= float(learning_rate) <= 0.1 or not 1 <= int(gradient_accumulation_steps) <= 64:raise ToolExecutionError("DDPM learning rate or gradient accumulation is outside ADAM's safe range.")if not 0 <= int(dataloader_num_workers) <= 16 or not 1 <= int(save_every) <= 1000 or not 1 <= int(preview_steps) <= 500 or not 1 <= int(preview_every) <= 100_000 or not 10 <= int(training_intensity) <= 100 or mixed_precision not in {"fp16", "no"}:35 unmodified linesand (resume / "scheduler.bin").is_file())standalone_checkpoint = (resume / "pytorch_model.bin").is_file() or (resume / "model.safetensors").is_file()source_model = resume.parent if resume.name.startswith("checkpoint-") else resumeif not accelerate_checkpoint and not standalone_checkpoint:if not (source_model / "model_index.json").is_file():raise ToolExecutionError("The saved DDPM model is incomplete and cannot be fine-tuned safely.")pretrained_model = source_modelresume = Nonecontext.log("The exact resume checkpoint is incomplete. Creating a new fine-tuned model ""from the saved DDPM pipeline instead.")else:if not resume.is_dir() or not resume.name.startswith("checkpoint-"):raise ToolExecutionError("A valid DDPM checkpoint-* folder is required to resume.")checkpoint_size = _saved_unet_size(resume)target_size = (canvas_height, canvas_width)if checkpoint_size and checkpoint_size != target_size and (source_model / "model_index.json").is_file():pretrained_model = source_modelresume = Nonecontext.log(f"Changing DDPM canvas from {checkpoint_size[1]}x{checkpoint_size[0]} to "f"{canvas_width}x{canvas_height}. ""Starting a fresh fine-tune from the saved model weights instead of resuming the old optimizer schedule.")if resume is not None:5 unmodified linesf"Continuing after approximately {prior_epochs} completed epochs "f"for {int(epochs) - prior_epochs} additional epochs.")if output.exists():raise ToolExecutionError("The chosen DDPM output folder already exists; ADAM will not overwrite it.")output.mkdir(parents=True, exist_ok=False)if resume:# The connected trainer resolves --resume_from_checkpoint inside its# output directory. Copy only the checkpoint into this new branch so# it can restore optimizer state without touching the source model.resume_copy = output / resume.nameshutil.copytree(resume, resume_copy)resume = resume_copy# The connected trainer asks Accelerate/TensorBoard to write directly to# output/logs/train. Create it up front because its writer does not always# create the nested directory on Windows.(output / "logs" / "train").mkdir(parents=True, exist_ok=True)stop_file = output / ".adam_stop_training.flag"command = [sys.executable, str(script), "--train_data_dir", str(training_dataset), "--output_dir", str(output),"--model_name", model_name, "--resolution", str(int(resolution)), "--train_batch_size", str(int(batch_size)),"--resolution_width", str(canvas_width), "--resolution_height", str(canvas_height), "--resize_mode", resize_mode,"--num_epochs", str(int(epochs)), "--learning_rate", str(float(learning_rate)), "--mixed_precision", mixed_precision,"--ddpm_beta_schedule", "linear", "--tf32", "true", "--save_images_epochs", str(int(preview_every) if preview_enabled else int(epochs) + 1),"--save_model_epochs", str(int(save_every)), "--training_intensity", str(int(training_intensity)), "--dataloader_num_workers", str(int(dataloader_num_workers)),8 unmodified linescommand.extend(["--resume_completed_epochs", str(int(completed_epochs))])if pretrained_model:command.extend(["--pretrained_model_path", str(pretrained_model)])context.log(f"Starting real DDPM training with {image_count} images from {training_dataset} on a {canvas_width}x{canvas_height} "f"{resize_mode} canvas, batch {batch_size}, lr {learning_rate}.")context.log(f"Output folder: {output}")process = subprocess.Popen(command, cwd=str(trainer_root), stdout=subprocess.PIPE, stderr=subprocess.STDOUT,text=True, encoding="utf-8", errors="replace", shell=False)97 unmodified lines}],}def _stage_context(context: ToolContext, *, stage_index: int, stage_count: int) -> ToolContext:"""Map one stage's progress into the single job progress bar."""def report(percent: int, message: str, **details: object) -> None:overall = round(((stage_index + max(0, min(percent, 100)) / 100) / stage_count) * 100)context.progress(overall,f"Stage {stage_index + 1}/{stage_count} · {message}",**details,)return ToolContext(root=context.root, job_id=context.job_id, tool=context.tool,cancel_event=context.cancel_event, run_event=context.run_event,progress_callback=report, log_callback=context.log_callback,preview_callback=context.preview_callback,# A settings-change request currently restarts a single DDPM process.# Keep a curriculum stage atomic until that recovery path understands# its stage manifest.adjustment_event=None, adjustment_request=None, step_delay=context.step_delay,)def _stage_output(root: Path, stage_number: int, resolution: int) -> Path:base = root / f"stage-{stage_number:02d}-{resolution}px"if not base.exists():return baseattempt = 2while (candidate := root / f"{base.name}-retry-{attempt}").exists():attempt += 1return candidatedef train_ddpm(context: ToolContext,dataset_dir: str,model_name: str,epochs: int,output_dir: str,resume_from: str = "",resolution: int = 128, batch_size: int = 1, learning_rate: float = 0.0001,gradient_accumulation_steps: int = 1, dataloader_num_workers: int = 4,mixed_precision: str = "fp16", save_every: int = 10, preview_steps: int = 50,training_intensity: int = 100, preview_enabled: bool = True,preview_every: int = 5, preview_prompt: str = "", preview_seed: int = 123456789,completed_epochs: int = 0,training_aspect_ratio: str = "Dataset (Auto)", resize_mode: str = "fit",progressive_stages: list[dict[str, object]] | None = None,progressive_auto_batch: bool = True,) -> dict[str, object]:"""Train once, or run a low-to-high resolution DDPM curriculum.Every completed stage is retained in a hidden sibling folder. The publicoutput folder is created only after the final pipeline has completed, so apartial curriculum can never replace a usable completed model."""if not progressive_stages:return _train_ddpm_stage(context, dataset_dir, model_name, epochs, output_dir, resume_from,resolution, batch_size, learning_rate, gradient_accumulation_steps,dataloader_num_workers, mixed_precision, save_every, preview_steps,training_intensity, preview_enabled, preview_every, preview_prompt,preview_seed, completed_epochs, training_aspect_ratio, resize_mode,)stages = parse_stages(progressive_stages, trainer="ddpm", total_epochs=epochs)public_output = Path(output_dir).expanduser().resolve()if public_output.exists():raise ToolExecutionError("The chosen DDPM output folder already exists; ADAM will not overwrite it.")stage_root = public_output.parent / f".{public_output.name}.progressive"state_path = stage_root / "progressive_state.json"stage_root.mkdir(parents=True, exist_ok=True)try:state = json.loads(state_path.read_text(encoding="utf-8"))except (OSError, json.JSONDecodeError):state = {"model_name": model_name, "stages": [], "completed": []}completed = state.get("completed", []) if isinstance(state.get("completed"), list) else []completed_by_index = {int(item.get("index")): Path(str(item.get("output")))for item in completed if isinstance(item, dict) and str(item.get("index", "")).isdigit()}final_resolution = stages[-1].resolutionprior_model = resume_fromfinal_result: dict[str, object] | None = Nonecontext.log("Progressive DDPM schedule: " + stage_summary(stages) + ". "+ ("Auto batch caps are enabled." if progressive_auto_batch else "Using the same batch settings at every stage."))for index, stage in enumerate(stages):completed_output = completed_by_index.get(index)if completed_output and completed_output.is_dir():prior_model = str(completed_output)context.log(f"Stage {index + 1}/{len(stages)} already completed; using its saved weights.")continuestage_output = _stage_output(stage_root, index + 1, stage.resolution)stage_batch, stage_accumulation = stage_batch_settings(trainer="ddpm", stage_resolution=stage.resolution, final_resolution=final_resolution,final_batch_size=batch_size, base_accumulation=gradient_accumulation_steps,auto_batch=bool(progressive_auto_batch),)context.log(f"Stage {index + 1}/{len(stages)}: {stage.resolution}px for {stage.epochs} epochs; "f"batch {stage_batch}, gradient accumulation {stage_accumulation}.")result = _train_ddpm_stage(_stage_context(context, stage_index=index, stage_count=len(stages)),dataset_dir, model_name, stage.epochs, str(stage_output), prior_model,stage.resolution, stage_batch, learning_rate, stage_accumulation,dataloader_num_workers, mixed_precision, min(save_every, stage.epochs), preview_steps,training_intensity, preview_enabled, min(preview_every, stage.epochs), preview_prompt,preview_seed, 0, training_aspect_ratio, resize_mode,)prior_model = str(stage_output)final_result = resultcompleted.append({"index": index, "resolution": stage.resolution, "epochs": stage.epochs, "output": prior_model})state.update({"stages": [{"resolution": item.resolution, "epochs": item.epochs} for item in stages], "completed": completed})state_path.write_text(json.dumps(state, indent=2), encoding="utf-8")if not prior_model or not Path(prior_model).is_dir():raise ToolExecutionError("Progressive DDPM training did not produce a final stage model.")shutil.move(prior_model, public_output)final_checkpoint = sorted(public_output.glob("checkpoint-*"),key=lambda path: int(path.name.rsplit("-", 1)[-1])if path.name.rsplit("-", 1)[-1].isdigit() else -1,)[-1:]checkpoint = str(final_checkpoint[0]) if final_checkpoint else ""context.progress(100, "Progressive DDPM training completed")return {"output_folder": str(public_output), "model_name": model_name,"progressive_stages": [{"resolution": stage.resolution, "epochs": stage.epochs} for stage in stages],"assets": [{"kind": "model", "name": model_name, "path": str(public_output), "trainer": "ddpm","dataset_path": str(Path(dataset_dir).expanduser().resolve()), "checkpoint": checkpoint,"epochs": sum(stage.epochs for stage in stages),}],}
7 unmodified lines89101112131415161711 unmodified lines2930313233343540 unmodified lines76777879808182838474 unmodified lines1591601617 unmodified linesimport sysimport threadingimport timefrom pathlib import Pathfrom adam.config import ConfigManagerfrom adam.executor import ToolCancelled, ToolContext, ToolExecutionErrorfrom adam.process_control import set_process_tree_paused, terminate_process_tree11 unmodified linesreturn Nonedef train_flow(context: ToolContext,dataset_dir: str,model_name: str,40 unmodified linessaved_resolution = int(metadata.get("resolution", 0) or 0)except (OSError, ValueError, TypeError, json.JSONDecodeError) as exc:raise ToolExecutionError("Choose a valid completed Flow Matching model to continue.") from excif saved_resolution != int(resolution):raise ToolExecutionError(f"The selected Flow model is {saved_resolution}px; continuation must use the same resolution.")output.parent.mkdir(parents=True, exist_ok=True)command = [74 unmodified lines"kind": "model", "name": safe_name, "path": str(output), "trainer": "flow","dataset_path": str(dataset), "checkpoint": str(output), "epochs": int(epochs),}]}7 unmodified lines891011121314151617181911 unmodified lines3132333435363740 unmodified lines787980818283848586878874 unmodified lines1631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752767 unmodified linesimport sysimport threadingimport timeimport shutilfrom pathlib import Pathfrom adam.config import ConfigManagerfrom adam.executor import ToolCancelled, ToolContext, ToolExecutionErrorfrom adam.progressive_training import parse_stages, stage_batch_settings, stage_summaryfrom adam.process_control import set_process_tree_paused, terminate_process_tree11 unmodified linesreturn Nonedef _train_flow_stage(context: ToolContext,dataset_dir: str,model_name: str,40 unmodified linessaved_resolution = int(metadata.get("resolution", 0) or 0)except (OSError, ValueError, TypeError, json.JSONDecodeError) as exc:raise ToolExecutionError("Choose a valid completed Flow Matching model to continue.") from excif saved_resolution and saved_resolution != int(resolution):context.log("Resolution-change fine-tune: loading "f"{saved_resolution}px Flow weights for training at {int(resolution)}px. ""Optimizer state will start fresh.")output.parent.mkdir(parents=True, exist_ok=True)command = [74 unmodified lines"kind": "model", "name": safe_name, "path": str(output), "trainer": "flow","dataset_path": str(dataset), "checkpoint": str(output), "epochs": int(epochs),}]}def _stage_context(context: ToolContext, *, stage_index: int, stage_count: int) -> ToolContext:def report(percent: int, message: str, **details: object) -> None:overall = round(((stage_index + max(0, min(percent, 100)) / 100) / stage_count) * 100)context.progress(overall, f"Stage {stage_index + 1}/{stage_count} · {message}", **details)return ToolContext(root=context.root, job_id=context.job_id, tool=context.tool,cancel_event=context.cancel_event, run_event=context.run_event,progress_callback=report, log_callback=context.log_callback,preview_callback=context.preview_callback, step_delay=context.step_delay,)def _stage_output(root: Path, stage_number: int, resolution: int) -> Path:base = root / f"stage-{stage_number:02d}-{resolution}px"if not base.exists():return baseattempt = 2while (candidate := root / f"{base.name}-retry-{attempt}").exists():attempt += 1return candidatedef train_flow(context: ToolContext,dataset_dir: str,model_name: str,epochs: int,output_dir: str,resume_from: str = "",resolution: int = 256, batch_size: int = 8, learning_rate: float = 0.0002,gradient_accumulation: int = 1, workers: int = 4, mixed_precision: str = "fp16",save_every: int = 10, preview_every: int = 10, preview_steps: int = 10,gradient_checkpointing: bool = False, preview_enabled: bool = True,preview_prompt: str = "", preview_seed: int = 123456789,progressive_stages: list[dict[str, object]] | None = None,progressive_auto_batch: bool = True,) -> dict[str, object]:"""Train one Flow model or carry it through a saved resolution curriculum."""if not progressive_stages:return _train_flow_stage(context, dataset_dir, model_name, epochs, output_dir, resume_from, resolution,batch_size, learning_rate, gradient_accumulation, workers, mixed_precision,save_every, preview_every, preview_steps, gradient_checkpointing,preview_enabled, preview_prompt, preview_seed,)stages = parse_stages(progressive_stages, trainer="flow", total_epochs=epochs)public_output = Path(output_dir).expanduser().resolve()if public_output.exists():raise ToolExecutionError("The chosen Flow Matching output folder already exists; ADAM will not overwrite it.")stage_root = public_output.parent / f".{public_output.name}.progressive"state_path = stage_root / "progressive_state.json"stage_root.mkdir(parents=True, exist_ok=True)try:state = json.loads(state_path.read_text(encoding="utf-8"))except (OSError, json.JSONDecodeError):state = {"model_name": model_name, "stages": [], "completed": []}completed = state.get("completed", []) if isinstance(state.get("completed"), list) else []completed_by_index = {int(item.get("index")): Path(str(item.get("output")))for item in completed if isinstance(item, dict) and str(item.get("index", "")).isdigit()}final_resolution = stages[-1].resolutionprior_model = resume_fromcontext.log("Progressive Flow Matching schedule: " + stage_summary(stages) + ". "+ ("Auto batch caps are enabled." if progressive_auto_batch else "Using the same batch settings at every stage."))for index, stage in enumerate(stages):completed_output = completed_by_index.get(index)if completed_output and completed_output.is_dir():prior_model = str(completed_output)context.log(f"Stage {index + 1}/{len(stages)} already completed; using its saved weights.")continuestage_output = _stage_output(stage_root, index + 1, stage.resolution)stage_batch, stage_accumulation = stage_batch_settings(trainer="flow", stage_resolution=stage.resolution, final_resolution=final_resolution,final_batch_size=batch_size, base_accumulation=gradient_accumulation,auto_batch=bool(progressive_auto_batch),)context.log(f"Stage {index + 1}/{len(stages)}: {stage.resolution}px for {stage.epochs} epochs; "f"batch {stage_batch}, gradient accumulation {stage_accumulation}.")_train_flow_stage(_stage_context(context, stage_index=index, stage_count=len(stages)),dataset_dir, model_name, stage.epochs, str(stage_output), prior_model,stage.resolution, stage_batch, learning_rate, stage_accumulation, workers,mixed_precision, min(save_every, stage.epochs), min(preview_every, stage.epochs),preview_steps, gradient_checkpointing or stage.resolution >= 384,preview_enabled, preview_prompt, preview_seed,)prior_model = str(stage_output)completed.append({"index": index, "resolution": stage.resolution, "epochs": stage.epochs, "output": prior_model})state.update({"stages": [{"resolution": item.resolution, "epochs": item.epochs} for item in stages], "completed": completed})state_path.write_text(json.dumps(state, indent=2), encoding="utf-8")if not prior_model or not Path(prior_model).is_dir():raise ToolExecutionError("Progressive Flow Matching training did not produce a final stage model.")shutil.move(prior_model, public_output)context.progress(100, "Progressive Flow Matching training completed")return {"output_folder": str(public_output), "model_name": model_name,"progressive_stages": [{"resolution": stage.resolution, "epochs": stage.epochs} for stage in stages],"assets": [{"kind": "model", "name": model_name, "path": str(public_output), "trainer": "flow","dataset_path": str(Path(dataset_dir).expanduser().resolve()), "checkpoint": str(public_output),"epochs": sum(stage.epochs for stage in stages),}],}
66 unmodified lines67686970717269 unmodified lines14214314414514614751 unmodified lines19920020120220320457 unmodified lines26226326426526626766 unmodified linesseed: int,sampler: str,aspect_ratio: str,preview_interval: int = 0,smart_generation: bool = False,smart_wanted_results: int = 0,69 unmodified lines}if aspect_ratio not in allowed_aspects:raise ToolExecutionError("Choose one of the supported Flow aspect ratios.")if len(prompt) > 500:raise ToolExecutionError("The generation label must be 500 characters or shorter.")if not 0 <= int(preview_interval) <= step_count:51 unmodified linestry:settings = {"aspect_ratio": aspect_ratio}if preview_enabled and preview_supported:settings["preview_interval"] = int(preview_interval)settings["preview_callback"] = lambda payload, step=0, total_steps=step_count, current=index: publish_generation_preview(57 unmodified lines"steps": step_count,"sampler": method,"aspect_ratio": aspect_ratio,"preview_interval": int(preview_interval),"preview_supported": preview_supported,"images": ordered_images if smart_keep_rejected or not smart_enabled else selected_paths,66 unmodified lines676869707172737469 unmodified lines14414514614714814915015115215315415515615715815916016116251 unmodified lines21421521621721821922022157 unmodified lines27928028128228328428528666 unmodified linesseed: int,sampler: str,aspect_ratio: str,width: int = 0,height: int = 0,preview_interval: int = 0,smart_generation: bool = False,smart_wanted_results: int = 0,69 unmodified lines}if aspect_ratio not in allowed_aspects:raise ToolExecutionError("Choose one of the supported Flow aspect ratios.")custom_width = int(width or 0)custom_height = int(height or 0)if bool(custom_width) != bool(custom_height):raise ToolExecutionError("Set both Flow image width and height, or leave both unset.")if custom_width and (not 64 <= custom_width <= 2048or not 64 <= custom_height <= 2048or custom_width % 16or custom_height % 16):raise ToolExecutionError("Flow image width and height must each be between 64 and 2048 pixels and divisible by 16.")if len(prompt) > 500:raise ToolExecutionError("The generation label must be 500 characters or shorter.")if not 0 <= int(preview_interval) <= step_count:51 unmodified linestry:settings = {"aspect_ratio": aspect_ratio}if custom_width:settings.update({"width": custom_width, "height": custom_height})if preview_enabled and preview_supported:settings["preview_interval"] = int(preview_interval)settings["preview_callback"] = lambda payload, step=0, total_steps=step_count, current=index: publish_generation_preview(57 unmodified lines"steps": step_count,"sampler": method,"aspect_ratio": aspect_ratio,"width": custom_width,"height": custom_height,"preview_interval": int(preview_interval),"preview_supported": preview_supported,"images": ordered_images if smart_keep_rejected or not smart_enabled else selected_paths,
256 unmodified lines257258259260261262263256 unmodified lines"trigger_word": trigger,"epochs": int(epochs),"settings": settings,"training_overrides": training_overrides,}mp_context = multiprocessing.get_context("spawn")events = mp_context.Queue()256 unmodified lines257258259260261262263264265266267268269270256 unmodified lines"trigger_word": trigger,"epochs": int(epochs),"settings": settings,# ``preview_prompt`` is a named argument, so Python removes it from# ``training_overrides``. Explicitly include it here so a new ADAM# run cannot inherit the connected trainer's last saved prompt."training_overrides": {**training_overrides,"preview_prompt": str(preview_prompt),"preview_interval_epochs": max(1, int(preview_every)),},}mp_context = multiprocessing.get_context("spawn")events = mp_context.Queue()
2 unmodified lines34567891011121312 unmodified lines26272829303163 unmodified lines95969798991001019 unmodified lines11111211311411511611726 unmodified lines1441451461471481491501511521531541551561571581591601611621631642 unmodified linesfrom __future__ import annotationsimport jsonimport randomimport reimport sysfrom datetime import datetime, timezonefrom pathlib import Pathfrom adam.config import ConfigManagerfrom adam.executor import ToolCancelled, ToolContext, ToolExecutionError12 unmodified lines}def _safe_label(value: str) -> str:label = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', " ", value.strip()[:96] or "LoRA")return re.sub(r"\s+", " ", label).strip(" .") or "LoRA"63 unmodified linesraise ToolExecutionError("Image count must be between 1 and 48.")if not 1 <= step_count <= 150:raise ToolExecutionError("LoRA generation steps must be between 1 and 150.")if sampler not in {"DPM++ 2M", "DPM++ SDE", "Euler", "Euler a", "DDIM"}:raise ToolExecutionError("Choose one of the supported LoRA samplers.")if aspect_ratio not in ASPECT_SIZES:raise ToolExecutionError("Choose one of the supported LoRA aspect ratios.")9 unmodified linessys.path.insert(0, str(source_root))try:from loratrainer.models.generation_config import GenerationConfigfrom loratrainer.trainer.diffusers_sdxl_generator import DiffusersSDXLGeneratorBackendexcept Exception as exc:raise ToolExecutionError(f"Could not load the LoRA Trainer generator: {exc}") from exc26 unmodified linesprompt_weighting=bool(prompt_weighting),)def progress(update) -> None:context.checkpoint()current = max(0, int(getattr(update, "current_image", 0)))context.progress(min(99, max(1, round(current * 100 / count))), str(getattr(update, "message", "Generating with LoRA")))if int(preview_interval) > 0:payload = getattr(update, "preview", None) or getattr(update, "preview_path", None)if payload:publish_generation_preview(context, output, payload, image_index=max(0, current - 1), image_count=count,step=int(getattr(update, "step", getattr(update, "current_step", 0)) or 0),total_steps=step_count,)try:paths = DiffusersSDXLGeneratorBackend().generate(request, progress)except ToolCancelled:raiseexcept Exception as exc:2 unmodified lines34567891011121314151612 unmodified lines293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114263 unmodified lines2062072082092102112129 unmodified lines22222322422522622726 unmodified lines2542552562572582592602612622632 unmodified linesfrom __future__ import annotationsimport jsonimport multiprocessingimport queueimport randomimport reimport sysfrom datetime import datetime, timezonefrom pathlib import Pathfrom typing import Anyfrom adam.config import ConfigManagerfrom adam.executor import ToolCancelled, ToolContext, ToolExecutionError12 unmodified lines}def _run_lora_generation_worker(payload: dict[str, Any], events: Any) -> None:"""Run SDXL inference outside ADAM's long-lived desktop process.Diffusers owns CUDA allocations below Python's normal object lifecycle.Keeping each LoRA batch in a spawned worker gives queued requests the sameclean CUDA context as the connected LoRA Trainer application."""try:source_root = str(payload["source_root"])if source_root not in sys.path:sys.path.insert(0, source_root)from loratrainer.models.generation_config import GenerationConfigfrom loratrainer.trainer.diffusers_sdxl_generator import DiffusersSDXLGeneratorBackendrequest = GenerationConfig(base_model_path=Path(str(payload["base_model_path"])),output_dir=Path(str(payload["output_dir"])),positive_prompt=str(payload["positive_prompt"]),negative_prompt=str(payload["negative_prompt"]),lora_path=Path(str(payload["lora_path"])) if payload.get("lora_path") else None,reference_image=Path(str(payload["reference_image"])) if payload.get("reference_image") else None,width=int(payload["width"]), height=int(payload["height"]),steps=int(payload["steps"]), cfg_scale=float(payload["cfg_scale"]),seed=int(payload["seed"]), sampler=str(payload["sampler"]),batch_count=int(payload["batch_count"]), lora_strength=float(payload["lora_strength"]),denoise_strength=float(payload["denoise_strength"]),prompt_weighting=bool(payload["prompt_weighting"]),)def progress(update: Any) -> None:events.put({"type": "progress", "current_image": int(getattr(update, "current_image", 0) or 0),"message": str(getattr(update, "message", "Generating with LoRA") or "Generating with LoRA"),"preview": getattr(update, "preview", None) or getattr(update, "preview_path", None),"step": int(getattr(update, "step", getattr(update, "current_step", 0)) or 0),})paths = DiffusersSDXLGeneratorBackend().generate(request, progress)events.put({"type": "result", "paths": [str(path) for path in paths]})except Exception as exc:events.put({"type": "error", "message": str(exc), "exception": type(exc).__name__})def _generate_in_isolated_process(context: ToolContext, source_root: Path, request: Any, output: Path,count: int, step_count: int, preview_interval: int,) -> list[Path]:"""Generate a batch in a short-lived CUDA process and relay its progress."""payload = {"source_root": str(source_root), "base_model_path": str(request.base_model_path),"output_dir": str(request.output_dir), "positive_prompt": request.positive_prompt,"negative_prompt": request.negative_prompt, "lora_path": str(request.lora_path or ""),"reference_image": str(request.reference_image or ""), "width": request.width,"height": request.height, "steps": request.steps, "cfg_scale": request.cfg_scale,"seed": request.seed, "sampler": request.sampler, "batch_count": request.batch_count,"lora_strength": request.lora_strength, "denoise_strength": request.denoise_strength,"prompt_weighting": request.prompt_weighting,}worker_context = multiprocessing.get_context("spawn")events = worker_context.Queue()process = worker_context.Process(target=_run_lora_generation_worker, args=(payload, events))process.start()result: list[Path] | None = Noneerror = ""try:while True:if context.cancel_event.is_set():process.terminate()process.join(timeout=3)raise ToolCancelled("Job cancelled by user.")try:event = events.get(timeout=0.1)except queue.Empty:if not process.is_alive():breakcontinueif event.get("type") == "progress":current = max(0, int(event.get("current_image", 0)))context.progress(min(99, max(1, round(current * 100 / count))),str(event.get("message", "Generating with LoRA")),)preview = event.get("preview")if int(preview_interval) > 0 and preview:publish_generation_preview(context, output, preview, image_index=max(0, current - 1), image_count=count,step=int(event.get("step", 0)), total_steps=step_count,)elif event.get("type") == "result":result = [Path(str(path)) for path in event.get("paths", [])]elif event.get("type") == "error":error = str(event.get("message") or "Unknown worker error")process.join(timeout=3)finally:if process.is_alive():process.terminate()process.join(timeout=3)events.close()events.join_thread()if error:raise ToolExecutionError(f"LoRA generation failed: {error}")if result is None:raise ToolExecutionError(f"LoRA generation worker exited without returning images (exit code {process.exitcode}).")return resultdef _safe_label(value: str) -> str:label = re.sub(r'[<>:"/\\|?*\x00-\x1f]+', " ", value.strip()[:96] or "LoRA")return re.sub(r"\s+", " ", label).strip(" .") or "LoRA"63 unmodified linesraise ToolExecutionError("Image count must be between 1 and 48.")if not 1 <= step_count <= 150:raise ToolExecutionError("LoRA generation steps must be between 1 and 150.")if sampler not in {"DPM++ 2M", "DPM++ 2M Karras", "DPM++ 2M SDE", "DPM++ 2M SDE Karras", "DPM++ SDE", "DPM++ SDE Karras", "Euler", "Euler a", "Heun", "LMS", "DDIM"}:raise ToolExecutionError("Choose one of the supported LoRA samplers.")if aspect_ratio not in ASPECT_SIZES:raise ToolExecutionError("Choose one of the supported LoRA aspect ratios.")9 unmodified linessys.path.insert(0, str(source_root))try:from loratrainer.models.generation_config import GenerationConfigexcept Exception as exc:raise ToolExecutionError(f"Could not load the LoRA Trainer generator: {exc}") from exc26 unmodified linesprompt_weighting=bool(prompt_weighting),)try:paths = _generate_in_isolated_process(context, source_root, request, output, count, step_count, int(preview_interval),)except ToolCancelled:raiseexcept Exception as exc:
.gitattributes+1
ADAM-source-2026-10-01.zipAdded+3
ADAM.spec+1
README.md+591-394
SHA256SUMS.txtAdded+1
adam/assets.py+72-20
adam/auto_training.pyAdded+109
adam/cnn_reviewer.pyAdded+172
adam/commands.py+1-1
adam/config.py+3
adam/dataset_registry.py+4-3
adam/generations.py+334-14
adam/intelligence.pyAdded+200
adam/job_manager.py+18-3
adam/model_plugins.py+3-1
adam/model_plugins_builtin/ddpm/manifest.py+3-1
adam/model_plugins_builtin/flow_matching/manifest.py+2
adam/model_plugins_builtin/inrflow/__init__.pyAdded+2
adam/model_plugins_builtin/inrflow/common.pyAdded+106
adam/model_plugins_builtin/inrflow/generator.pyAdded+305
adam/model_plugins_builtin/inrflow/manifest.pyAdded+394
adam/model_plugins_builtin/inrflow/model.pyAdded+400
adam/model_plugins_builtin/inrflow/trainer.pyAdded+523
adam/model_plugins_builtin/oasis/manifest.py+24-9
adam/model_plugins_builtin/pixelrow/__init__.pyAdded+2
adam/model_plugins_builtin/pixelrow/common.pyAdded+86
adam/model_plugins_builtin/pixelrow/generator.pyAdded+212
adam/model_plugins_builtin/pixelrow/manifest.pyAdded+301
adam/model_plugins_builtin/pixelrow/model.pyAdded+244
adam/model_plugins_builtin/pixelrow/trainer.pyAdded+411
adam/model_plugins_builtin/sdxl_lora/manifest.py+1-1
adam/model_plugins_builtin/wan_video/__init__.pyAdded+1
adam/model_plugins_builtin/wan_video/manifest.pyAdded+50
adam/nova.py+2
adam/oasis_dataset.py+94-15
adam/oasis_player.pyAdded+112
adam/ollama.py+56-7
adam/orion.py+85
adam/planner.py+254-21
adam/progressive_training.pyAdded+103
adam/recommendations.py+113-15
adam/remote_access.py+25-4
adam/remote_dashboard.py+22-13
adam/remote_v1.py+53-35
adam/tool_folders.py+5
adam/tools/ddpm_adapter.py+244-28
adam/tools/flow_adapter.py+119-4
adam/tools/flow_generator.py+19
adam/tools/lora_adapter.py+8-1
adam/tools/lora_generator.py+115-16