The platform for continuously improving AI agents.
Remove Baseten and Together AI (#341)
Freyam Mehtad0bbf7a7e0d3
diff --git a/.agents/skills/backend-architecture/SKILL.md b/.agents/skills/backend-architecture/SKILL.mdindex 03c46b4e..ead7c7f8 100644--- a/.agents/skills/backend-architecture/SKILL.md+++ b/.agents/skills/backend-architecture/SKILL.md@@ -15,7 +15,7 @@ Single Django app `overbae`, project-scoped tenancy.- `services/` — business logic. Largest subtrees: `datasets/` (Data Workshop; data-workshop skill), `mcp/` (mcp skill), `connectors/`, `sft_assets/` (training code baked into the Modal image), `codebase/`.- `tasks/` — Celery tasks, roughly one module per feature; `utils/task_lock.py` for locking.- `modal/` — Modal app entrypoints (vLLM serving, SFT, native decision evaluation and serving) and `models.json`. Code shared by those workers and the API lives in the root `modal_shared/` package.-- `management/commands/` — `seed_demo` (seed-demo-data skill), `grant_credits`, `sync_baseten_finetuning_costs`.+- `management/commands/` — `seed_demo` (seed-demo-data skill), `grant_credits`.## Patterns every subsystem followsdiff --git a/.agents/skills/finetuning-model-onboarding/SKILL.md b/.agents/skills/finetuning-model-onboarding/SKILL.mdindex 617ccbf2..447531c1 100644--- a/.agents/skills/finetuning-model-onboarding/SKILL.md+++ b/.agents/skills/finetuning-model-onboarding/SKILL.md@@ -66,7 +66,7 @@ For every new model, before it's usable for finetuning:- `validated_context_length: true` once probed — this flag means "this number came from an actual training run on H100/H200," not an assumption.1. Set `finetuning.real_max_context_length` to the max across validated training types, and keep every `training_type.*.context_length <= real_max_context_length`.-`tests/test_modelfam.py::test_baseten_real_max_context_length` enforces this shape for every `backend: "baseten"` entry — run it before considering onboarding done.+`tests/test_modelfam.py::test_modal_real_max_context_length` enforces this shape for every `backend: "modal"` entry — run it before considering onboarding done.## 5. Everything model-specific goes in `models.json`@@ -76,12 +76,11 @@ Model configuration — context lengths, batch sizes, training type enablement,Actual training cost is **computed, not stored per model** — `overbae/services/finetuning_pricing.py` derives it from fields already in `models.json`:-- Modal (the only backend settings allow): `estimate_training_cost()` picks GPU count from `_BASETEN_GPU_COUNT_TIERS` keyed on `total_params_b`, estimates duration from FLOPs (`6·N·D` full / `4·N·D` LoRA at 35% assumed MFU) plus a fixed 10-minute overhead, and bills GPU count × seconds × `_MODAL_H100_USD_PER_SECOND`.-- The Baseten (per-minute) and Together (`training_price_per_million()`, `_TOGETHER_SFT_TIERS`) branches remain for catalog entries on those backends.+- Modal (the only backend settings allow): `estimate_training_cost()` picks GPU count from `_GPU_COUNT_TIERS` keyed on `total_params_b`, estimates duration from FLOPs (`6·N·D` full / `4·N·D` LoRA at 35% assumed MFU) plus a fixed 10-minute overhead, and bills GPU count × seconds × `_MODAL_H100_USD_PER_SECOND`.-So as long as the new model's `total_params_b` is set correctly in `models.json`, cost estimation works automatically — don't add a new pricing branch or per-model rate to `finetuning_pricing.py`. It returns `None` for an unpriced backend, for zero trained tokens, and for a >100B-param Together model, which needs an individually negotiated rate.+So as long as the new model's `total_params_b` is set correctly in `models.json`, cost estimation works automatically — don't add a new pricing branch or per-model rate to `finetuning_pricing.py`. It returns `None` for an unpriced backend and for zero trained tokens.-The one thing to add by hand is the **marketing "from" floor**: `models.json`'s `pricing.train_from_usd` (paired with `pricing.run_from_usd_per_1m_output` — `model_library.py`'s `_pricing()` drops the whole block from the API response unless both are set). This is a display-only number for the model library UI, not read by the cost estimator. Set it by calling `estimate_training_run()`/`estimate_training_cost()` for a small representative dataset on the new model and rounding to a customer-facing number consistent with similarly-sized peer models already in the catalog (e.g. dense ~1-4B models cluster around `0.5–0.7`, larger dense/MoE tiers step up to `1.0–2.5`, frontier-scale up to `4.5–5.0`).+The one thing to add by hand is the **"from" price**: `models.json`'s `pricing.train_from_usd` (paired with `pricing.run_from_usd_per_1m_output` — `model_library.py`'s `_pricing()` drops the whole block from the API response unless both are set). This is a display-only number for the model library UI, not read by the cost estimator. It is at cost, with no markup: set it from `estimate_training_cost()` for a small representative LoRA run on the new model, to two decimals, consistent with similarly-sized peer models already in the catalog (e.g. dense ~1-4B models sit around `0.30–0.43`, larger dense/MoE tiers `0.61–1.52`, frontier-scale `2.73–3.04`).## 7. New `ModelFamily` needs a frontend icon@@ -110,7 +109,7 @@ A catalog row that only trains is unfinished. Serving is measured on Modal `--en- [ ] Context probed per training type, H100 before H200, with real Modal runs- [ ] `training_type.{full,lora}.context_length` + `validated_context_length` set from actual probe results- [ ] `real_max_context_length` set and consistent with validated training types-- [ ] `tests/test_modelfam.py` passes, including `test_baseten_real_max_context_length`+- [ ] `tests/test_modelfam.py` passes, including `test_modal_real_max_context_length`- [ ] `total_params_b` set correctly (drives auto-computed training cost — no manual rate needed)- [ ] `pricing.train_from_usd` + `pricing.run_from_usd_per_1m_output` set for the model library display- [ ] Frontend icon mapped if the family is newdiff --git a/.env.example b/.env.exampleindex bf38b691..a583203b 100644--- a/.env.example+++ b/.env.example@@ -105,8 +105,6 @@ SALES_DASHBOARD_TOKEN=HF_TOKEN=# Finetuning-BASETEN_API_KEY=-BASETEN_PROJECT=FINETUNING_BACKEND=modal# Modal tokens: https://modal.com/settings/tokens. INFERENCE_API_URL is printed@@ -118,9 +116,7 @@ MODAL_ENVIRONMENT=overmind-devMODAL_TOKEN_ID=MODAL_TOKEN_SECRET=-TOGETHER_API_KEY=--# Fine-tuning checkpoint S3 archive (baseten/modal providers) — durable home+# Fine-tuning checkpoint S3 archive — durable home# for checkpoint.zip/job_logs.txt/metrics.json, see# overbae/modal/register_model.py's sync_*_to_s3. Django reads these for# presigned download URLs. Same keys must also be on the "overmind-inference"diff --git a/Makefile b/Makefileindex c20ca4c0..00e969f7 100644--- a/Makefile+++ b/Makefile@@ -10,7 +10,7 @@ install-hooks:# Data Workshop scripts need `make sandbox` running and SANDBOX_URL=http://127.0.0.1:8080# with the same SANDBOX_TOKEN in .env.worker:- OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES TOGETHER_API_KEY=placeholder-local-dev \+ OBJC_DISABLE_INITIALIZE_FORK_SAFETY=YES \uv run celery -A overbae worker -l info --pool=solo -n local@%h \-Q control,io,assistant,io_traces,batch,landing,interactivediff --git a/SECURITY.md b/SECURITY.mdindex a980ed87..df37842e 100644--- a/SECURITY.md+++ b/SECURITY.md@@ -14,7 +14,7 @@ Include the affected component (API, Console, SDK, MCP server), steps to reprodu- This repository: the API (`overbae/`), the Console (`frontend/`), the SDK and CLI (`overmind/`, published to PyPI as `overmind`), and the MCP server at `/api/mcp/`.- The hosted service at `console.overmindlab.ai` and `api.overmindlab.ai`.-Third-party services the platform integrates with (model providers, Modal, Baseten, Stripe, Clerk) are out of scope; report those upstream.+Third-party services the platform integrates with (model providers, Modal, Stripe, Clerk) are out of scope; report those upstream.## Supported versionsdiff --git a/docker-compose.yml b/docker-compose.ymlindex ec32c0b8..f6a910bf 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -22,7 +22,6 @@ x-env-common: &env-commonDAYTONA_API_KEY: ${DAYTONA_API_KEY:-}JEV_REQUESTS_PER_MINUTE: ${JEV_REQUESTS_PER_MINUTE:-1200}JEV_TOKENS_PER_SECOND: ${JEV_TOKENS_PER_SECOND:-250000}- TOGETHER_API_KEY: ${TOGETHER_API_KEY:-}HF_TOKEN: ${HF_TOKEN:-}INFERENCE_API_URL: ${INFERENCE_API_URL:-}INFERENCE_API_KEY: ${INFERENCE_API_KEY:-}diff --git a/docker/entrypoint.sh b/docker/entrypoint.shindex 4700dbfe..f4d37983 100755--- a/docker/entrypoint.sh+++ b/docker/entrypoint.sh@@ -3,19 +3,6 @@# Disable with RUN_DB_BOOTSTRAP=0 (e.g. production where migrate runs in CI).set -e-# Write ~/.trussrc so truss_train.push() can authenticate with Baseten.-if [ -n "${BASETEN_API_KEY}" ]; then- _HOME="${HOME:-/root}"- mkdir -p "$_HOME"- cat > "$_HOME/.trussrc" << TRUSSRC-[baseten]-remote_provider = baseten-auth_type = api_key-api_key = ${BASETEN_API_KEY}-remote_url = https://app.baseten.co-TRUSSRC-fi-if [ "${RUN_DB_BOOTSTRAP:-1}" = "1" ]; thenecho "==> migrate"python manage.py migrate --noinputdiff --git a/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx b/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsxindex 6755053f..295f746d 100644--- a/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx+++ b/frontend/src/components/finetuning/train/__tests__/use-train-wizard.test.tsx@@ -7,7 +7,7 @@ import { useTrainWizard } from "../use-train-wizard";const mocks = vi.hoisted(() => ({benchmarks: [{ baseModelId: "Qwen", finetuningJobName: "Support", modelId: "ft-trained" }],- catalog: { backend: "baseten", models: {}, tiers: [] },+ catalog: { backend: "modal", models: {}, tiers: [] },context: {data: { checks: [{ message: "Context may be too small.", status: "warning" }] },isError: false,@@ -93,7 +93,7 @@ beforeEach(() => {mocks.recommendation.candidates = [mocks.recommendation.candidates[0]];mocks.recommendation.shown = ["model"];mocks.estimateResults = [];- mocks.catalog.backend = "baseten";+ mocks.catalog.backend = "modal";mocks.overlapCount = 0;mocks.train.results[0].capability = "cap";mocks.validate.mockResolvedValue({ valid: true });@@ -111,12 +111,7 @@ const args = {projectId: "project",};-it.each([- "baseten",- "modal",- "together",-])("uses the same default %s monitoring policy for forecasting and launch", async (backend) => {- mocks.catalog.backend = backend;+it("uses the same default monitoring policy for forecasting and launch", async () => {const { result } = renderHook(() => useTrainWizard({ ...args, initialEvalDatasetId: undefined }));await waitFor(() => expect(result.current.canLaunch).toBe(true));const latest = mocks.queries.mock.calls.at(-1)![0];@@ -130,7 +125,7 @@ it.each([interval_steps: null,loss_sample: 2048,max_checks: 12,- mode: backend === "together" ? "off" : "adaptive",+ mode: "adaptive",overhead_fraction: 0.1,selection: "last",target_seconds: 300,diff --git a/frontend/src/components/finetuning/train/use-train-wizard.ts b/frontend/src/components/finetuning/train/use-train-wizard.tsindex a43363b1..091a840f 100644--- a/frontend/src/components/finetuning/train/use-train-wizard.ts+++ b/frontend/src/components/finetuning/train/use-train-wizard.ts@@ -61,14 +61,25 @@ export type EvaluationPlan = Required<>;const EMPTY_CATALOG: ModelCatalog = {- backend: BackendEnum.baseten,+ backend: BackendEnum.modal,hasToolCalling: false,- maxContext: null,models: {},monitoring: {},tiers: [...TIER_ORDER],};+const MONITORING = {+ early_stopping: null,+ interval_steps: null,+ loss_sample: 2048,+ max_checks: 12,+ mode: "adaptive",+ overhead_fraction: 0.1,+ selection: "last",+ target_seconds: 300,+ train_sample: 256,+};+const FAILED_VALIDATION: DatasetValidationResponse = {errors: ["Couldn't validate this dataset."],format: "unknown",@@ -277,20 +288,6 @@ export function useTrainWizard({(hasToolCalling ? toolCatalogQuery.data : baseCatalogQuery.data) ??baseCatalogQuery.data ??EMPTY_CATALOG;- const monitoring = useMemo(- () => ({- early_stopping: null,- interval_steps: null,- loss_sample: 2048,- max_checks: 12,- mode: catalog.backend === "together" ? "off" : "adaptive",- overhead_fraction: 0.1,- selection: "last",- target_seconds: 300,- train_sample: 256,- }),- [catalog.backend]- );// Every constraint-passing model, ranked by grade; `shown` names the opening line-up.const candidates = useMemo(() => rec?.candidates ?? [], [rec]);@@ -449,7 +446,7 @@ export function useTrainWizard({hyperparameters: {...buildHyperparameters(draft),monitoring: {- ...monitoring,+ ...MONITORING,...(nativeDecision ? { initial: preTrainingBaseline } : {}),},...(nativeDecision@@ -467,7 +464,6 @@ export function useTrainWizard({draft.hyperparams,nativeDecision,preTrainingBaseline,- monitoring,dataset?.active,validationSelection,] as const,@@ -642,7 +638,7 @@ export function useTrainWizard({hyperparameters: {...buildHyperparameters(fixed),monitoring: {- ...monitoring,+ ...MONITORING,...(nativeDecision ? { initial: preTrainingBaseline } : {}),},...(nativeDecision@@ -673,7 +669,6 @@ export function useTrainWizard({}}, [canLaunch,- monitoring,preTrainingBaseline,decisionObjective,evaluationEnabled,diff --git a/frontend/src/hooks/use-finetuning.ts b/frontend/src/hooks/use-finetuning.tsindex 79b0cda2..f0cf334a 100644--- a/frontend/src/hooks/use-finetuning.ts+++ b/frontend/src/hooks/use-finetuning.ts@@ -470,14 +470,13 @@ export const useLossCurvesQuery = (jobId: string | undefined, refetchWhileLive =export type ModelEntry = FinetuningModelCatalogEntry;export type ModelCatalog = FinetuningModelCatalogResponse;-export const useModelCatalogQuery = (hasToolCalling = false, maxContext?: number) =>+export const useModelCatalogQuery = (hasToolCalling = false) =>useQuery({gcTime: 30 * 60 * 1000,queryFn: () =>apiClient.finetuningJobs.finetuningJobsModelsRetrieve({hasToolCalling: hasToolCalling || undefined,- maxContext: maxContext ?? undefined,}),- queryKey: ["finetuning-model-catalog", hasToolCalling, maxContext ?? null],+ queryKey: ["finetuning-model-catalog", hasToolCalling],staleTime: Infinity,});diff --git a/frontend/src/openapi/apis/FinetuningJobsApi.ts b/frontend/src/openapi/apis/FinetuningJobsApi.tsindex e9695795..7f4ccf77 100644--- a/frontend/src/openapi/apis/FinetuningJobsApi.ts+++ b/frontend/src/openapi/apis/FinetuningJobsApi.ts@@ -172,7 +172,6 @@ export interface FinetuningJobsModelSwapPromptRetrieveRequest {export interface FinetuningJobsModelsRetrieveRequest {hasToolCalling?: boolean;- maxContext?: number;}export interface FinetuningJobsMonitoringEvidenceRetrieveRequest {@@ -1074,7 +1073,7 @@ export class FinetuningJobsApi extends runtime.BaseAPI {}/**- * Return the curated model catalog organised by tier. When ``FINETUNING_BACKEND`` is ``baseten``, the Baseten catalog from models.json is returned. Pass ``?has_tool_calling=true`` to receive only models that support function-calling fine-tuning. Tiers that contain no eligible models are omitted from the response.+ * Return the curated model catalog organised by tier. The catalog is the ``FINETUNING_BACKEND`` rows of models.json. Pass ``?has_tool_calling=true`` to receive only models that support function-calling fine-tuning. Tiers that contain no eligible models are omitted from the response.* List available fine-tuning models by tier*/async finetuningJobsModelsRetrieveRaw(requestParameters: FinetuningJobsModelsRetrieveRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<FinetuningModelCatalogResponse>> {@@ -1084,10 +1083,6 @@ export class FinetuningJobsApi extends runtime.BaseAPI {queryParameters['has_tool_calling'] = requestParameters['hasToolCalling'];}- if (requestParameters['maxContext'] != null) {- queryParameters['max_context'] = requestParameters['maxContext'];- }-const headerParameters: runtime.HTTPHeaders = {};if (this.configuration && this.configuration.accessToken) {@@ -1124,7 +1119,7 @@ export class FinetuningJobsApi extends runtime.BaseAPI {}/**- * Return the curated model catalog organised by tier. When ``FINETUNING_BACKEND`` is ``baseten``, the Baseten catalog from models.json is returned. Pass ``?has_tool_calling=true`` to receive only models that support function-calling fine-tuning. Tiers that contain no eligible models are omitted from the response.+ * Return the curated model catalog organised by tier. The catalog is the ``FINETUNING_BACKEND`` rows of models.json. Pass ``?has_tool_calling=true`` to receive only models that support function-calling fine-tuning. Tiers that contain no eligible models are omitted from the response.* List available fine-tuning models by tier*/async finetuningJobsModelsRetrieve(requestParameters: FinetuningJobsModelsRetrieveRequest = {}, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<FinetuningModelCatalogResponse> {@@ -1686,7 +1681,7 @@ export class FinetuningJobsApi extends runtime.BaseAPI {}/**- * Check whether a dataset\'s datapoints conform to Together AI\'s format.+ * Check whether a dataset\'s datapoints conform to the fine-tuning format.* Validate a dataset for fine-tuning*/async finetuningJobsValidateDatasetCreateRaw(requestParameters: FinetuningJobsValidateDatasetCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<DatasetValidationResponse>> {@@ -1738,7 +1733,7 @@ export class FinetuningJobsApi extends runtime.BaseAPI {}/**- * Check whether a dataset\'s datapoints conform to Together AI\'s format.+ * Check whether a dataset\'s datapoints conform to the fine-tuning format.* Validate a dataset for fine-tuning*/async finetuningJobsValidateDatasetCreate(requestParameters: FinetuningJobsValidateDatasetCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<DatasetValidationResponse> {@@ -1752,11 +1747,9 @@ export class FinetuningJobsApi extends runtime.BaseAPI {* @export*/export const FinetuningJobsEventsListProviderEnum = {- baseten: 'baseten',modal: 'modal',nebius: 'nebius',- tinker: 'tinker',- together_ai: 'together_ai'+ tinker: 'tinker'} as const;export type FinetuningJobsEventsListProviderEnum = typeof FinetuningJobsEventsListProviderEnum[keyof typeof FinetuningJobsEventsListProviderEnum];/**@@ -1779,11 +1772,9 @@ export type FinetuningJobsEventsListStatusEnum = typeof FinetuningJobsEventsList* @export*/export const FinetuningJobsListProviderEnum = {- baseten: 'baseten',modal: 'modal',nebius: 'nebius',- tinker: 'tinker',- together_ai: 'together_ai'+ tinker: 'tinker'} as const;export type FinetuningJobsListProviderEnum = typeof FinetuningJobsListProviderEnum[keyof typeof FinetuningJobsListProviderEnum];/**@@ -1844,11 +1835,9 @@ export type FinetuningJobsRunsListOrderingEnum = typeof FinetuningJobsRunsListOr* @export*/export const FinetuningJobsRunsListProviderEnum = {- baseten: 'baseten',modal: 'modal',nebius: 'nebius',- tinker: 'tinker',- together_ai: 'together_ai'+ tinker: 'tinker'} as const;export type FinetuningJobsRunsListProviderEnum = typeof FinetuningJobsRunsListProviderEnum[keyof typeof FinetuningJobsRunsListProviderEnum];/**diff --git a/frontend/src/openapi/models/BackendEnum.ts b/frontend/src/openapi/models/BackendEnum.tsindex 1793686d..d90a3824 100644--- a/frontend/src/openapi/models/BackendEnum.ts+++ b/frontend/src/openapi/models/BackendEnum.ts@@ -14,14 +14,10 @@/**- * * `together` - together- * * `baseten` - baseten* * `modal` - modal* @export*/export const BackendEnum = {- together: 'together',- baseten: 'baseten',modal: 'modal'} as const;export type BackendEnum = typeof BackendEnum[keyof typeof BackendEnum];diff --git a/frontend/src/openapi/models/FinetuningCostEstimate.ts b/frontend/src/openapi/models/FinetuningCostEstimate.tsindex 52b3d672..a2b4525c 100644--- a/frontend/src/openapi/models/FinetuningCostEstimate.ts+++ b/frontend/src/openapi/models/FinetuningCostEstimate.ts@@ -25,24 +25,12 @@ export interface FinetuningCostEstimate {* @memberof FinetuningCostEstimate*/usd: number;- /**- *- * @type {number}- * @memberof FinetuningCostEstimate- */- pricePerMillionUsd: number | null;/**** @type {number}* @memberof FinetuningCostEstimate*/trainedTokens: number;- /**- *- * @type {boolean}- * @memberof FinetuningCostEstimate- */- minimumApplied: boolean;}/**@@ -50,9 +38,7 @@ export interface FinetuningCostEstimate {*/export function instanceOfFinetuningCostEstimate(value: object): value is FinetuningCostEstimate {if (!('usd' in value) || value['usd'] === undefined) return false;- if (!('pricePerMillionUsd' in value) || value['pricePerMillionUsd'] === undefined) return false;if (!('trainedTokens' in value) || value['trainedTokens'] === undefined) return false;- if (!('minimumApplied' in value) || value['minimumApplied'] === undefined) return false;return true;}@@ -67,9 +53,7 @@ export function FinetuningCostEstimateFromJSONTyped(json: any, ignoreDiscriminatreturn {'usd': json['usd'],- 'pricePerMillionUsd': json['price_per_million_usd'],'trainedTokens': json['trained_tokens'],- 'minimumApplied': json['minimum_applied'],};}@@ -85,8 +69,6 @@ export function FinetuningCostEstimateToJSONTyped(value?: FinetuningCostEstimatereturn {'usd': value['usd'],- 'price_per_million_usd': value['pricePerMillionUsd'],'trained_tokens': value['trainedTokens'],- 'minimum_applied': value['minimumApplied'],};}diff --git a/frontend/src/openapi/models/FinetuningModelCatalogResponse.ts b/frontend/src/openapi/models/FinetuningModelCatalogResponse.tsindex 7f672df9..27aa9c48 100644--- a/frontend/src/openapi/models/FinetuningModelCatalogResponse.ts+++ b/frontend/src/openapi/models/FinetuningModelCatalogResponse.ts@@ -65,12 +65,6 @@ export interface FinetuningModelCatalogResponse {* @memberof FinetuningModelCatalogResponse*/hasToolCalling: boolean;- /**- *- * @type {number}- * @memberof FinetuningModelCatalogResponse- */- maxContext: number | null;/**** @type {any}@@ -89,7 +83,6 @@ export function instanceOfFinetuningModelCatalogResponse(value: object): value iif (!('tiers' in value) || value['tiers'] === undefined) return false;if (!('models' in value) || value['models'] === undefined) return false;if (!('hasToolCalling' in value) || value['hasToolCalling'] === undefined) return false;- if (!('maxContext' in value) || value['maxContext'] === undefined) return false;if (!('monitoring' in value) || value['monitoring'] === undefined) return false;return true;}@@ -108,7 +101,6 @@ export function FinetuningModelCatalogResponseFromJSONTyped(json: any, ignoreDis'tiers': ((json['tiers'] as Array<any>).map(TiersEnumFromJSON)),'models': json['models'],'hasToolCalling': json['has_tool_calling'],- 'maxContext': json['max_context'],'monitoring': json['monitoring'],};}@@ -128,7 +120,6 @@ export function FinetuningModelCatalogResponseToJSONTyped(value?: FinetuningMode'tiers': ((value['tiers'] as Array<any>).map(TiersEnumToJSON)),'models': value['models'],'has_tool_calling': value['hasToolCalling'],- 'max_context': value['maxContext'],'monitoring': value['monitoring'],};}diff --git a/frontend/src/openapi/models/ProviderEnum.ts b/frontend/src/openapi/models/ProviderEnum.tsindex fe634bea..31a614f4 100644--- a/frontend/src/openapi/models/ProviderEnum.ts+++ b/frontend/src/openapi/models/ProviderEnum.ts@@ -14,18 +14,14 @@/**- * * `together_ai` - Together Ai* * `nebius` - Nebius* * `tinker` - Tinker- * * `baseten` - Baseten* * `modal` - Modal* @export*/export const ProviderEnum = {- together_ai: 'together_ai',nebius: 'nebius',tinker: 'tinker',- baseten: 'baseten',modal: 'modal'} as const;export type ProviderEnum = typeof ProviderEnum[keyof typeof ProviderEnum];diff --git a/modal_shared/__init__.py b/modal_shared/__init__.pyindex 50d66dc7..aaf9f7f0 100644--- a/modal_shared/__init__.py+++ b/modal_shared/__init__.py@@ -1,4 +1,4 @@-"""Standalone package shared by Modal workers, Baseten training, and Django.+"""Standalone package shared by the Modal workers and Django.Deliberately lives OUTSIDE the ``overbae`` package: ``overbae/__init__.py``imports Celery, which configures Django settings on import. Modal entrypointdiff --git a/modal_shared/modelfam/__init__.py b/modal_shared/modelfam/__init__.pyindex 7fcb0551..b0632bde 100644--- a/modal_shared/modelfam/__init__.py+++ b/modal_shared/modelfam/__init__.py@@ -1,6 +1,6 @@"""Pure-stdlib model-family registry shared by training, serving, and Django.-No torch / django / modal imports — ships into bare Modal/Baseten containers.+No torch / django / modal imports — ships into bare Modal containers."""from modal_shared.modelfam.chat_template import (diff --git a/modal_shared/modelfam/spec.py b/modal_shared/modelfam/spec.pyindex 9f528bff..d1bdb006 100644--- a/modal_shared/modelfam/spec.py+++ b/modal_shared/modelfam/spec.py@@ -17,7 +17,7 @@ class FamilySpec:# Ordered substrings matched against lowercased model_id. First match wins# across the global registry order — put specific patterns before general ones.patterns: tuple[str, ...]- # Modal/Baseten Unsloth image key — frozen stack id in modal_shared.stacks.+ # Modal Unsloth image key — frozen stack id in modal_shared.stacks.train_image: str = "u2026_8_18"# Family default. Per-model shared-pool overrides live in serverless_engine.serve_image: str = "vllm"diff --git a/modal_shared/training_monitoring.py b/modal_shared/training_monitoring.pyindex 6b724a94..813cf9e3 100644--- a/modal_shared/training_monitoring.py+++ b/modal_shared/training_monitoring.py@@ -28,7 +28,7 @@ DEFAULT_POLICY = {def capabilities(provider):- controlled = provider in {"modal", "baseten"}+ controlled = provider == "modal"return {"schedule_modes": ["adaptive", "steps", "epoch", "off"] if controlled else ["off"],"loss_metrics": controlled,@@ -84,7 +84,7 @@ def resolve_policy(value, *, has_development, provider):if value is not None and (not isinstance(value, dict) or set(value) - DEFAULT_POLICY.keys()):raise ValueError("Unknown monitoring configuration fields")policy = {**DEFAULT_POLICY, **(value or {})}- if value is None and (not has_development or provider not in {"modal", "baseten"}):+ if value is None and (not has_development or provider != "modal"):policy["mode"] = "off"if policy["version"] != 1 or type(policy["version"]) is not int:raise ValueError("Unsupported monitoring version")@@ -192,7 +192,7 @@ def resolve_policy(value, *, has_development, provider):if policy["mode"] != "off":if not has_development:raise ValueError("Monitoring requires development data")- if provider not in {"modal", "baseten"}:+ if provider != "modal":raise ValueError("This provider does not support the requested monitoring policy")if required:if not policy["final"]:diff --git a/overbae/api/serializers.py b/overbae/api/serializers.pyindex 23f0f63c..c22eb599 100644--- a/overbae/api/serializers.py+++ b/overbae/api/serializers.py@@ -1351,7 +1351,7 @@ class FinetuningJobSerializer(serializers.ModelSerializer):def validate_hyperparameters(self, value):if not isinstance(value, dict):raise serializers.ValidationError("Use a JSON object for hyperparameters.")- if settings.FINETUNING_BACKEND in {"modal", "baseten"}:+ if settings.FINETUNING_BACKEND == "modal":try:validate_effective_batch(value)except ValueError as exc:@@ -1860,54 +1860,6 @@ class FinetuningJobSerializer(serializers.ModelSerializer):if eval_set and not eval_set.rows.filter(enabled=True).exists():raise serializers.ValidationError({"eval_set": "This eval set has no enabled rows."})- # Baseten/Modal: rows over the *selected training kind's* max fine-tuning- # context are rejected outright — MAX_LENGTH truncation would corrupt- # training targets. Check train + validation; require headroom.- if getattr(settings, "FINETUNING_BACKEND", "") == "baseten" and entry:- from overbae.modal.model_registry import context_headroom- from overbae.modal.training_type import training_context_length, training_enabled-- model_max = training_context_length(entry, training_kind_field)- headroom = context_headroom("baseten")- other_kind = "full" if training_kind_field == "lora" else "lora"- other_max = training_context_length(entry, other_kind)- other_supported = training_enabled(entry, other_kind)- for field_name, product in (- ("dataset", attrs.get("cell") or getattr(self.instance, "cell", None)),- ("validation_dataset", attrs.get("validation_cell")),- ):- if product is None or model_max is None:- continue- stats = dict(product.stats or {})- try:- max_tokens = int(stats.get("max_token_length") or 0)- except (TypeError, ValueError):- max_tokens = 0- if max_tokens and int(model_max) < max_tokens + headroom:- kind_label = "LoRA" if training_kind_field == "lora" else "full"- suggestion = ". Shorten or split the long rows, or pick a longer-context model."- if (- other_supported- and other_max is not None- and other_max >= max_tokens + headroom- ):- other_label = "full" if other_kind == "full" else "LoRA"- suggestion = f". Switch to {other_label} fine-tuning, which supports {other_max:,} tokens for this model."- raise serializers.ValidationError(- {- field_name: (- f"Longest dataset row is ≈{max_tokens:,} tokens but this model's "- f"{kind_label} fine-tuning context is {int(model_max):,} tokens"- + (- f" (need {max_tokens + headroom:,} with headroom)"- if headroom- else ""- )- + suggestion- )- }- )-return attrs@@ -1922,10 +1874,7 @@ class FinetuningGpuConfigSerializer(serializers.Serializer):class FinetuningCostEstimateSerializer(serializers.Serializer):usd = serializers.FloatField()- # Null on the self-hosted backends: they bill GPU-minutes, not tokens.- price_per_million_usd = serializers.FloatField(allow_null=True)trained_tokens = serializers.IntegerField()- minimum_applied = serializers.BooleanField()class FinetuningTimeEstimateSerializer(serializers.Serializer):@@ -2112,11 +2061,10 @@ class FinetuningModelCatalogEntrySerializer(serializers.Serializer):class FinetuningModelCatalogResponseSerializer(serializers.Serializer):"""Response of ``GET /api/finetuning-jobs/models/``."""- backend = serializers.ChoiceField(choices=["together", "baseten", "modal"])+ backend = serializers.ChoiceField(choices=["modal"])tiers = serializers.ListField(child=serializers.ChoiceField(choices=FinetuningJob.Tier.choices))models = serializers.DictField(child=FinetuningModelCatalogEntrySerializer(many=True))has_tool_calling = serializers.BooleanField()- max_context = serializers.IntegerField(allow_null=True)monitoring = serializers.JSONField()diff --git a/overbae/api/views.py b/overbae/api/views.pyindex e87fcb8e..c2fd546b 100644--- a/overbae/api/views.py+++ b/overbae/api/views.py@@ -1211,15 +1211,6 @@ class FinetuningJobViewSet(viewsets.ModelViewSet):"When true, only models that support function-calling fine-tuning are returned."),),- OpenApiParameter(- "max_context",- int,- required=False,- description=(- "Only return models whose context window is at least this many tokens. "- "Non-numeric values are ignored. Together only; ignored for Baseten."- ),- ),],responses={200: FinetuningModelCatalogResponseSerializer},)@@ -1227,26 +1218,20 @@ class FinetuningJobViewSet(viewsets.ModelViewSet):def models(self, request):"""Return the curated model catalog organised by tier.- When ``FINETUNING_BACKEND`` is ``baseten``, the Baseten catalog from- models.json is returned. Pass ``?has_tool_calling=true`` to receive- only models that support function-calling fine-tuning. Tiers that- contain no eligible models are omitted from the response.+ The catalog is the ``FINETUNING_BACKEND`` rows of models.json. Pass+ ``?has_tool_calling=true`` to receive only models that support+ function-calling fine-tuning. Tiers that contain no eligible models are+ omitted from the response."""raw = request.query_params.get("has_tool_calling", "").lower()has_tool_calling = raw in {"true", "1", "yes"}- max_context: int | None = None- raw_ctx = request.query_params.get("max_context", "")- if raw_ctx.isdigit():- max_context = int(raw_ctx)-from overbae.services.finetuning_catalog import fetch_finetuning_model_catalogreturn Response(- fetch_finetuning_model_catalog(- has_tool_calling=has_tool_calling,- max_context=max_context,- )+ FinetuningModelCatalogResponseSerializer(+ fetch_finetuning_model_catalog(has_tool_calling=has_tool_calling)+ ).data)@extend_schema(@@ -1256,7 +1241,7 @@ class FinetuningJobViewSet(viewsets.ModelViewSet):)@action(detail=False, methods=["post"], url_path="validate-dataset")def validate_dataset(self, request):- """Check whether a dataset's datapoints conform to Together AI's format."""+ """Check whether a dataset's datapoints conform to the fine-tuning format."""from overbae.services.finetuning_validator import validate_datasetbody = DatasetValidateRequestSerializer(data=request.data)diff --git a/overbae/core/llms.py b/overbae/core/llms.pyindex b1465656..d078412e 100644--- a/overbae/core/llms.py+++ b/overbae/core/llms.py@@ -43,8 +43,6 @@ from overbae.models import DeployedModellogger = logging.getLogger(__name__)-_TOGETHER_BASE_URL = "https://api.together.xyz/v1"-# Seconds per completion. The SDK default of 600s lets one hung socket read pin# a `--pool=threads` worker thread long enough to starve the queue, so this stays# well above a healthy completion but far below the default. Total retry time is@@ -75,7 +73,7 @@ class ModelSpec:fine-tunes and custom OpenAI-compatible endpoints — built from a ``ModelRef``."""- provider: str # openai | anthropic | gemini | together | custom+ provider: str # openai | anthropic | gemini | custommodel_id: strbase_url: str = ""# Env var name; secrets are never persisted.@@ -177,13 +175,6 @@ def _split_base_url(url: str) -> tuple[str, tuple[tuple[str, str], ...]]:def _model_spec_client_and_name(spec: ModelSpec) -> tuple[AsyncOpenAI, str, str]:provider = (spec.provider or "").lower()- if provider == "together":- key_env = spec.api_key_env or "TOGETHER_API_KEY"- api_key = os.environ.get(key_env)- if not api_key:- raise RuntimeError(f"{key_env} is required for Together model '{spec.model_id}'")- return _openai_compatible_client(_TOGETHER_BASE_URL, api_key), spec.model_id, provider-if provider == "custom":if not spec.base_url:raise RuntimeError(f"Custom model '{spec.model_id}' requires base_url")diff --git a/overbae/management/commands/sync_baseten_finetuning_costs.py b/overbae/management/commands/sync_baseten_finetuning_costs.pydeleted file mode 100644index cc6eeab0..00000000--- a/overbae/management/commands/sync_baseten_finetuning_costs.py+++ /dev/null@@ -1,51 +0,0 @@-from __future__ import annotations--from datetime import UTC, datetime--from django.core.management.base import BaseCommand, CommandError-from django.utils import timezone-from django.utils.dateparse import parse_datetime--from overbae.services.baseten_billing import EARLIEST_QUERYABLE, sync_finetuning_job_costs---def _parse_dt(raw: str | None, *, default: datetime) -> datetime:- if not raw:- return default- dt = parse_datetime(raw)- if dt is None:- # Allow date-only YYYY-MM-DD- try:- dt = datetime.fromisoformat(raw)- except ValueError as exc:- raise CommandError(f"Invalid datetime: {raw}") from exc- if dt.tzinfo is None:- dt = dt.replace(tzinfo=UTC)- return dt---class Command(BaseCommand):- help = "Sync Baseten training costs onto FinetuningJob rows from the billing API."-- def add_arguments(self, parser):- parser.add_argument(- "--since",- help="ISO start (default: 2026-01-01 UTC, Baseten earliest queryable date)",- )- parser.add_argument(- "--until",- help="ISO end (default: now)",- )-- def handle(self, *args, **options):- since = _parse_dt(options.get("since"), default=EARLIEST_QUERYABLE)- until = _parse_dt(options.get("until"), default=timezone.now())- if until <= since:- raise CommandError("--until must be after --since")- result = sync_finetuning_job_costs(since=since, until=until)- self.stdout.write(- self.style.SUCCESS(- f"chunks={result['chunks']} fetched={result['fetched']} "- f"matched={result['matched']} updated={result['updated']}"- )- )diff --git a/overbae/migrations/0061_retire_baseten_together.py b/overbae/migrations/0061_retire_baseten_together.pynew file mode 100644index 00000000..997fa7da--- /dev/null+++ b/overbae/migrations/0061_retire_baseten_together.py@@ -0,0 +1,41 @@+from django.db import migrations, models+++def unsubmitted_jobs_to_modal(apps, schema_editor):+ # The old default stored "baseten" until submission, so these jobs never left Modal's queue.+ FinetuningJob = apps.get_model("overbae", "FinetuningJob")+ FinetuningJob.objects.filter(+ provider="baseten", remote_job_id="", started_at__isnull=True+ ).update(provider="modal")+++class Migration(migrations.Migration):+ dependencies = [+ ("overbae", "0060_feedback_reports"),+ ]++ operations = [+ migrations.AlterField(+ model_name="finetuningjob",+ name="provider",+ field=models.CharField(+ choices=[("nebius", "Nebius"), ("tinker", "Tinker"), ("modal", "Modal")],+ default="modal",+ max_length=20,+ ),+ ),+ migrations.AlterField(+ model_name="modelref",+ name="provider",+ field=models.CharField(+ choices=[+ ("openai", "Openai"),+ ("anthropic", "Anthropic"),+ ("gemini", "Gemini"),+ ("custom", "Custom"),+ ],+ max_length=20,+ ),+ ),+ migrations.RunPython(unsubmitted_jobs_to_modal, migrations.RunPython.noop),+ ]diff --git a/overbae/modal/model_registry.py b/overbae/modal/model_registry.pyindex 567aa6b7..cbe8c192 100644--- a/overbae/modal/model_registry.py+++ b/overbae/modal/model_registry.py@@ -42,21 +42,6 @@ def library_filters() -> dict[str, Any]:return filters if isinstance(filters, dict) else {}[email protected]_cache(maxsize=1)-def _raw() -> dict[str, dict[str, Any]]:- """Together AI models only, keyed by model ID."""- return {m["id"]: m for m in _raw_all() if m.get("backend") == "together"}---def all_models() -> dict[str, dict[str, Any]]:- """Together AI models only, keyed by model ID."""- return _raw()---def get_model(together_id: str) -> dict[str, Any] | None:- return _raw().get(together_id)--def get_sft_context_length(model_id: str, *, backend: str | None = None) -> int | None:"""With ``backend`` omitted, prefers ``settings.FINETUNING_BACKEND``, then any matching entrythat has a finetuning sub-config."""@@ -64,7 +49,6 @@ def get_sft_context_length(model_id: str, *, backend: str | None = None) -> intfrom django.conf import settingsbackend = getattr(settings, "FINETUNING_BACKEND", None)- backend = _catalog_backend(backend)preferred: int | None = Nonefallback: int | None = None@@ -94,7 +78,7 @@ def get_training_context_policy(backend: str) -> dict[str, Any]:def context_headroom(backend: str) -> int:"""Training-context headroom (tokens) required above the longest dataset row.- ``0`` when the backend has no policy entry (e.g. Together)."""+ ``0`` when the backend has no policy entry."""try:return int(get_training_context_policy(backend)["context_headroom"])except (KeyError, TypeError, ValueError):@@ -114,17 +98,11 @@ def min_sft_context_length(backend: str) -> int | None:return min(contexts) if contexts else None-def _catalog_backend(backend: str | None) -> str | None:- """models.json has no ``modal`` rows — Modal trains the Baseten catalog."""- return "baseten" if backend == "modal" else backend--def _finetune_entry(model_id: str, *, backend: str | None = None) -> dict[str, Any] | None:if backend is None:from django.conf import settingsbackend = getattr(settings, "FINETUNING_BACKEND", None)- backend = _catalog_backend(backend)fallback: dict[str, Any] | None = Nonefor m in _raw_all():if m.get("id") != model_id:@@ -137,7 +115,7 @@ def _finetune_entry(model_id: str, *, backend: str | None = None) -> dict[str, Adef get_hf_base(model_id: str, *, backend: str | None = None) -> str:- """HF id for the active finetuning backend (Modal uses Baseten catalog rows)."""+ """HF id for the active finetuning backend."""cfg = _finetune_entry(model_id, backend=backend)return cfg["hf_model_id"] if cfg and cfg.get("hf_model_id") else model_id@@ -178,7 +156,7 @@ def get_tier_models(*, backend: str | None = None) -> dict[str, list[dict[str, Aif backend is None:from django.conf import settings- backend = _catalog_backend(getattr(settings, "FINETUNING_BACKEND", "baseten"))+ backend = getattr(settings, "FINETUNING_BACKEND", "modal")buckets: dict[str, list[dict[str, Any]]] = {t: [] for t in TIER_ORDER}for cfg in _raw_all():@@ -192,10 +170,7 @@ def get_tier_models(*, backend: str | None = None) -> dict[str, list[dict[str, Adef get_model_config_any_backend(model_id: str) -> dict[str, Any] | None:- """The first non-disabled match across backends, or ``None`` when uncatalogued."""- cfg = _raw().get(model_id)- if cfg:- return cfg+ """The first match across backends, or ``None`` when uncatalogued."""for m in _raw_all():aliases = {m.get("id"), m.get("hf_model_id"), *(m.get("benchmark_hf_model_ids") or [])}if model_id in aliases:@@ -203,7 +178,7 @@ def get_model_config_any_backend(model_id: str) -> dict[str, Any] | None:return None-def _finetuning_catalog(+def finetuning_catalog(backend: str, *, include_disabled: bool = False) -> dict[str, list[dict[str, Any]]]:"""Fine-tuning catalog for a backend, grouped by tier (shared shape)."""@@ -225,7 +200,7 @@ def _finetuning_catalog("params": m["params"],"total_params_b": m["total_params_b"],"context_length": ft["context_length"],- # Alias under the field name the Together catalog uses.+ # The recommendation engine reads this key name."context_length_sft": ft["context_length"],"max_batch_size": ft["max_batch_size"],"min_batch_size": ft["min_batch_size"],@@ -239,12 +214,6 @@ def _finetuning_catalog(return {tier: models for tier, models in buckets.items() if models}-def baseten_finetuning_catalog(- *, include_disabled: bool = False-) -> dict[str, list[dict[str, Any]]]:- return _finetuning_catalog("baseten", include_disabled=include_disabled)--def get_all_models_by_backend(backend: str, *, include_disabled: bool = True) -> dict[str, dict[str, Any]]:diff --git a/overbae/modal/models.json b/overbae/modal/models.jsonindex 9cbd74ff..1d429b4b 100644--- a/overbae/modal/models.json+++ b/overbae/modal/models.json@@ -1,5 +1,5 @@{- "comment": "Single source of truth for all models supported by the Overmind platform. Each entry carries a 'backend' field (baseten | together | decision). Models available on multiple backends appear as separate entries with their own inference/finetuning sub-configs. inference.gpu_type is the default for base-model inference (BF16 serving, single GPU). inference.lora_supported declares verified shared-base LoRA support for MoE models; dense models support it by default. inference.min_vram_gb is a measured minimum GPU capacity enforced for automatic inference selection, including short contexts. num_attn_layers/num_kv_heads/head_dim are used by gpu_selector.py to derive the optimal GPU + concurrency for a model at its serving max_model_len, including input and reserved output. For hybrid models (Qwen3.5), num_attn_layers counts only full-attention layers. Use model_registry.py helpers to filter by backend. To add/remove models, edit only this file. Baseten models train LoRA or Full on H100s/H200s via our TRL train.py; finetuning.context_length is the model's max trainable context = HF config max_position_embeddings (Qwen2.5 32768, Qwen3 dense 40960, Qwen3.5/3.6/3.8/Coder 262144, Llama 3.x / GPT-OSS / Antares-1B 131072, Antares-350M 32768, LFM3-1.7B 262144, LFM2.5-230M/350M/1.2B 32768 per Liquid's documented window, LFM2.5-8B-A1B 128000, LFM2.5-2.6B 131072; train.py applies no RoPE scaling). context_length (top-level) is the published inference window (YaRN-extended where the vendor documents it: Qwen2.5\u22657B and Qwen3 dense \u2192 131072; Qwen2.5-0.5B stays 32768). Baseten itself imposes no per-model training context limit (max_seq_len up to 1048576, docs.baseten.co/engines/engine-builder-llm/engine-builder-config; training is arbitrary code, docs.baseten.co/training/getting-started). The runner snaps the actual training MAX_LENGTH up from dataset stats using finetuning_providers.<backend> policy below. pricing.train_from_usd is a marketing 'from' floor for a typical small LoRA run (Baseten H100 $0.10833/GPU-min = $6.50/h, baseten.co/pricing): \u226414B anchored on Jul 2026 Baseten-invoiced job averages; larger sizes estimated from typical GPU-minutes \u00d7 rate on 1\u00d7H100 (\u226472B). pricing.run_from_usd_per_1m_output is serving per 1M output tokens (Modal L4/L40S self-hosted vLLM floors; MoE uses active-param band). group is the marketing library tab label (Group on /models specs); provider comes from providers.display_names. model.marketing holds buyer-facing copy per model (pitch, description, overview, good_for) for the marketing site detail pages. group is only the library tab/filter label. library_filters defines the marketing /models multi-select filters (use_case, tier, context); each model.use_cases lists which use-case filter ids apply. tier/context filters match model.tier and model.context_length against library_filters entries. The order of the models array is the catalog display order within a tier (newest generation first); recommendation ranking is decided by benchmark grades, not by this order.",+ "comment": "Single source of truth for all models supported by the Overmind platform. Each entry carries a 'backend' field naming the provider that trains and serves it (modal | decision). Models available on several backends appear as separate entries with their own inference/finetuning sub-configs. inference.gpu_type is the default for base-model inference (BF16 serving, single GPU). inference.lora_supported declares verified shared-base LoRA support for MoE models; dense models support it by default. inference.min_vram_gb is a measured minimum GPU capacity enforced for automatic inference selection, including short contexts. num_attn_layers/num_kv_heads/head_dim are used by gpu_selector.py to derive the optimal GPU + concurrency for a model at its serving max_model_len, including input and reserved output. For hybrid models (Qwen3.5), num_attn_layers counts only full-attention layers. Use model_registry.py helpers to filter by backend. To add/remove models, edit only this file. modal models train LoRA or Full on H100s/H200s via our train.py; finetuning.context_length is the model's max trainable context = HF config max_position_embeddings (Qwen2.5 32768, Qwen3 dense 40960, Qwen3.5/3.6/3.8/Coder 262144, Llama 3.x / GPT-OSS / Antares-1B 131072, Antares-350M 32768, LFM3-1.7B 262144, LFM2.5-230M/350M/1.2B 32768 per Liquid's documented window, LFM2.5-8B-A1B 128000, LFM2.5-2.6B 131072; train.py applies no RoPE scaling). context_length (top-level) is the published inference window (YaRN-extended where the vendor documents it: Qwen2.5\u22657B and Qwen3 dense \u2192 131072; Qwen2.5-0.5B stays 32768). The runner snaps the actual training MAX_LENGTH up from dataset stats using finetuning_providers.<backend> policy below. pricing.train_from_usd is the 'from' price of a typical small LoRA run at cost: its typical GPU-minutes \u00d7 Modal's H100 rate ($3.95/h, modal.com/pricing, retrieved 2026-11-20) on 1\u00d7H100 (\u226472B). pricing.run_from_usd_per_1m_output is serving per 1M output tokens (Modal L4/L40S self-hosted vLLM floors; MoE uses active-param band). group is the marketing library tab label (Group on /models specs); provider comes from providers.display_names. model.marketing holds buyer-facing copy per model (pitch, description, overview, good_for) for the marketing site detail pages. group is only the library tab/filter label. library_filters defines the marketing /models multi-select filters (use_case, tier, context); each model.use_cases lists which use-case filter ids apply. tier/context filters match model.tier and model.context_length against library_filters entries. The order of the models array is the catalog display order within a tier (newest generation first); recommendation ranking is decided by benchmark grades, not by this order.","providers": {"comment": "Friendly display name per model-id prefix (the part before the first '/'), keyed lowercase, under display_names. Used by overbae.services.model_library to label each model's family/provider on the public /library pages. Unknown prefixes fall back to a title-cased version of the raw prefix \u2014 add an entry here instead of hardcoding it in Python.","display_names": {@@ -18,721 +18,6 @@}},"models": [-{- "id": "Qwen/Qwen3.5-2B",- "openrouter_id": null,- "backend": "together",- "display": "Qwen 3.5 2B",- "hf_model_id": "Qwen/Qwen3.5-2B",- "tier": "compact",- "params": "2B",- "total_params_b": 2.0,- "context_length": 131072,- "supports_tool_calling": true,- "type": null,- "hidden_size": 2048,- "fp8_supported": true,- "inference": {- "gpu_type": "L4",- "max_model_len": 8192- },- "finetuning": {- "context_length": 131072,- "max_batch_size": 8,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 6,- "num_kv_heads": 2,- "head_dim": 256,- "group": "Qwen 3.5",- "pricing": {- "train_from_usd": 0.55,- "run_from_usd_per_1m_output": 4.0- },- "marketing": {- "pitch": "Compact Qwen 3.5 with 128K training context and tool calling.",- "description": "The default recommendation for most agents. A 256K context window at every size, tool calling from 0.8B up, and compact models that train on up to 128K tokens.",- "overview": "Qwen 3.5 is the default recommendation for most agents on Overmind. Every size shares a 256K inference context, tool calling starts at 0.8B, and the compact models train on up to 128K tokens. LoRA on 27B and 35B-A3B uses the full 256K.",- "good_for": [- "General-purpose agents that call tools",- "Long-trace training on compact bases",- "Size ladders from 0.8B through a 35B MoE"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "Qwen/Qwen3.5-0.8B",- "openrouter_id": null,- "backend": "together",- "display": "Qwen 3.5 0.8B",- "hf_model_id": "Qwen/Qwen3.5-0.8B",- "tier": "compact",- "params": "0.8B",- "total_params_b": 0.8,- "context_length": 131072,- "supports_tool_calling": true,- "type": null,- "hidden_size": 1536,- "fp8_supported": true,- "inference": {- "gpu_type": "L4",- "max_model_len": 8192- },- "finetuning": {- "context_length": 131072,- "max_batch_size": 8,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 6,- "num_kv_heads": 2,- "head_dim": 256,- "group": "Qwen 3.5",- "pricing": {- "train_from_usd": 0.5,- "run_from_usd_per_1m_output": 2.5- },- "marketing": {- "pitch": "Smallest Qwen 3.5 with tool calling, trainable at 128K context.",- "description": "The default recommendation for most agents. A 256K context window at every size, tool calling from 0.8B up, and compact models that train on up to 128K tokens.",- "overview": "Qwen 3.5 is the default recommendation for most agents on Overmind. Every size shares a 256K inference context, tool calling starts at 0.8B, and the compact models train on up to 128K tokens. LoRA on 27B and 35B-A3B uses the full 256K.",- "good_for": [- "High-volume tool-calling loops at minimal serve cost",- "Long-trace training on a compact base",- "First experiment in a Qwen 3.5 size ladder"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "Qwen/Qwen3-4B",- "openrouter_id": null,- "backend": "together",- "display": "Qwen 3 4B",- "hf_model_id": "Qwen/Qwen3-4B",- "tier": "compact",- "params": "4B",- "total_params_b": 4.0,- "context_length": 40960,- "supports_tool_calling": true,- "type": null,- "hidden_size": 2560,- "fp8_supported": true,- "inference": {- "gpu_type": "L4",- "max_model_len": 8192- },- "finetuning": {- "context_length": 40960,- "max_batch_size": 16,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 36,- "num_kv_heads": 8,- "head_dim": 128,- "group": "Qwen 3",- "pricing": {- "train_from_usd": 0.7,- "run_from_usd_per_1m_output": 4.0- },- "marketing": {- "pitch": "Compact Qwen 3 step up when 1.7B underfits after training.",- "description": "The widest size ladder in the catalogue, 0.6B through 32B, plus a code-specialised mixture-of-experts model. Useful when you want to hold the family constant and vary only size across parallel experiments.",- "overview": "Qwen 3 gives you the widest size ladder in the catalogue: 0.6B through 32B, plus a code-specialised mixture-of-experts model. Hold the family constant, vary only size across parallel experiments, and let the benchmark pick the winner against your production model.",- "good_for": [- "Side-by-side size sweeps in one family",- "Code agents (via Qwen 3 Coder 30B)",- "Compact bases when tool calling is optional"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "Qwen/Qwen3-1.7B",- "openrouter_id": null,- "backend": "together",- "display": "Qwen 3 1.7B",- "hf_model_id": "Qwen/Qwen3-1.7B",- "tier": "compact",- "params": "1.7B",- "total_params_b": 1.7,- "context_length": 40960,- "supports_tool_calling": true,- "type": null,- "hidden_size": 2048,- "fp8_supported": true,- "inference": {- "gpu_type": "L4",- "max_model_len": 8192- },- "finetuning": {- "context_length": 40960,- "max_batch_size": 32,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 28,- "num_kv_heads": 8,- "head_dim": 128,- "group": "Qwen 3",- "pricing": {- "train_from_usd": 0.55,- "run_from_usd_per_1m_output": 4.0- },- "marketing": {- "pitch": "Compact Qwen 3 with tool calling for cheap, narrow agent jobs.",- "description": "The widest size ladder in the catalogue, 0.6B through 32B, plus a code-specialised mixture-of-experts model. Useful when you want to hold the family constant and vary only size across parallel experiments.",- "overview": "Qwen 3 gives you the widest size ladder in the catalogue: 0.6B through 32B, plus a code-specialised mixture-of-experts model. Hold the family constant, vary only size across parallel experiments, and let the benchmark pick the winner against your production model.",- "good_for": [- "Side-by-side size sweeps in one family",- "Code agents (via Qwen 3 Coder 30B)",- "Compact bases when tool calling is optional"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "meta-llama/Llama-3.2-3B-Instruct",- "openrouter_id": "meta-llama/llama-3.2-3b-instruct",- "backend": "together",- "display": "Llama 3.2 3B Instruct",- "hf_model_id": "meta-llama/Llama-3.2-3B-Instruct",- "tier": "compact",- "params": "3B",- "total_params_b": 3.0,- "context_length": 131072,- "supports_tool_calling": true,- "type": null,- "hidden_size": 3072,- "fp8_supported": false,- "inference": {- "gpu_type": "L4",- "max_model_len": 8192- },- "finetuning": {- "context_length": 131072,- "max_batch_size": 8,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 28,- "num_kv_heads": 8,- "head_dim": 128,- "group": "Llama 3",- "pricing": {- "train_from_usd": 0.55,- "run_from_usd_per_1m_output": 4.0- },- "marketing": {- "pitch": "Compact Llama 3.2 step up, still trainable at the full 128K context.",- "description": "Meta's instruct models, all three trainable at their full 128K context. The natural choice when your rows are long and you want a compact model.",- "overview": "Llama 3 on Overmind covers Meta's instruct models at 1B, 3B, and 8B, each trainable at their full 128K context. Pick this family when your rows are long and you still want a compact model you can serve cheaply after training.",- "good_for": [- "Long-row training on compact bases",- "Meta-stack compatibility",- "Tool-calling agents at 1B through 8B"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "meta-llama/Llama-3.2-1B-Instruct",- "openrouter_id": "meta-llama/llama-3.2-1b-instruct",- "backend": "together",- "display": "Llama 3.2 1B Instruct",- "hf_model_id": "meta-llama/Llama-3.2-1B-Instruct",- "tier": "compact",- "params": "1B",- "total_params_b": 1.0,- "context_length": 131072,- "supports_tool_calling": true,- "type": null,- "hidden_size": 2048,- "fp8_supported": false,- "inference": {- "gpu_type": "L4",- "max_model_len": 8192- },- "finetuning": {- "context_length": 131072,- "max_batch_size": 8,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 16,- "num_kv_heads": 8,- "head_dim": 64,- "group": "Llama 3",- "pricing": {- "train_from_usd": 0.5,- "run_from_usd_per_1m_output": 2.5- },- "marketing": {- "pitch": "Compact Llama trainable at full 128K context for long-row jobs.",- "description": "Meta's instruct models, all three trainable at their full 128K context. The natural choice when your rows are long and you want a compact model.",- "overview": "Llama 3 on Overmind covers Meta's instruct models at 1B, 3B, and 8B, each trainable at their full 128K context. Pick this family when your rows are long and you still want a compact model you can serve cheaply after training.",- "good_for": [- "Long-row training on compact bases",- "Meta-stack compatibility",- "Tool-calling agents at 1B through 8B"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "Qwen/Qwen3.5-9B",- "openrouter_id": "qwen/qwen3.5-9b",- "backend": "together",- "display": "Qwen 3.5 9B",- "hf_model_id": "unsloth/Qwen3.5-9B",- "tier": "small",- "params": "9B",- "total_params_b": 9.0,- "context_length": 262144,- "supports_tool_calling": true,- "type": null,- "hidden_size": 4096,- "fp8_supported": true,- "inference": {- "gpu_type": "L4",- "max_model_len": 16384- },- "finetuning": {- "context_length": 65536,- "max_batch_size": 8,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 8,- "num_kv_heads": 4,- "head_dim": 256,- "group": "Qwen 3.5",- "pricing": {- "train_from_usd": 1.0,- "run_from_usd_per_1m_output": 6.0- },- "marketing": {- "pitch": "Small-tier Qwen 3.5 default when compact quality is not enough.",- "description": "The default recommendation for most agents. A 256K context window at every size, tool calling from 0.8B up, and compact models that train on up to 128K tokens.",- "overview": "Qwen 3.5 is the default recommendation for most agents on Overmind. Every size shares a 256K inference context, tool calling starts at 0.8B, and the compact models train on up to 128K tokens. LoRA on 27B and 35B-A3B uses the full 256K.",- "good_for": [- "General-purpose agents that call tools",- "Long-trace training on compact bases",- "Size ladders from 0.8B through a 35B MoE"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "Qwen/Qwen3-8B",- "openrouter_id": "qwen/qwen3-8b",- "backend": "together",- "display": "Qwen 3 8B",- "hf_model_id": "Qwen/Qwen3-8B",- "tier": "small",- "params": "8B",- "total_params_b": 8.0,- "context_length": 40960,- "supports_tool_calling": true,- "type": null,- "hidden_size": 4096,- "fp8_supported": true,- "inference": {- "gpu_type": "L4",- "max_model_len": 16384- },- "finetuning": {- "context_length": 40960,- "max_batch_size": 8,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 36,- "num_kv_heads": 8,- "head_dim": 128,- "group": "Qwen 3",- "pricing": {- "train_from_usd": 1.0,- "run_from_usd_per_1m_output": 6.0- },- "marketing": {- "pitch": "Small-tier Qwen 3 for size sweeps that need more than compact.",- "description": "The widest size ladder in the catalogue, 0.6B through 32B, plus a code-specialised mixture-of-experts model. Useful when you want to hold the family constant and vary only size across parallel experiments.",- "overview": "Qwen 3 gives you the widest size ladder in the catalogue: 0.6B through 32B, plus a code-specialised mixture-of-experts model. Hold the family constant, vary only size across parallel experiments, and let the benchmark pick the winner against your production model.",- "good_for": [- "Side-by-side size sweeps in one family",- "Code agents (via Qwen 3 Coder 30B)",- "Compact bases when tool calling is optional"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "Qwen/Qwen2.5-7B-Instruct",- "openrouter_id": "qwen/qwen-2.5-7b-instruct",- "backend": "together",- "display": "Qwen 2.5 7B Instruct",- "hf_model_id": "Qwen/Qwen2.5-7B-Instruct",- "tier": "small",- "params": "7B",- "total_params_b": 7.0,- "context_length": 32768,- "supports_tool_calling": true,- "type": null,- "hidden_size": 3584,- "fp8_supported": true,- "inference": {- "gpu_type": "L4",- "max_model_len": 16384- },- "finetuning": {- "context_length": 32768,- "max_batch_size": 16,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 28,- "num_kv_heads": 4,- "head_dim": 128,- "group": "Qwen 2.5",- "pricing": {- "train_from_usd": 1.0,- "run_from_usd_per_1m_output": 6.0- },- "marketing": {- "pitch": "Small-tier Qwen 2.5 instruct for pipelines already tuned on this line.",- "description": "The mature, heavily-benchmarked generation, including a dedicated coder model at 32B. Worth keeping when an existing pipeline is already tuned around it.",- "overview": "Qwen 2.5 is the mature, heavily-benchmarked generation on the platform, including a dedicated 32B coder. Keep it when an existing pipeline is already tuned around this line and you want controlled training rather than a family jump.",- "good_for": [- "Pipelines already tuned on Qwen 2.5",- "Code specialists at 32B",- "Stable baselines for eval-driven iteration"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "meta-llama/Meta-Llama-3.1-8B-Instruct-Reference",- "openrouter_id": "meta-llama/llama-3.1-8b-instruct",- "backend": "together",- "display": "Llama 3.1 8B Instruct",- "hf_model_id": "meta-llama/Llama-3.1-8B-Instruct",- "tier": "small",- "params": "8B",- "total_params_b": 8.0,- "context_length": 131072,- "supports_tool_calling": true,- "type": null,- "hidden_size": 4096,- "fp8_supported": true,- "inference": {- "gpu_type": "L4",- "max_model_len": 8192- },- "finetuning": {- "context_length": 131072,- "max_batch_size": 8,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 32,- "num_kv_heads": 8,- "head_dim": 128,- "group": "Llama 3",- "pricing": {- "train_from_usd": 1.0,- "run_from_usd_per_1m_output": 6.0- },- "marketing": {- "pitch": "Small-tier Llama 3.1 with full 128K training context and tool calling.",- "description": "Meta's instruct models, all three trainable at their full 128K context. The natural choice when your rows are long and you want a compact model.",- "overview": "Llama 3 on Overmind covers Meta's instruct models at 1B, 3B, and 8B, each trainable at their full 128K context. Pick this family when your rows are long and you still want a compact model you can serve cheaply after training.",- "good_for": [- "Long-row training on compact bases",- "Meta-stack compatibility",- "Tool-calling agents at 1B through 8B"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "Qwen/Qwen3.5-27B",- "openrouter_id": "qwen/qwen3.5-27b",- "backend": "together",- "display": "Qwen 3.5 27B",- "hf_model_id": "Qwen/Qwen3.5-27B",- "tier": "mid",- "params": "27B",- "total_params_b": 27.0,- "context_length": 131072,- "supports_tool_calling": true,- "type": null,- "hidden_size": 7168,- "fp8_supported": true,- "inference": {- "gpu_type": "A100-80GB",- "max_model_len": 16384- },- "finetuning": {- "context_length": 32768,- "max_batch_size": 16,- "min_batch_size": 16,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": true,- "disabled_reason": null,- "num_attn_layers": 16,- "num_kv_heads": 4,- "head_dim": 256,- "group": "Qwen 3.5",- "pricing": {- "train_from_usd": 2.0,- "run_from_usd_per_1m_output": 15.0- },- "marketing": {- "pitch": "Mid-tier Qwen 3.5 for agents that need more headroom before an MoE jump.",- "description": "The default recommendation for most agents. A 256K context window at every size, tool calling from 0.8B up, and compact models that train on up to 128K tokens.",- "overview": "Qwen 3.5 is the default recommendation for most agents on Overmind. Every size shares a 256K inference context, tool calling starts at 0.8B, and the compact models train on up to 128K tokens. LoRA on 27B and 35B-A3B uses the full 256K.",- "good_for": [- "General-purpose agents that call tools",- "Long-trace training on compact bases",- "Size ladders from 0.8B through a 35B MoE"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "Qwen/Qwen3-14B",- "openrouter_id": "qwen/qwen3-14b",- "backend": "together",- "display": "Qwen 3 14B",- "hf_model_id": "Qwen/Qwen3-14B",- "tier": "mid",- "params": "14B",- "total_params_b": 14.0,- "context_length": 40960,- "supports_tool_calling": true,- "type": null,- "hidden_size": 5120,- "fp8_supported": true,- "inference": {- "gpu_type": "L40S",- "max_model_len": 16384- },- "finetuning": {- "context_length": 40960,- "max_batch_size": 8,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": true- },- "lora": {- "enabled": true- }- }- },- "disabled": false,- "disabled_reason": null,- "num_attn_layers": 40,- "num_kv_heads": 8,- "head_dim": 128,- "group": "Qwen 3",- "pricing": {- "train_from_usd": 1.25,- "run_from_usd_per_1m_output": 10.0- },- "marketing": {- "pitch": "Mid-tier dense Qwen 3 for parallel experiments against compact and large.",- "description": "The widest size ladder in the catalogue, 0.6B through 32B, plus a code-specialised mixture-of-experts model. Useful when you want to hold the family constant and vary only size across parallel experiments.",- "overview": "Qwen 3 gives you the widest size ladder in the catalogue: 0.6B through 32B, plus a code-specialised mixture-of-experts model. Hold the family constant, vary only size across parallel experiments, and let the benchmark pick the winner against your production model.",- "good_for": [- "Side-by-side size sweeps in one family",- "Code agents (via Qwen 3 Coder 30B)",- "Compact bases when tool calling is optional"- ]- },- "use_cases": [- "tool-calling"- ]- },-{- "id": "Qwen/Qwen3.5-35B-A3B",- "openrouter_id": "qwen/qwen3.5-35b-a3b",- "backend": "together",- "display": "Qwen 3.5 35B MoE",- "hf_model_id": "Qwen/Qwen3.5-35B-A3B",- "tier": "large",- "params": "35B MoE (3B active)",- "total_params_b": 35.0,- "context_length": 262144,- "supports_tool_calling": true,- "type": null,- "hidden_size": 7168,- "fp8_supported": true,- "inference": {- "gpu_type": "A100-80GB",- "max_model_len": 16384- },- "finetuning": {- "context_length": 65536,- "max_batch_size": 8,- "min_batch_size": 8,- "training_type": {- "full": {- "enabled": false- },- "lora": {- "enabled": true- }- }- },- "disabled": true,- "disabled_reason": null,- "num_attn_layers": 10,- "num_kv_heads": 2,- "head_dim": 256,- "group": "Qwen 3.5",- "pricing": {- "train_from_usd": 2.5,- "run_from_usd_per_1m_output": 8.0- },- "marketing": {- "pitch": "Large MoE Qwen 3.5: 35B total weights, 3B active per token at serve time.",- "description": "The default recommendation for most agents. A 256K context window at every size, tool calling from 0.8B up, and compact models that train on up to 128K tokens.",- "overview": "Qwen 3.5 is the default recommendation for most agents on Overmind. Every size shares a 256K inference context, tool calling starts at 0.8B, and the compact models train on up to 128K tokens. LoRA on 27B and 35B-A3B uses the full 256K.",- "good_for": [- "Higher-quality Qwen 3.5 runs with MoE serve economics",- "Tool-calling agents that outgrow dense mid-tier bases",- "Side-by-side experiments against Qwen 3.5 27B"- ]- },- "use_cases": [- "tool-calling"- ]- },{"id": "Qwen/Qwen3.5-4B","openrouter_id": null,@@ -771,12 +56,12 @@"num_attn_layers": 8,"num_kv_heads": 4,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Qwen 3.5","pricing": {- "train_from_usd": 0.7,+ "train_from_usd": 0.43,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -834,12 +119,12 @@"num_attn_layers": 6,"num_kv_heads": 2,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Qwen 3.5","pricing": {- "train_from_usd": 0.55,+ "train_from_usd": 0.33,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -897,12 +182,12 @@"num_attn_layers": 6,"num_kv_heads": 2,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Qwen 3.5","pricing": {- "train_from_usd": 0.5,+ "train_from_usd": 0.3,"run_from_usd_per_1m_output": 2.5},"marketing": {@@ -925,7 +210,7 @@{"id": "Qwen/Qwen3-4B","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Qwen 3 4B","hf_model_id": "unsloth/Qwen3-4B","tier": "compact",@@ -965,7 +250,7 @@"head_dim": 128,"group": "Qwen 3","pricing": {- "train_from_usd": 0.7,+ "train_from_usd": 0.43,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -988,7 +273,7 @@{"id": "Qwen/Qwen3-1.7B","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Qwen 3 1.7B","hf_model_id": "unsloth/Qwen3-1.7B","tier": "compact",@@ -1028,7 +313,7 @@"head_dim": 128,"group": "Qwen 3","pricing": {- "train_from_usd": 0.55,+ "train_from_usd": 0.33,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -1049,7 +334,7 @@{"id": "Qwen/Qwen3-0.6B","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Qwen 3 0.6B","hf_model_id": "unsloth/Qwen3-0.6B","tier": "compact",@@ -1089,7 +374,7 @@"head_dim": 128,"group": "Qwen 3","pricing": {- "train_from_usd": 0.5,+ "train_from_usd": 0.3,"run_from_usd_per_1m_output": 2.5},"marketing": {@@ -1110,7 +395,7 @@{"id": "Qwen/Qwen2.5-0.5B-Instruct","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Qwen 2.5 0.5B Instruct","hf_model_id": "unsloth/Qwen2.5-0.5B-Instruct","tier": "compact",@@ -1150,7 +435,7 @@"head_dim": 64,"group": "Qwen 2.5","pricing": {- "train_from_usd": 0.5,+ "train_from_usd": 0.3,"run_from_usd_per_1m_output": 2.5},"marketing": {@@ -1171,7 +456,7 @@{"id": "meta-llama/Llama-3.2-3B-Instruct","openrouter_id": "meta-llama/llama-3.2-3b-instruct",- "backend": "baseten",+ "backend": "modal","display": "Llama 3.2 3B Instruct","hf_model_id": "unsloth/Llama-3.2-3B-Instruct","tier": "compact",@@ -1211,7 +496,7 @@"head_dim": 128,"group": "Llama 3","pricing": {- "train_from_usd": 0.55,+ "train_from_usd": 0.33,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -1232,7 +517,7 @@{"id": "meta-llama/Llama-3.2-1B-Instruct","openrouter_id": "meta-llama/llama-3.2-1b-instruct",- "backend": "baseten",+ "backend": "modal","display": "Llama 3.2 1B Instruct","hf_model_id": "unsloth/Llama-3.2-1B-Instruct","tier": "compact",@@ -1272,7 +557,7 @@"head_dim": 64,"group": "Llama 3","pricing": {- "train_from_usd": 0.5,+ "train_from_usd": 0.3,"run_from_usd_per_1m_output": 2.5},"marketing": {@@ -1293,7 +578,7 @@{"id": "LiquidAI/LFM3-1.7B","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "LFM3 1.7B","hf_model_id": "LiquidAI/LFM3-1.7B","tier": "compact",@@ -1333,7 +618,7 @@"head_dim": 128,"group": "LFM3","pricing": {- "train_from_usd": 0.55,+ "train_from_usd": 0.33,"run_from_usd_per_1m_output": 2.5},"marketing": {@@ -1356,7 +641,7 @@{"id": "LiquidAI/LFM2.5-2.6B","openrouter_id": "liquid/lfm-2.5-2.6b:free",- "backend": "baseten",+ "backend": "modal","display": "LFM2.5 2.6B","hf_model_id": "LiquidAI/LFM2.5-2.6B","tier": "compact",@@ -1396,7 +681,7 @@"head_dim": 64,"group": "LFM2.5","pricing": {- "train_from_usd": 0.55,+ "train_from_usd": 0.33,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -1416,7 +701,7 @@{"id": "LiquidAI/LFM2.5-1.2B-Instruct","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "LFM2.5 1.2B Instruct","hf_model_id": "unsloth/LFM2.5-1.2B-Instruct","tier": "compact",@@ -1456,7 +741,7 @@"head_dim": 64,"group": "LFM2.5","pricing": {- "train_from_usd": 0.5,+ "train_from_usd": 0.3,"run_from_usd_per_1m_output": 2.5},"marketing": {@@ -1479,7 +764,7 @@{"id": "LiquidAI/LFM2.5-350M","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "LFM2.5 350M","hf_model_id": "LiquidAI/LFM2.5-350M","tier": "compact",@@ -1519,7 +804,7 @@"head_dim": 64,"group": "LFM2.5","pricing": {- "train_from_usd": 0.5,+ "train_from_usd": 0.3,"run_from_usd_per_1m_output": 2.5},"marketing": {@@ -1539,7 +824,7 @@{"id": "LiquidAI/LFM2.5-230M","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "LFM2.5 230M","hf_model_id": "unsloth/LFM2.5-230M","tier": "compact",@@ -1579,7 +864,7 @@"head_dim": 64,"group": "LFM2.5","pricing": {- "train_from_usd": 0.5,+ "train_from_usd": 0.3,"run_from_usd_per_1m_output": 2.5},"marketing": {@@ -1602,7 +887,7 @@{"id": "fdtn-ai/antares-1b","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Antares 1B (Security)","hf_model_id": "fdtn-ai/antares-1b","tier": "compact",@@ -1642,7 +927,7 @@"head_dim": 128,"group": "Antares","pricing": {- "train_from_usd": 0.55,+ "train_from_usd": 0.33,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -1663,7 +948,7 @@{"id": "fdtn-ai/antares-350m","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Antares 350M (Security)","hf_model_id": "fdtn-ai/antares-350m","tier": "compact",@@ -1703,7 +988,7 @@"head_dim": 64,"group": "Antares","pricing": {- "train_from_usd": 0.5,+ "train_from_usd": 0.3,"run_from_usd_per_1m_output": 2.5},"marketing": {@@ -1759,12 +1044,12 @@"num_attn_layers": 8,"num_kv_heads": 4,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Qwen 3.5","pricing": {- "train_from_usd": 1.0,+ "train_from_usd": 0.61,"run_from_usd_per_1m_output": 6.0},"marketing": {@@ -1787,7 +1072,7 @@{"id": "Qwen/Qwen3-8B","openrouter_id": "qwen/qwen3-8b",- "backend": "baseten",+ "backend": "modal","display": "Qwen 3 8B","hf_model_id": "unsloth/Qwen3-8B","tier": "small",@@ -1827,7 +1112,7 @@"head_dim": 128,"group": "Qwen 3","pricing": {- "train_from_usd": 1.0,+ "train_from_usd": 0.61,"run_from_usd_per_1m_output": 6.0},"marketing": {@@ -1850,7 +1135,7 @@{"id": "Qwen/Qwen2.5-7B-Instruct","openrouter_id": "qwen/qwen-2.5-7b-instruct",- "backend": "baseten",+ "backend": "modal","display": "Qwen 2.5 7B Instruct","hf_model_id": "unsloth/Qwen2.5-7B-Instruct","tier": "small",@@ -1890,7 +1175,7 @@"head_dim": 128,"group": "Qwen 2.5","pricing": {- "train_from_usd": 1.0,+ "train_from_usd": 0.61,"run_from_usd_per_1m_output": 6.0},"marketing": {@@ -1948,12 +1233,12 @@"num_attn_layers": 8,"num_kv_heads": 4,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Ornith","pricing": {- "train_from_usd": 1.0,+ "train_from_usd": 0.61,"run_from_usd_per_1m_output": 6.0},"marketing": {@@ -1976,7 +1261,7 @@{"id": "google/gemma-4-E4B-it","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Gemma 4 E4B","hf_model_id": "unsloth/gemma-4-E4B-it","tier": "small",@@ -2018,7 +1303,7 @@"head_dim": 256,"group": "Gemma 4","pricing": {- "train_from_usd": 0.75,+ "train_from_usd": 0.46,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -2039,7 +1324,7 @@{"id": "google/gemma-4-E2B-it","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Gemma 4 E2B","hf_model_id": "unsloth/gemma-4-E2B-it","tier": "small",@@ -2081,7 +1366,7 @@"head_dim": 256,"group": "Gemma 4","pricing": {- "train_from_usd": 0.55,+ "train_from_usd": 0.33,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -2102,7 +1387,7 @@{"id": "meta-llama/Llama-3.1-8B-Instruct","openrouter_id": "meta-llama/llama-3.1-8b-instruct",- "backend": "baseten",+ "backend": "modal","display": "Llama 3.1 8B Instruct","hf_model_id": "unsloth/Llama-3.1-8B-Instruct","tier": "small",@@ -2142,7 +1427,7 @@"head_dim": 128,"group": "Llama 3","pricing": {- "train_from_usd": 1.0,+ "train_from_usd": 0.61,"run_from_usd_per_1m_output": 6.0},"marketing": {@@ -2165,7 +1450,7 @@{"id": "LiquidAI/LFM2.5-8B-A1B","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "LFM2.5 8B-A1B","hf_model_id": "LiquidAI/LFM2.5-8B-A1B","tier": "small",@@ -2205,7 +1490,7 @@"head_dim": 64,"group": "LFM2.5","pricing": {- "train_from_usd": 0.75,+ "train_from_usd": 0.46,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -2260,12 +1545,12 @@"num_attn_layers": 16,"num_kv_heads": 4,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Qwen 3.8","pricing": {- "train_from_usd": 2.0,+ "train_from_usd": 1.22,"run_from_usd_per_1m_output": 15.0},"marketing": {@@ -2323,12 +1608,12 @@"num_attn_layers": 16,"num_kv_heads": 4,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Qwen 3.6","pricing": {- "train_from_usd": 2.0,+ "train_from_usd": 1.22,"run_from_usd_per_1m_output": 15.0},"marketing": {@@ -2386,12 +1671,12 @@"num_attn_layers": 16,"num_kv_heads": 4,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Qwen 3.5","pricing": {- "train_from_usd": 2.0,+ "train_from_usd": 1.22,"run_from_usd_per_1m_output": 15.0},"marketing": {@@ -2451,12 +1736,12 @@"num_attn_layers": 48,"num_kv_heads": 4,"head_dim": 128,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Qwen 3","pricing": {- "train_from_usd": 2.0,+ "train_from_usd": 1.22,"run_from_usd_per_1m_output": 8.0},"marketing": {@@ -2477,7 +1762,7 @@{"id": "Qwen/Qwen3-14B","openrouter_id": "qwen/qwen3-14b",- "backend": "baseten",+ "backend": "modal","display": "Qwen 3 14B","hf_model_id": "unsloth/Qwen3-14B","tier": "mid",@@ -2517,7 +1802,7 @@"head_dim": 128,"group": "Qwen 3","pricing": {- "train_from_usd": 1.25,+ "train_from_usd": 0.76,"run_from_usd_per_1m_output": 10.0},"marketing": {@@ -2540,7 +1825,7 @@{"id": "Qwen/Qwen2.5-14B-Instruct","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Qwen 2.5 14B Instruct","hf_model_id": "unsloth/Qwen2.5-14B-Instruct","tier": "mid",@@ -2580,7 +1865,7 @@"head_dim": 128,"group": "Qwen 2.5","pricing": {- "train_from_usd": 1.25,+ "train_from_usd": 0.76,"run_from_usd_per_1m_output": 10.0},"marketing": {@@ -2638,12 +1923,12 @@"num_attn_layers": 16,"num_kv_heads": 4,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Fara","pricing": {- "train_from_usd": 2.0,+ "train_from_usd": 1.22,"run_from_usd_per_1m_output": 15.0},"marketing": {@@ -2666,7 +1951,7 @@{"id": "google/gemma-4-12B-it","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Gemma 4 12B","hf_model_id": "unsloth/gemma-4-12b-it","tier": "mid",@@ -2707,7 +1992,7 @@"head_dim": 256,"group": "Gemma 4","pricing": {- "train_from_usd": 1.0,+ "train_from_usd": 0.61,"run_from_usd_per_1m_output": 6.0},"marketing": {@@ -2765,12 +2050,12 @@"num_attn_layers": 12,"num_kv_heads": 8,"head_dim": 64,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "GPT-OSS","pricing": {- "train_from_usd": 1.75,+ "train_from_usd": 1.06,"run_from_usd_per_1m_output": 12.0},"marketing": {@@ -2828,12 +2113,12 @@"num_attn_layers": 10,"num_kv_heads": 2,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Qwen 3.5","pricing": {- "train_from_usd": 2.5,+ "train_from_usd": 1.52,"run_from_usd_per_1m_output": 8.0},"marketing": {@@ -2856,7 +2141,7 @@{"id": "Qwen/Qwen3-32B","openrouter_id": "qwen/qwen3-32b",- "backend": "baseten",+ "backend": "modal","display": "Qwen 3 32B","hf_model_id": "unsloth/Qwen3-32B","tier": "large",@@ -2896,7 +2181,7 @@"head_dim": 128,"group": "Qwen 3","pricing": {- "train_from_usd": 2.25,+ "train_from_usd": 1.37,"run_from_usd_per_1m_output": 20.0},"marketing": {@@ -2919,7 +2204,7 @@{"id": "Qwen/Qwen2.5-72B-Instruct","openrouter_id": "qwen/qwen-2.5-72b-instruct",- "backend": "baseten",+ "backend": "modal","display": "Qwen 2.5 72B Instruct","hf_model_id": "unsloth/Qwen2.5-72B-Instruct","tier": "large",@@ -2959,7 +2244,7 @@"head_dim": 128,"group": "Qwen 2.5","pricing": {- "train_from_usd": 5.0,+ "train_from_usd": 3.04,"run_from_usd_per_1m_output": 40.0},"marketing": {@@ -2980,7 +2265,7 @@{"id": "Qwen/Qwen2.5-32B-Instruct","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Qwen 2.5 32B Instruct","hf_model_id": "unsloth/Qwen2.5-32B-Instruct","tier": "large",@@ -3020,7 +2305,7 @@"head_dim": 128,"group": "Qwen 2.5","pricing": {- "train_from_usd": 2.25,+ "train_from_usd": 1.37,"run_from_usd_per_1m_output": 20.0},"marketing": {@@ -3043,7 +2328,7 @@{"id": "Qwen/Qwen2.5-Coder-32B-Instruct","openrouter_id": "qwen/qwen-2.5-coder-32b-instruct",- "backend": "baseten",+ "backend": "modal","display": "Qwen 2.5 Coder 32B Instruct","hf_model_id": "unsloth/Qwen2.5-Coder-32B-Instruct","tier": "large",@@ -3083,7 +2368,7 @@"head_dim": 128,"group": "Qwen 2.5","pricing": {- "train_from_usd": 2.25,+ "train_from_usd": 1.37,"run_from_usd_per_1m_output": 20.0},"marketing": {@@ -3144,12 +2429,12 @@"num_attn_layers": 10,"num_kv_heads": 2,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Ornith","pricing": {- "train_from_usd": 2.5,+ "train_from_usd": 1.52,"run_from_usd_per_1m_output": 8.0},"marketing": {@@ -3172,7 +2457,7 @@{"id": "google/gemma-4-31B-it","openrouter_id": "google/gemma-4-31b-it",- "backend": "baseten",+ "backend": "modal","display": "Gemma 4 31B","hf_model_id": "unsloth/gemma-4-31B-it","tier": "large",@@ -3213,7 +2498,7 @@"head_dim": 256,"group": "Gemma 4","pricing": {- "train_from_usd": 2.5,+ "train_from_usd": 1.52,"run_from_usd_per_1m_output": 10.0},"marketing": {@@ -3234,7 +2519,7 @@{"id": "google/gemma-4-26B-A4B-it","openrouter_id": "google/gemma-4-26b-a4b-it",- "backend": "baseten",+ "backend": "modal","display": "Gemma 4 26B-A4B","hf_model_id": "unsloth/gemma-4-26B-A4B-it","tier": "large",@@ -3275,7 +2560,7 @@"head_dim": 256,"group": "Gemma 4","pricing": {- "train_from_usd": 2.0,+ "train_from_usd": 1.22,"run_from_usd_per_1m_output": 8.0},"marketing": {@@ -3296,7 +2581,7 @@{"id": "meta-llama/Llama-3.3-70B-Instruct","openrouter_id": "meta-llama/llama-3.3-70b-instruct",- "backend": "baseten",+ "backend": "modal","display": "Llama 3.3 70B Instruct","hf_model_id": "unsloth/Llama-3.3-70B-Instruct","tier": "large",@@ -3336,7 +2621,7 @@"head_dim": 128,"group": "Llama 3","pricing": {- "train_from_usd": 4.5,+ "train_from_usd": 2.73,"run_from_usd_per_1m_output": 35.0},"marketing": {@@ -3359,7 +2644,7 @@{"id": "unsloth/Muse-Glimmer-30B","openrouter_id": null,- "backend": "baseten",+ "backend": "modal","display": "Muse Glimmer 30B","hf_model_id": "unsloth/Muse-Glimmer-30B","tier": "large",@@ -3400,7 +2685,7 @@"head_dim": 128,"group": "Muse Glimmer","pricing": {- "train_from_usd": 2.5,+ "train_from_usd": 1.52,"run_from_usd_per_1m_output": 10.0},"marketing": {@@ -3458,12 +2743,12 @@"num_attn_layers": 42,"num_kv_heads": 2,"head_dim": 256,- "backend": "baseten",+ "backend": "modal","disabled": false,"disabled_reason": null,"group": "Nemotron","pricing": {- "train_from_usd": 0.75,+ "train_from_usd": 0.46,"run_from_usd_per_1m_output": 4.0},"marketing": {@@ -3486,7 +2771,7 @@{"id": "nvidia/NVIDIA-Nemotron-3.5-Lightning-30B-A3B","openrouter_id": "nvidia/nemotron-3.5-lightning",- "backend": "baseten",+ "backend": "modal","display": "Nemotron 3.5 Lightning 30B-A3B","hf_model_id": "unsloth/NVIDIA-Nemotron-3.5-Lightning-30B-A3B","benchmark_hf_model_ids": [@@ -3531,7 +2816,7 @@"head_dim": 128,"group": "Nemotron 3.5","pricing": {- "train_from_usd": 2.0,+ "train_from_usd": 1.22,"run_from_usd_per_1m_output": 6.0},"marketing": {@@ -4068,8 +3353,8 @@}],"finetuning_providers": {- "baseten": {- "comment": "MAX_LENGTH snapping policy for train.py \u2014 our choice, not a Baseten platform limit: power-of-two buckets keep padding/packing predictable; headroom covers chat-template/special tokens beyond the raw JSON token estimate.",+ "modal": {+ "comment": "MAX_LENGTH snapping policy for train.py \u2014 our choice, not a provider limit: power-of-two buckets keep padding/packing predictable; headroom covers chat-template/special tokens beyond the raw JSON token estimate.","context_buckets": [4096,8192,diff --git a/overbae/modal/register_model.py b/overbae/modal/register_model.pyindex aefb16a4..d2e41b59 100644--- a/overbae/modal/register_model.py+++ b/overbae/modal/register_model.py@@ -1,4 +1,4 @@-"""Download fine-tune checkpoints (Nebius, Baseten, or Modal), merge LoRA, and FP8-quantize for+"""Download fine-tune checkpoints (Nebius, Modal, or the S3 archive), merge LoRA, and FP8-quantize forserving. ``quantize=False`` skips FP8 and serves merged BF16 — see``weight_ops.quantize_checkpoint`` for which models need that.@@ -16,7 +16,7 @@ Storage layout:/weights/.drafts/{org--draft}/ DFlash drafts for the bases that use one/weights/.adapters/{job_id}/ LoRA adapters served on a shared base-S3 (baseten/modal only), the durable provider-independent home the UI's checkpoint-download+S3, the durable provider-independent home the UI's checkpoint-downloadbutton reads from. Archiving is idempotent, and a metadata-only zip counts as missing so thenext deploy retries:{user_id}/{finetuning_job_id}/checkpoints/checkpoint.zip@@ -25,9 +25,7 @@ next deploy retries:Modal secrets, under secret name "overmind-inference":INFERENCE_API_KEY — bearer token for RegisterAPIServer HTTP endpoints- TOGETHER_API_KEY — Together SDK checkpoint download + job validationNEBIUS_API_KEY — Nebius download; MUST be the key that submitted the job- BASETEN_API_KEY — Baseten checkpoint downloadHF_TOKEN — optional, needed for gated base models during mergeAWS_ACCESS_KEY_ID — S3 checkpoint archive (CloudBucketMount)AWS_SECRET_ACCESS_KEY — S3 checkpoint archive (CloudBucketMount)@@ -225,14 +223,14 @@ def _resolve_staged_base(def resolve_artifact_dir(staging: Path) -> tuple[Path, bool]:- """Returns ``(dir, is_lora)``. Baseten produces two real layouts: the final artifact at the- staging ROOT, or ONLY nested ``checkpoint-N/`` dirs when the root save did not sync, in which- case the artifact is the highest-step checkpoint. Handing the staging root to AutoConfig in- the nested case raises "Unrecognized model".-- A config file alone does NOT make a directory the artifact: Baseten's listing can surface- config.json before the larger weight files finish syncing, so a directory is trusted only once- it also holds a weight file.+ """Returns ``(dir, is_lora)``. Archived checkpoints have two real layouts: the final artifact+ at the staging ROOT, or ONLY nested ``checkpoint-N/`` dirs when the root save did not sync, in+ which case the artifact is the highest-step checkpoint. Handing the staging root to AutoConfig+ in the nested case raises "Unrecognized model".++ A config file alone does NOT make a directory the artifact: an archive can hold config.json+ without the larger weight files, so a directory is trusted only once it also holds a weight+ file."""if (staging / "adapter_config.json").exists() and _dir_has_weights(staging):return staging, True@@ -401,7 +399,7 @@ def _read_json(path: Path) -> dict | None:)@modal.concurrent(max_inputs=50)class RegisterAPIServer:- """CPU gateway: cache check → Baseten download → GPU merge/quantize."""+ """CPU gateway: cache check → checkpoint staging → GPU merge/quantize."""@modal.method()def register(@@ -409,43 +407,32 @@ class RegisterAPIServer:*,remote_job_id: str,model_id: str,- provider: str = "baseten",- baseten_api_key: str = "",+ provider: str = "modal",user_id: str = "",job_id: str = "",- job_result: dict | None = None,quantize: bool = True,merge_base_model: str = "",params_b: float = 0.0,) -> dict:"""Runs download + quantize (or copy) on a cache miss.- ``user_id``/``job_id``/``job_result`` apply only to the baseten and modal providers, where- they address the S3 archive. ``quantize`` carries models.json's ``fp8_supported``.+ ``user_id``/``job_id`` address the S3 archive. ``quantize`` carries models.json's ``fp8_supported``.``merge_base_model`` is the catalog HF id, used when adapter_config points at a quantizedremapped repo. ``params_b`` only picks the merge/quantize GPU tier."""- if provider not in ("nebius", "baseten", "modal"):- raise ValueError(- f"Provider {provider!r} is not supported. Use 'nebius', 'baseten', or 'modal'."- )- if provider in ("baseten", "modal") and not job_id:+ if provider not in ("nebius", "modal"):+ raise ValueError(f"Provider {provider!r} is not supported. Use 'nebius' or 'modal'.")+ if provider == "modal" and not job_id:raise ValueError(f"job_id is required for provider={provider!r} (S3 archive addressing)")weights_vol.reload()- # Cache key: Baseten remote_id is "project_id:job_id", stable part LAST; Modal- # remote_id is "run_id:function_call_id", stable part FIRST, because a+ # Cache key: Modal remote_id is "run_id:function_call_id", stable part FIRST, because a# FunctionCall id is not reusable across retries. This is the FP8-cache key,# independent of the S3 archive's {user_id}/{job_id} namespace.- if provider == "baseten":- cache_key = remote_job_id.split(":")[-1]- elif provider == "modal":- cache_key = remote_job_id.split(":")[0]- else:- cache_key = remote_job_id+ cache_key = remote_job_id.split(":")[0] if provider == "modal" else remote_job_idexpected_quant = "fp8" if quantize else "bf16"weights_dir = _weights_dir(cache_key)meta_file = weights_dir / ".meta.json"@@ -458,24 +445,6 @@ class RegisterAPIServer:download_meta = _read_json(staging / ".download_meta.json")def _dispatch_download() -> dict:- if provider == "baseten":- key = baseten_api_key or os.environ.get("BASETEN_API_KEY", "")- print(f"[RegisterAPI] Archiving {remote_job_id} (Baseten) to S3")- sync_baseten_checkpoint_to_s3.remote(- remote_id=remote_job_id,- user_id=user_id,- job_id=job_id,- baseten_api_key=key,- job_result=job_result or {},- )- print(f"[RegisterAPI] Pulling {job_id} checkpoint back from S3")- return download_checkpoint_from_s3.remote(- user_id=user_id,- job_id=job_id,- model_id=model_id,- cache_key=cache_key,- merge_base_model=merge_base_model,- )if provider == "modal":# Training wrote the checkpoint to a Volume in this same Modal account, so stage# it volume→volume rather than gating the deploy on zip→upload→download→unzip.@@ -649,11 +618,9 @@ class RegisterAPIServer:class RegisterRequest(BaseModel):remote_job_id: strmodel_id: str- provider: str = "baseten"- baseten_api_key: str = ""+ provider: str = "modal"user_id: str = ""job_id: str = ""- job_result: dict | None = Nonequantize: bool = True@web.get("/health")@@ -666,10 +633,8 @@ class RegisterAPIServer:remote_job_id=req.remote_job_id,model_id=req.model_id,provider=req.provider,- baseten_api_key=req.baseten_api_key,user_id=req.user_id,job_id=req.job_id,- job_result=req.job_result,quantize=req.quantize,)@@ -683,35 +648,6 @@ class RegisterAPIServer:return web-def _fetch_baseten_logs_text(project_id: str, job_id: str, headers: dict, api_base: str) -> str:- """Same pagination shape as ``BasetenRunner._fetch_logs``, but standalone: this module has no- Django import and calls Baseten's API directly."""- import requests # noqa: PLC0415-- lines: list[str] = []- cursor_ms = 0- last_ns = -1- for _ in range(30):- resp = requests.get(- f"{api_base}/v1/training_projects/{project_id}/jobs/{job_id}/logs",- headers=headers,- params={"limit": 1000, "direction": "asc", "start_epoch_millis": cursor_ms},- timeout=30,- )- resp.raise_for_status()- page = resp.json().get("logs", [])- fresh = (- [e for e in page if int(e.get("timestamp") or 0) > last_ns] if last_ns >= 0 else page- )- for entry in fresh:- lines.append(str(entry.get("message") or "").rstrip("\n"))- if len(page) < 1000 or (last_ns >= 0 and not fresh):- break- last_ns = int(page[-1].get("timestamp") or 0)- cursor_ms = last_ns // 1_000_000- return "\n".join(lines)--def _archive_to_s3(user_id: str, job_id: str, local_zip: Path, log_text: str, metrics: dict) -> None:@@ -734,191 +670,6 @@ def _s3_checkpoint_exists(user_id: str, job_id: str) -> bool:return zip_path.exists() and zip_path.stat().st_size > 0 and _zip_has_weights(zip_path)- image=download_image,- timeout=2 * 60 * 60,- scaledown_window=2,- volumes={S3_MOUNT: _s3_mount(read_only=False)},- secrets=[inference_secret, aws_secret],-)[email protected](max_inputs=1)-def sync_baseten_checkpoint_to_s3(- *,- remote_id: str,- user_id: str,- job_id: str,- baseten_api_key: str = "",- job_result: dict | None = None,-) -> dict:- """``remote_id`` is ``"{project_id}:{baseten_job_id}"``; ``job_id`` is the Django FinetuningJob- PK, the S3 addressing key and distinct from ``baseten_job_id``. Idempotent."""- import requests # noqa: PLC0415-- if _s3_checkpoint_exists(user_id, job_id):- print(f"[Baseten→S3] {job_id} already archived — skipping")- return {"job_id": job_id, "skipped": True}-- # Drop a metadata-only zip left by a mid-sync archive, or it poisons the bucket- # next to the fresh one.- stale = _s3_prefix(user_id, job_id) / "checkpoints" / "checkpoint.zip"- if stale.exists():- print(f"[Baseten→S3] {job_id} has incomplete checkpoint.zip — re-archiving")- stale.unlink(missing_ok=True)-- baseten_api_key = baseten_api_key or os.environ.get("BASETEN_API_KEY", "")- if not baseten_api_key:- raise RuntimeError(- "BASETEN_API_KEY is not set (pass it from Django settings or add to Modal overmind-inference secret)"- )-- project_id, baseten_job_id = remote_id.split(":", 1)- headers = {"Authorization": f"Bearer {baseten_api_key}"}- api_base = "https://api.baseten.co"-- # TRAINING_JOB_COMPLETED alone is not enough: Baseten surfaces tiny config files- # in the listing before the large weight shards land, so archiving mid-sync writes- # a metadata-only zip. The sync status must be checked too.- job_resp = requests.get(- f"{api_base}/v1/training_projects/{project_id}/jobs/{baseten_job_id}",- headers=headers,- timeout=30,- )- job_resp.raise_for_status()- job_data = job_resp.json().get("training_job", {})- job_status = job_data.get("current_status", "")- if job_status != "TRAINING_JOB_COMPLETED":- raise ValueError(f"Baseten job {baseten_job_id} not completed (status={job_status})")- sync_status = job_data.get("checkpoint_sync_status", "")- if sync_status != "COMPLETED":- raise ValueError(- f"Baseten job {baseten_job_id} checkpoint sync not done "- f"(checkpoint_sync_status={sync_status!r}) — retry later"- )-- print(f"[Baseten→S3] Listing checkpoint files for {baseten_job_id}")- all_files: list[dict] = []- page_token = 0- while True:- resp = requests.get(- f"{api_base}/v1/training_projects/{project_id}/jobs/{baseten_job_id}/checkpoint_files",- headers=headers,- params={"page_size": 500, "page_token": page_token},- timeout=30,- )- resp.raise_for_status()- data = resp.json()- all_files.extend(data.get("presigned_urls", []))- next_token = data.get("next_page_token")- if next_token is None:- break- page_token = next_token-- if not all_files:- raise RuntimeError(f"No checkpoint files found for Baseten job {baseten_job_id}")-- # Two real artifact layouts: adapter at the listing root, or ONLY nested- # checkpoint-N/ dirs when the root save did not sync — then pull just the- # highest-step checkpoint, since each carries a full adapter_model.safetensors.- # A root config file is NOT proof the root artifact is usable, so an actual root- # weight file is required before the nested fallback is skipped.- rel_names = [f["relative_file_name"] for f in all_files]- root_names = {r for r in rel_names if "/" not in r}- root_has_config = any(r in ("adapter_config.json", "config.json") for r in root_names)- root_has_weights = any(- n == "adapter_model.safetensors" or n == "pytorch_model.bin" or n.startswith("model")- for n in root_names- if n.endswith((".safetensors", ".bin"))- )- root_has_artifact = root_has_config and root_has_weights- ckpt_dirs = {r.split("/")[0] for r in rel_names if r.split("/")[0].startswith("checkpoint-")}- latest_ckpt = max(ckpt_dirs, key=lambda n: _checkpoint_step(Path(n))) if ckpt_dirs else None- # The fallback flattens the nested dir onto the local staging root, because every- # downstream check reads the root, not a nested checkpoint-N/.- use_nested_ckpt = not root_has_artifact and latest_ckpt is not None- if use_nested_ckpt:- print(f"[Baseten→S3] Root artifact incomplete — using nested {latest_ckpt}/ instead")-- # A LoRA job needs only the adapter + tokenizer, so the large base-model shards TRL- # may have copied are skipped. A full-SFT job's trained weights ARE the- # model*.safetensors, so those must be pulled. Optimizer state is skipped either way.- listing_is_lora = any(Path(r).name == "adapter_config.json" for r in rel_names)- skip_patterns = (- ("model.safetensors", "optimizer.pt", "model-")- if listing_is_lora- else ("optimizer.pt", "scheduler.pt", "rng_state")- )- always_download = (- "adapter_config.json",- "adapter_model.safetensors",- "tokenizer_config.json",- "special_tokens_map.json",- "tokenizer.json",- "tokenizer.model",- "trainer_state.json",- )- print(f"[Baseten→S3] Checkpoint type: {'LoRA adapter' if listing_is_lora else 'full SFT'}")-- local_dir = Path(f"/tmp/baseten_ckpt_{job_id}")- if local_dir.exists():- shutil.rmtree(local_dir)- local_dir.mkdir(parents=True, exist_ok=True)-- for file_info in all_files:- rel = file_info["relative_file_name"]-- if use_nested_ckpt:- prefix = f"{latest_ckpt}/"- if not rel.startswith(prefix):- continue # skip root-level (incomplete) and other checkpoints- rel = rel[len(prefix) :] # flatten onto local root- elif "/" not in rel:- pass # root-level artifact path — use as-is- else:- continue # root artifact is usable; ignore other checkpoint-N/ dirs-- fname = Path(rel).name- size_mb = file_info.get("size_bytes", 0) / 1e6-- is_critical = any(fname == a for a in always_download)- is_large = any(fname.startswith(p) for p in skip_patterns)-- if is_large and not is_critical:- print(f"[Baseten→S3] (skip large) {rel} ({size_mb:.0f} MB)")- continue-- dest = local_dir / rel- dest.parent.mkdir(parents=True, exist_ok=True)- r = requests.get(file_info["url"], timeout=600, stream=True)- r.raise_for_status()- with dest.open("wb") as f:- for chunk in r.iter_content(chunk_size=4 << 20):- f.write(chunk)- print(f"[Baseten→S3] ✓ {rel} ({dest.stat().st_size / 1e3:.0f} KB)")-- if not any(local_dir.iterdir()):- raise RuntimeError(f"No files staged for Baseten job {baseten_job_id} — nothing to archive")-- # Never write a metadata-only zip: Celery retries until the listing includes real- # weights, or the nested-checkpoint fallback finds them.- if not _dir_has_weights(local_dir):- raise RuntimeError(- f"Baseten job {baseten_job_id} staged without weight files "- f"(files: {sorted(p.name for p in local_dir.iterdir())}) — "- "checkpoint listing incomplete, retry later"- )-- zip_path = Path(f"/tmp/{job_id}_checkpoint.zip")- _zip_directory(local_dir, zip_path)-- print(f"[Baseten→S3] Fetching full job log for {baseten_job_id}")- log_text = _fetch_baseten_logs_text(project_id, baseten_job_id, headers, api_base)-- _archive_to_s3(user_id, job_id, zip_path, log_text, job_result or {})- shutil.rmtree(local_dir, ignore_errors=True)- zip_path.unlink(missing_ok=True)- return {"job_id": job_id, "skipped": False}--@app.function(image=download_image,timeout=30 * 60,@@ -1257,7 +1008,7 @@ def download_checkpoint_from_s3(cache_key: str,merge_base_model: str = "",) -> dict:- """The common download path for both the baseten and modal providers: once a checkpoint is+ """The common download path for every archived checkpoint: once a checkpoint isarchived, the FP8 pipeline no longer cares which provider trained it.``job_id``/``user_id`` address the S3 archive; ``cache_key`` is the SEPARATE FP8-cache keydiff --git a/overbae/models/finetuning.py b/overbae/models/finetuning.pyindex 8be3eca9..75e2c147 100644--- a/overbae/models/finetuning.py+++ b/overbae/models/finetuning.py@@ -74,12 +74,10 @@ class FinetuningJob(models.Model):LARGE = "large"class Provider(models.TextChoices):- TOGETHER_AI = "together_ai"# Legacy providers — retired backends kept so existing job rows render;- # new submissions only go to TOGETHER_AI, BASETEN, or MODAL.+ # new submissions only go to MODAL.NEBIUS = "nebius"TINKER = "tinker"- BASETEN = "baseten"MODAL = "modal"class SplitMethod(models.TextChoices):@@ -185,7 +183,7 @@ class FinetuningJob(models.Model):model_tier = models.CharField(max_length=20, choices=Tier.choices, blank=True, default="")# Set once on submission; never changes.- provider = models.CharField(max_length=20, choices=Provider.choices, default=Provider.BASETEN)+ provider = models.CharField(max_length=20, choices=Provider.choices, default=Provider.MODAL)base_model = models.CharField(max_length=255)preparation = models.ForeignKey(@@ -232,8 +230,7 @@ class FinetuningJob(models.Model):celery_task_id = models.CharField(max_length=255, blank=True, default="")- # Per-job USD from Baseten's GET /v1/billing/usage_summary breakdown item- # subtotal; credits there are account-level only.+ # Recorded training charge in USD.cost_usd = models.DecimalField(max_digits=12, decimal_places=4, null=True, blank=True)billed_minutes = models.PositiveIntegerField(null=True, blank=True)cost_synced_at = models.DateTimeField(null=True, blank=True)diff --git a/overbae/models/innermind.py b/overbae/models/innermind.pyindex 55967b9f..501f6491 100644--- a/overbae/models/innermind.py+++ b/overbae/models/innermind.py@@ -21,7 +21,6 @@ class ModelRef(models.Model):OPENAI = "openai"ANTHROPIC = "anthropic"GEMINI = "gemini"- TOGETHER = "together"CUSTOM = "custom"id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)@@ -35,7 +34,7 @@ class ModelRef(models.Model):model_id = models.CharField(max_length=512)# Empty => the provider default.base_url = models.CharField(max_length=1024, blank=True, default="")- # Env var name holding the API key, e.g. "TOGETHER_API_KEY" — secrets are+ # Env var name holding the API key, e.g. "INFERENCE_API_KEY" — secrets are# never stored in the DB.api_key_ref = models.CharField(max_length=128, blank=True, default="")# Extra completion kwargs forwarded to LiteLLM (temperature, max_tokens…).diff --git a/overbae/services/baseten_billing.py b/overbae/services/baseten_billing.pydeleted file mode 100644index 96102529..00000000--- a/overbae/services/baseten_billing.py+++ /dev/null@@ -1,255 +0,0 @@-"""Baseten training cost sync from the management billing API.--Fetches ``GET /v1/billing/usage_summary`` (max 31-day windows), matches-``TRAINING_JOB`` breakdown items to :class:`FinetuningJob` via-``remote_job_id`` suffix, and stores raw per-job compute USD-(``cost_usd`` / ``billed_minutes``). Account-level credits are ignored.-"""--from __future__ import annotations--import logging-from collections import defaultdict-from dataclasses import dataclass-from datetime import UTC, datetime, timedelta-from decimal import Decimal, InvalidOperation-from typing import Any-from uuid import UUID--import requests-from django.conf import settings-from django.db.models import Count, Q, Sum-from django.utils import timezone--from overbae.models import BillingService-from overbae.models.finetuning import FinetuningJob-from overbae.services.billing_ledger import charge_credits--logger = logging.getLogger(__name__)--_API_BASE = "https://api.baseten.co"-EARLIEST_QUERYABLE = datetime(2026, 1, 1, tzinfo=UTC)-# Baseten rejects ranges longer than 31 days inclusive — use 30-day steps.-_MAX_CHUNK = timedelta(days=30)-_TRAINING_JOB = "TRAINING_JOB"---@dataclass(frozen=True)-class _ResourceCost:- cost_usd: Decimal- billed_minutes: int---def _api_key() -> str:- return getattr(settings, "BASETEN_API_KEY", "") or ""---def _parse_money(value: Any) -> Decimal:- if value is None:- return Decimal("0")- try:- return Decimal(str(value))- except (InvalidOperation, ValueError, TypeError):- return Decimal("0")---def _baseten_job_id(remote_job_id: str) -> str | None:- """Extract Baseten job id from ``{project_id}:{job_id}``."""- if not remote_job_id or ":" not in remote_job_id:- return None- _, job_id = remote_job_id.split(":", 1)- return job_id or None---def usage_summary_chunks(- since: datetime,- until: datetime,-) -> list[tuple[datetime, datetime]]:- """Split ``[since, until]`` into ≤31-day windows, clamped to earliest date."""- if since.tzinfo is None:- since = since.replace(tzinfo=UTC)- if until.tzinfo is None:- until = until.replace(tzinfo=UTC)- since = max(since, EARLIEST_QUERYABLE)- if until <= since:- return []- chunks: list[tuple[datetime, datetime]] = []- cursor = since- while cursor < until:- end = min(cursor + _MAX_CHUNK, until)- chunks.append((cursor, end))- cursor = end- return chunks---def fetch_usage_summary(*, start: datetime, end: datetime) -> dict[str, Any]:- key = _api_key()- if not key:- raise RuntimeError("BASETEN_API_KEY is not configured in Django settings.")- resp = requests.get(- f"{_API_BASE}/v1/billing/usage_summary",- headers={"Authorization": f"Bearer {key}"},- params={- "start_date": start.astimezone(UTC).isoformat().replace("+00:00", "Z"),- "end_date": end.astimezone(UTC).isoformat().replace("+00:00", "Z"),- },- timeout=60,- )- resp.raise_for_status()- return resp.json()---def accumulate_training_costs(summaries: list[dict[str, Any]]) -> dict[str, _ResourceCost]:- """Sum training breakdown items across summaries, keyed by billable_resource.id."""- totals: dict[str, list[Decimal | int]] = defaultdict(lambda: [Decimal("0"), 0])- for summary in summaries:- training = summary.get("training_usage") or {}- for item in training.get("breakdown") or []:- resource = item.get("billable_resource") or {}- if resource.get("kind") != _TRAINING_JOB:- continue- rid = resource.get("id")- if not rid:- continue- totals[str(rid)][0] += _parse_money(item.get("subtotal"))- totals[str(rid)][1] += int(item.get("minutes") or 0)- return {- rid: _ResourceCost(cost_usd=vals[0], billed_minutes=int(vals[1]))- for rid, vals in totals.items()- }---def _eligible_jobs_qs():- return FinetuningJob.objects.filter(- provider=FinetuningJob.Provider.BASETEN,- ).exclude(remote_job_id="")---def sync_finetuning_job_costs(*, since: datetime, until: datetime | None = None) -> dict[str, int]:- until = until or timezone.now()- if not _api_key():- logger.warning("BASETEN_API_KEY unset — skipping finetuning cost sync")- return {"fetched": 0, "matched": 0, "updated": 0, "chunks": 0}-- chunks = usage_summary_chunks(since, until)- if not chunks:- return {"fetched": 0, "matched": 0, "updated": 0, "chunks": 0}-- summaries: list[dict[str, Any]] = []- for start, end in chunks:- try:- summaries.append(fetch_usage_summary(start=start, end=end))- except requests.RequestException:- logger.exception(- "Baseten usage_summary failed for %s → %s",- start.isoformat(),- end.isoformat(),- )- raise-- costs = accumulate_training_costs(summaries)- if not costs:- return {"fetched": 0, "matched": 0, "updated": 0, "chunks": len(chunks)}-- jobs = list(_eligible_jobs_qs().select_related("triggered_by"))- by_remote: dict[str, list] = defaultdict(list)- for job in jobs:- rid = _baseten_job_id(job.remote_job_id)- if rid:- by_remote[rid].append(job)-- now = timezone.now()- matched = 0- updated = 0- for resource_id, cost in costs.items():- targets = by_remote.get(resource_id) or []- if not targets:- continue- matched += len(targets)- for job in targets:- previous = job.cost_usd or Decimal("0")- job.cost_usd = cost.cost_usd- job.billed_minutes = cost.billed_minutes- job.cost_synced_at = now- job.save(update_fields=["cost_usd", "billed_minutes", "cost_synced_at", "updated_at"])- delta = cost.cost_usd - previous- if delta > 0 and job.triggered_by_id:- charge_credits(- job.triggered_by,- delta,- BillingService.FINETUNING_JOB,- project_id=job.project_id,- idempotency_key=f"finetuning-job:{job.id}:{cost.cost_usd}",- metadata={- "job_id": str(job.id),- "cost_usd": str(cost.cost_usd),- "delta": str(delta),- },- )- updated += 1-- return {- "fetched": len(costs),- "matched": matched,- "updated": updated,- "chunks": len(chunks),- }---def sync_recent_finetuning_costs(*, lookback_days: int = 14) -> dict[str, int]:- """Covers at least ``lookback_days``, and extends back to the earliest start of any- active or recently completed job so multi-week runs are not undercounted.- """- now = timezone.now()- floor = max(now - timedelta(days=lookback_days), EARLIEST_QUERYABLE)- terminal = {- FinetuningJob.Status.SUCCEEDED,- FinetuningJob.Status.FAILED,- FinetuningJob.Status.CANCELLED,- }- qs = _eligible_jobs_qs().filter(- Q(completed_at__gte=floor)- | Q(started_at__gte=floor)- | Q(created_at__gte=floor)- | ~Q(status__in=terminal)- )- starts: list[datetime] = []- for job in qs.only("started_at", "created_at").iterator():- start = job.started_at or job.created_at- if start is not None:- starts.append(start)- since = min([floor, *starts]) if starts else floor- since = max(since, EARLIEST_QUERYABLE)- return sync_finetuning_job_costs(since=since, until=now)---def sync_job_cost_window(job) -> dict[str, int] | None:- if getattr(job, "provider", None) != FinetuningJob.Provider.BASETEN:- return None- if not getattr(job, "remote_job_id", None):- return None- since = job.started_at or job.created_at or timezone.now()- return sync_finetuning_job_costs(since=since, until=timezone.now())---def project_finetuning_costs(project_id: UUID | str) -> dict[str, Any]:- qs = FinetuningJob.objects.filter(- project_id=project_id,- provider=FinetuningJob.Provider.BASETEN,- )- agg = qs.aggregate(- job_count=Count("id"),- jobs_with_cost=Count("id", filter=Q(cost_usd__isnull=False)),- cost_usd=Sum("cost_usd"),- billed_minutes=Sum("billed_minutes"),- )- job_count = agg["job_count"] or 0- jobs_with_cost = agg["jobs_with_cost"] or 0- return {- "project_id": str(project_id),- "job_count": job_count,- "jobs_with_cost": jobs_with_cost,- "jobs_missing_cost": job_count - jobs_with_cost,- "cost_usd": agg["cost_usd"],- "billed_minutes": agg["billed_minutes"] or 0,- }diff --git a/overbae/services/decision_providers.py b/overbae/services/decision_providers.pyindex 7e988cb2..c2e74f88 100644--- a/overbae/services/decision_providers.py+++ b/overbae/services/decision_providers.py@@ -56,7 +56,7 @@ def catalog(project):"kind": "foundation","qualification": "catalog_eligible",}- for model, config in get_all_models_by_backend("baseten", include_disabled=False).items()+ for model, config in get_all_models_by_backend("modal", include_disabled=False).items()if get_unsloth_image(model) in NATIVE_FOUNDATION_STACKS]options.extend(diff --git a/overbae/services/deployment.py b/overbae/services/deployment.pyindex a78c5855..fc56b014 100644--- a/overbae/services/deployment.py+++ b/overbae/services/deployment.py@@ -9,7 +9,6 @@ from datetime import timedeltaimport modalfrom asgiref.sync import async_to_sync-from django.conf import settingsfrom django.core.cache import cachefrom django.db import transactionfrom django.db.models import Q@@ -462,10 +461,8 @@ def _remote_operation(deployed: DeployedModel):"remote_job_id": job.remote_job_id,"model_id": deployed.model_id,"provider": job.provider,- "baseten_api_key": getattr(settings, "BASETEN_API_KEY", "") or "","user_id": str(job.triggered_by_id) if job.triggered_by_id else "","job_id": str(job.id),- "job_result": job.result if isinstance(job.result, dict) else {},"quantize": cfg.get("fp8_supported", True),"merge_base_model": base,"params_b": float(cfg.get("total_params_b") or 0),diff --git a/overbae/services/finetuning_catalog.py b/overbae/services/finetuning_catalog.pyindex 8b496199..853febda 100644--- a/overbae/services/finetuning_catalog.py+++ b/overbae/services/finetuning_catalog.py@@ -7,35 +7,23 @@ from typing import Anyfrom django.conf import settingsfrom modal_shared.training_monitoring import capabilities as monitoring_capabilities-from overbae.modal.model_registry import TIER_ORDER, baseten_finetuning_catalog+from overbae.modal.model_registry import TIER_ORDER, finetuning_catalogfrom overbae.services import model_catalog-from overbae.services.recommendation.constraints import eligible_models-def fetch_finetuning_model_catalog(- *, has_tool_calling: bool = False, max_context: int | None = None-) -> dict[str, Any]:+def fetch_finetuning_model_catalog(*, has_tool_calling: bool = False) -> dict[str, Any]:"""Return the catalog payload shared by the frontend API and MCP."""- backend = getattr(settings, "FINETUNING_BACKEND", "baseten")-- if backend in ("baseten", "modal"):- # Modal reuses the Baseten catalog verbatim; models.json has no duplicate rows.- catalog = baseten_finetuning_catalog(include_disabled=True)- if has_tool_calling:- catalog = {- tier: [- model- for model in models- if model.get("supports_tool_calling") and not model.get("disabled")- ]- for tier, models in catalog.items()- }- max_context = None- else:- catalog, _excluded = eligible_models(- has_tool_calling=has_tool_calling,- max_row_tokens=max_context,- )+ backend = getattr(settings, "FINETUNING_BACKEND", "modal")+ catalog = finetuning_catalog(backend, include_disabled=True)+ if has_tool_calling:+ catalog = {+ tier: [+ model+ for model in models+ if model.get("supports_tool_calling") and not model.get("disabled")+ ]+ for tier, models in catalog.items()+ }upstream = model_catalog.fetch_model_catalog()catalog = {tier: [@@ -50,6 +38,5 @@ def fetch_finetuning_model_catalog("tiers": [tier for tier in TIER_ORDER if tier in catalog],"models": catalog,"has_tool_calling": has_tool_calling,- "max_context": max_context,"monitoring": monitoring_capabilities(backend),}diff --git a/overbae/services/finetuning_checkpoints.py b/overbae/services/finetuning_checkpoints.pyindex adc17430..1ecb72d9 100644--- a/overbae/services/finetuning_checkpoints.py+++ b/overbae/services/finetuning_checkpoints.py@@ -62,7 +62,7 @@ def checkpoint_archive_exists(finetuning_job) -> bool:def get_checkpoint_download_url(finetuning_job) -> dict | None:"""Absent or unsupported archives return None; storage failures remain errors."""- if finetuning_job.provider not in ("baseten", "modal"):+ if finetuning_job.provider != "modal":return Nonebucket = getattr(settings, "AWS_BUCKET_NAME", "") or ""if not bucket:diff --git a/overbae/services/finetuning_eval.py b/overbae/services/finetuning_eval.pyindex e6ddd730..53e26083 100644--- a/overbae/services/finetuning_eval.py+++ b/overbae/services/finetuning_eval.py@@ -26,12 +26,12 @@ logger = logging.getLogger(__name__)def _is_self_hosted(job) -> bool:- """Baseten and Modal ship weight-only artifacts with no provider chat endpoint, so- their evals route through OUR Modal deployment. Together serves its own fine-tunes.+ """Modal ships weight-only artifacts with no provider chat endpoint, so its evals+ route through OUR Modal deployment."""from overbae.models import FinetuningJob- return job.provider in (FinetuningJob.Provider.BASETEN, FinetuningJob.Provider.MODAL)+ return job.provider == FinetuningJob.Provider.MODALdef job_wants_evals(job) -> bool:@@ -741,7 +741,7 @@ def _provider_routing(job, *, kind: str, target: _BaselineTarget | None) -> tupl"INFERENCE_API_URL is not configured — cannot eval Modal deployments")return ModelRef.Provider.CUSTOM, f"{gateway}/v1", "INFERENCE_API_KEY"- return ModelRef.Provider.TOGETHER, "", "TOGETHER_API_KEY"+ raise RuntimeError(f"{job.provider} jobs have no evaluation route")def _get_or_create_model_ref(diff --git a/overbae/services/finetuning_policy.py b/overbae/services/finetuning_policy.pyindex 3336cf6f..0917562a 100644--- a/overbae/services/finetuning_policy.py+++ b/overbae/services/finetuning_policy.py@@ -1,6 +1,6 @@"""Training policy: every fine-tuning heuristic in one module.-Shared by the recommender (pre-launch wizard) and the Baseten runner (submission+Shared by the recommender (pre-launch wizard) and the Modal runner (submissiontime) so the values the wizard shows are the values the training script receives —no silent recommendation → job → config drops."""@@ -37,8 +37,8 @@ TRAINING_SEED = 42PACKING_MIN_EXAMPLES = 1000PACKING_MAX_FILL = 0.25-# Baseten training GPUs (VRAM in GB) — hardware facts for the pre-submission-# memory guardrail, mirroring BasetenRunner's GPU table.+# Training GPUs (VRAM in GB) — hardware facts for the pre-submission memory+# guardrail, mirroring ModalRunner's GPU table.TRAINING_GPU_VRAM_GB: dict[str, float] = {"H100": 80.0, "H200": 141.0}_BF16_BYTES_PER_PARAM = 2# QLoRA 4-bit weight floor (Unsloth docs: 70B QLoRA ≈41 GB ≈0.59 B/param with@@ -168,7 +168,7 @@ def openai_batch_size(return min(max(min_batch, raw), max_batch)-def baseten_context_length(+def snap_context_length(needed_tokens: int = 0,*,model_max: int | None = None,@@ -180,7 +180,7 @@ def baseten_context_length(training targets. Buckets and headroom come from models.json, never from code.Raises when the model cannot cover the dataset's longest row (plus headroom)."""- policy = get_training_context_policy("baseten")+ policy = get_training_context_policy("modal")buckets: list[int] = sorted(int(b) for b in policy["context_buckets"])need = int(needed_tokens or 0)if need > 0:@@ -207,7 +207,7 @@ def validate_requested_context_length(context_length: int, *, model_max: int | N)if not 128 <= context_length <= 2_000_000:raise InputValidationError("Context length must be between 128 and 2,000,000 tokens.")- supported = baseten_context_length(model_max=model_max, requested=context_length)+ supported = snap_context_length(model_max=model_max, requested=context_length)if supported != context_length:raise InputValidationError(f"context_length={context_length} is unsupported; choose {supported} "@@ -224,10 +224,10 @@ def estimated_training_context_length(# Estimates size the first exact preprocessing pass; only tokenization can reject data.target = max(0, estimated_tokens)if target:- target += context_headroom("baseten")+ target += context_headroom("modal")if model_max:target = min(target, model_max)- return baseten_context_length(model_max=model_max, requested=max(target, requested or 0))+ return snap_context_length(model_max=model_max, requested=max(target, requested or 0))def should_pack(num_examples: int, avg_row_tokens: int, context_length: int) -> bool:@@ -246,10 +246,10 @@ class TrainingPlanError(ValueError):@dataclass-class BasetenTrainingPlan:- """Everything the Baseten training script is parameterised with — the single seam- between job hyperparameters and the env vars pushed to Baseten. ``notes`` records- every gap-fill and clamp.+class TrainingPlan:+ """Everything the training script is parameterised with — the single seam+ between job hyperparameters and the env vars pushed to the training worker. ``notes``+ records every gap-fill and clamp."""context_length: int@@ -370,7 +370,7 @@ def _resolve_memory_plan(return True, qlora_budget-def derive_baseten_training_plan(+def derive_training_plan(*,hyperparameters: dict[str, Any] | None,num_train_examples: int,@@ -383,13 +383,13 @@ def derive_baseten_training_plan(gpu_count: int = 1,model_id: str | None = None,hidden_size: int = 0,-) -> BasetenTrainingPlan:- """Derive the full Baseten training plan from data + catalog context.+) -> TrainingPlan:+ """Derive the full training plan from data + catalog context.Explicit hyperparameters are preserved or rejected; anything absentis gap-filled from the same heuristics the recommender uses, never a hardcodedconstant. Raises :class:`TrainingPlanError` when the combination cannot work, so a- job fails pre-submission instead of mid-run on Baseten.+ job fails pre-submission instead of mid-run.``hidden_size`` enables the activation token budget (0 = weight-only checks)."""@@ -412,7 +412,7 @@ def derive_baseten_training_plan(tt_name = str(training_type.get("type") or "Lora")if tt_name not in ("Lora", "Full"):raise TrainingPlanError(- f"Unknown training_type={tt_name!r}; the Baseten training script "+ f"Unknown training_type={tt_name!r}; the training script ""implements 'Lora' and 'Full' fine-tuning.")use_lora = tt_name == "Lora"@@ -430,7 +430,7 @@ def derive_baseten_training_plan("would be truncated, corrupting training targets.")requested_ctx = int(hp.get("context_length") or 0) or None- context_length = baseten_context_length(+ context_length = snap_context_length(max_row_tokens, model_max=model_max_context, requested=requested_ctx)@@ -598,7 +598,7 @@ def derive_baseten_training_plan(if packing:notes.append(f"packing enabled (avg row ≈{avg_row_tokens} tokens ≪ ctx {context_length})")- return BasetenTrainingPlan(+ return TrainingPlan(context_length=context_length,n_epochs=n_epochs,batch_size=batch_size,diff --git a/overbae/services/finetuning_pricing.py b/overbae/services/finetuning_pricing.pyindex de490fb0..6dc09fc0 100644--- a/overbae/services/finetuning_pricing.py+++ b/overbae/services/finetuning_pricing.py@@ -1,7 +1,5 @@"""Fine-tuning cost and duration estimation.- Together: cost = trained_tokens × price_per_million / 1e6- Baseten: cost = GPU count × billed minutes × per-GPU-minute rateModal: cost = GPU count × estimated seconds × per-GPU-second ratetrained_tokens = dataset_tokens × n_epochs@@ -15,42 +13,26 @@ from __future__ import annotationsimport mathfrom typing import Any-# Source: https://www.together.ai/pricing (retrieved 2026-07-13).-# $/1M trained tokens, tiered by base-model total parameter count.-# (max_params_b, lora_price, full_price)-_TOGETHER_SFT_TIERS: list[tuple[float, float, float]] = [- (16.0, 0.48, 0.54),- (69.0, 1.50, 1.65),- (100.0, 2.90, 3.20),-]-# Together applies a $4.00 minimum charge per fine-tuning job (same source).-_TOGETHER_MIN_CHARGE_USD = 4.00--# Source: https://www.baseten.co/pricing/ (retrieved 2026-07-17). Baseten bills-# training per GPU-minute of active compute (H100 80GB = $0.10833/min) — there is-# no per-token rate, so cost = GPU count × minutes × rate.-_BASETEN_H100_USD_PER_MIN = 0.10833# Source: https://modal.com/pricing (retrieved 2026-10-02). GPU compute only;# CPU, host memory, storage and provider rate multipliers are additional._MODAL_H100_USD_PER_SECOND = 0.001097-# Mirrors BasetenRunner._GPU_TABLE (finetuning_runner.py): LoRA SFT on+# Mirrors ModalRunner._GPU_TABLE (finetuning_runner.py): LoRA SFT on# (max_params_b, gpu_count) H100s. ≤72B is 1× via QLoRA.-_BASETEN_GPU_COUNT_TIERS: list[tuple[float, int]] = [+_GPU_COUNT_TIERS: list[tuple[float, int]] = [(32.0, 1),(72.0, 1),(float("inf"), 4),]-def _baseten_gpu_count(total_params_b: float) -> int:- for max_params, count in _BASETEN_GPU_COUNT_TIERS:+def _gpu_count(total_params_b: float) -> int:+ for max_params, count in _GPU_COUNT_TIERS:if total_params_b <= max_params:return countreturn 4-# Peak dense BF16 from the NVIDIA H100 SXM datasheet; Together's fine-tuning-# service runs on H100 clusters (docs.together.ai).+# Peak dense BF16 from the NVIDIA H100 SXM datasheet._H100_PEAK_BF16_TFLOPS = 989.0# Typical model-FLOPs-utilisation for managed SFT pipelines (~30–40%)._ASSUMED_MFU = 0.35@@ -64,23 +46,6 @@ _FLOPS_PER_PARAM_TOKEN_FULL = 6.0_FLOPS_PER_PARAM_TOKEN_LORA = 4.0-def training_price_per_million(- total_params_b: float,- *,- use_lora: bool,- backend: str,-) -> float | None:- """$/1M trained tokens for SFT, or None when unpriced. Baseten bills per- GPU-minute rather than per token — see estimate_training_cost.- """- if backend != "together":- return None- for max_params, lora_price, full_price in _TOGETHER_SFT_TIERS:- if total_params_b <= max_params:- return lora_price if use_lora else full_price- return None # >100B models are individually priced; none are in our catalog--def estimate_training_cost(trained_tokens: int,*,@@ -91,44 +56,18 @@ def estimate_training_cost("""Cost breakdown, or None when the backend is unpriced. ``trained_tokens`` isdataset tokens × epochs — the quantity providers bill."""- if backend in ("baseten", "modal"):- if trained_tokens <= 0:- return None- gpu_count = _baseten_gpu_count(total_params_b)- time_s = estimate_training_time_s(- trained_tokens, total_params_b=total_params_b, use_lora=use_lora- )- billed_minutes = time_s / 60 if backend == "modal" else math.ceil(time_s / 60)- gpu_cost = (- time_s * _MODAL_H100_USD_PER_SECOND- if backend == "modal"- else billed_minutes * _BASETEN_H100_USD_PER_MIN- )- return {- "usd": round(gpu_cost * gpu_count, 4),- "price_per_million_usd": None,- "trained_tokens": trained_tokens,- "minimum_applied": False,- "gpu_type": "H100",- "gpu_count": gpu_count,- "billed_minutes": billed_minutes,- }- price = training_price_per_million(- total_params_b,- use_lora=use_lora,- backend=backend,- )- if price is None or trained_tokens <= 0:+ if backend != "modal" or trained_tokens <= 0:return None- raw_usd = trained_tokens * price / 1_000_000- minimum_applied = backend == "together" and raw_usd < _TOGETHER_MIN_CHARGE_USD- usd = _TOGETHER_MIN_CHARGE_USD if minimum_applied else raw_usd+ gpu_count = _gpu_count(total_params_b)+ time_s = estimate_training_time_s(+ trained_tokens, total_params_b=total_params_b, use_lora=use_lora+ )return {- # 4 dp so small datasets don't round to a misleading $0.00.- "usd": round(usd, 4),- "price_per_million_usd": price,+ "usd": round(time_s * _MODAL_H100_USD_PER_SECOND * gpu_count, 4),"trained_tokens": trained_tokens,- "minimum_applied": minimum_applied,+ "gpu_type": "H100",+ "gpu_count": gpu_count,+ "billed_minutes": time_s / 60,}diff --git a/overbae/services/finetuning_runner.py b/overbae/services/finetuning_runner.pyindex a056f082..85317427 100644--- a/overbae/services/finetuning_runner.py+++ b/overbae/services/finetuning_runner.py@@ -15,16 +15,15 @@ import timefrom abc import ABC, abstractmethodfrom dataclasses import dataclass, fieldfrom datetime import datetime-from pathlib import Pathfrom typing import Any, ClassVarfrom django.conf import settingsfrom modal_shared.decisions import DECISION_OBJECTIVESfrom overbae.services.finetuning_policy import (- BasetenTrainingPlan,- baseten_context_length, # noqa: F401 — re-exported; tests/consumers import it from here- derive_baseten_training_plan,+ TrainingPlan,+ derive_training_plan,+ snap_context_length,)from overbae.services.training_policies import profile_optionsfrom overbae.services.training_preparation import ready_for_job@@ -32,18 +31,6 @@ from overbae.services.training_transfer import stage_datalogger = logging.getLogger(__name__)-# Together rejects suffixes with spaces, punctuation, etc. — only URL-safe chars.-_TOGETHER_SUFFIX_MAX_LEN = 40-_UNSAFE_SUFFIX_RE = re.compile(r"[^a-zA-Z0-9_-]+")---def together_suffix(name: str | None, *, fallback: str) -> str:- raw = (name or "").strip() or fallback.strip()- slug = _UNSAFE_SUFFIX_RE.sub("-", raw).strip("-").lower()- if not slug:- slug = fallback.strip("-").lower() or "ft"- return slug[:_TOGETHER_SUFFIX_MAX_LEN]-def resolve_modal_job_state(meta_status: str,@@ -126,7 +113,7 @@ class PollSnapshot:tokens_per_second: float | None = Nonetokens_processed: int | None = None- # Step-based progress (Baseten; Together leaves these unset).+ # Step-based progress.trained_steps: int | None = Nonephase: str = ""@@ -152,20 +139,19 @@ class PollSnapshot:"""``[{step, value}, …]``."""token_accuracy_series: list[dict[str, Any]] = field(default_factory=list)- """``[{step, train?, eval?}, …]`` — Baseten emits it from TRL's SFTTrainer;- Together does not expose it."""+ """``[{step, train?, eval?}, …]``."""checkpoints: list[dict[str, Any]] = field(default_factory=list)"""Normalised checkpoint rows for the monitor tables."""- # Baseten extended live metrics+ # Extended live metricslearning_rate: float | None = Nonetoken_accuracy: float | None = Noneeval_token_accuracy: float | None = Nonecurrent_epoch: float | None = Noneeta_s: float | None = None- # Full step history for live charts (Baseten only)+ # Full step history for live charts# Each entry: {step, epoch, train_loss, token_accuracy, lr}metrics_history: list[dict] = field(default_factory=list)# Each eval entry: {step, epoch, eval_loss, eval_token_accuracy}@@ -305,7 +291,7 @@ def filter_activity_logs(logs: list[dict], cap: int = MAX_ACTIVITY_LINES) -> lis"""The last ``cap`` meaningful operational lines for the live-activity feed.Filtering happens server-side so the frontend only receives display-ready lines.- Timestamps normalise to epoch ms — Baseten emits nanosecond strings.+ Timestamps normalise to epoch ms; providers may emit nanosecond strings."""out: list[dict] = []for entry in logs:@@ -385,14 +371,12 @@ def lifecycle_stage(status: str | None, progress: dict | None) -> str:# Backend names must never reach the frontend — error strings and log lines-# can echo them from raw exceptions/provider APIs (e.g. "Baseten API error",+# can echo them from raw exceptions/provider APIs (e.g. "Modal function failed",# "NEBIUS_API_KEY not set"). Boundaries are letter-only (not \b, which treats# `_` as a word char) so "NEBIUS_API_KEY" still matches. ``modal`` alone gets-# an extra ``(?!_)`` so package names like ``modal_shared`` stay intact. Order-# matters: longer/more-specific phrases first so "Together AI" doesn't leave a-# dangling "AI".+# an extra ``(?!_)`` so package names like ``modal_shared`` stay intact._BACKEND_NAME_RE = re.compile(- r"(?<![A-Za-z])(together\s*ai|baseten|nebius|modal(?!_))(?![A-Za-z])",+ r"(?<![A-Za-z])(nebius|modal(?!_))(?![A-Za-z])",re.IGNORECASE,)# GPU SKUs in activity copy ("Pre-warming GPU (L4)") — infra detail, not product.@@ -447,35 +431,6 @@ def sanitize_job_error(text: str) -> str:return scrubbed[:300]-def parse_download_stage(logs: list[dict]) -> tuple[str, dict[str, Any] | None]:- """``(stage, download)`` from the last ``BT_STAGE`` / ``BT_DOWNLOAD`` lines.- Providers that emit neither yield ``("", None)``.- """- stage = ""- download: dict[str, Any] | None = None- for entry in logs:- msg = (entry.get("message") or "").strip()- if msg.startswith("BT_STAGE "):- try:- rec = json.loads(msg[len("BT_STAGE ") :])- except ValueError:- continue- s = str(rec.get("stage") or "")- if s:- stage = s- elif msg.startswith("BT_DOWNLOAD "):- try:- rec = json.loads(msg[len("BT_DOWNLOAD ") :])- except ValueError:- continue- download = {- "pct": rec.get("pct"),- "downloaded_gb": rec.get("downloaded_gb"),- "total_gb": rec.get("total_gb"),- }- return stage, download--def thin_series(points: list[dict[str, Any]], cap: int = MAX_PERSISTED_SERIES_POINTS) -> list:"""Thin a step series to ≤``cap`` points with an even stride, alwayskeeping the last point (the monitor's "latest" values read from it).@@ -604,103 +559,6 @@ def progress_from_snapshot(snap: PollSnapshot, *, started_at=None) -> dict[str,}-def _obj_get(obj: Any, *keys: str, default=None):- """Read an attribute or dict key, trying several aliases."""- for key in keys:- if isinstance(obj, dict):- if key in obj and obj[key] is not None:- return obj[key]- else:- val = getattr(obj, key, None)- if val is not None:- return val- return default---def parse_together_metrics(raw_metrics: list[Any]) -> tuple[list[dict], list[dict], list[dict]]:- loss_by_step: dict[int, dict[str, Any]] = {}- lr_series: list[dict[str, Any]] = []- grad_series: list[dict[str, Any]] = []-- for row in raw_metrics:- data = (- row- if isinstance(row, dict)- else (- row.model_dump()- if hasattr(row, "model_dump")- else dict(getattr(row, "__dict__", {}) or {})- )- )- # Flatten nested keys; Together returns "train/loss" style keys.- flat: dict[str, Any] = {}- for k, v in data.items():- if str(k).startswith("_"):- continue- flat[str(k)] = v-- step_raw = flat.get("train/global_step") or flat.get("global_step") or flat.get("step")- if step_raw is None:- continue- step = int(step_raw)- point = loss_by_step.setdefault(step, {"step": step})-- train_loss = flat.get("train/loss", flat.get("train_loss"))- eval_loss = flat.get("eval/loss", flat.get("eval_loss"))- if train_loss is not None:- point["train_loss"] = float(train_loss)- if eval_loss is not None:- point["eval_loss"] = float(eval_loss)-- lr = flat.get("train/learning_rate", flat.get("learning_rate"))- if lr is not None:- lr_series.append({"step": step, "value": float(lr)})-- gn = flat.get("train/grad_norm", flat.get("grad_norm"))- if gn is not None:- grad_series.append({"step": step, "value": float(gn)})-- loss_series = [loss_by_step[k] for k in sorted(loss_by_step) if len(loss_by_step[k]) > 1]- lr_series.sort(key=lambda p: p["step"])- grad_series.sort(key=lambda p: p["step"])- return loss_series, lr_series, grad_series---def parse_together_checkpoints(checkpoints: list[Any]) -> list[dict[str, Any]]:- rows: list[dict[str, Any]] = []- for ckpt in checkpoints:- step = _obj_get(ckpt, "step", "checkpoint_step", "global_step")- if step is None:- continue- path = _obj_get(ckpt, "path", "filename", "name", "checkpoint_name", default="") or ""- ckpt_type = str(- _obj_get(ckpt, "type", "checkpoint_type", default="checkpoint") or "checkpoint"- )- created_at = _obj_get(ckpt, "created_at", "timestamp")- size = _obj_get(ckpt, "size", "size_bytes")- rows.append(- {- "id": str(_obj_get(ckpt, "id", default="") or path or step),- "step": int(step),- "type": ckpt_type,- "path": str(path),- "train_loss": None,- "valid_loss": None,- "result_files": [],- "file_count": 0,- "size_bytes": int(size) if size is not None else None,- "created_at": created_at,- "resumable": "resumable" in ckpt_type.lower() or bool(_obj_get(ckpt, "resumable")),- "has_eval": bool(_obj_get(ckpt, "has_eval")),- "upload_status": str(- _obj_get(ckpt, "upload_status", default="uploaded") or "uploaded"- ),- }- )- rows.sort(key=lambda r: r["step"])- return rows--class BaseFinetuningRunner(ABC):# Subclasses override with their provider's status strings._TERMINAL_OK: ClassVar[set[str]] = {"completed"}@@ -741,935 +599,6 @@ class BaseFinetuningRunner(ABC):return []-class TogetherAIRunner(BaseFinetuningRunner):- """Runner backed by the Together AI fine-tuning API.-- Requires the ``together`` SDK and ``TOGETHER_API_KEY`` in settings.- """-- # Provider status strings, normalised to lowercase before comparison.- _TERMINAL_OK = {"completed"}- _TERMINAL_FAIL = {"error", "user_error", "failed"}- _TERMINAL_CANCELLED = {"cancelled", "canceled"}-- # HP field aliases: accept human-friendly names and convert to SDK names.- _HP_ALIASES: dict[str, str] = {- "epochs": "n_epochs",- "num_epochs": "n_epochs",- "lr": "learning_rate",- "checkpoints": "n_checkpoints",- "evals": "n_evals",- }-- def _client(self):- from together import Together # noqa: PLC0415-- return Together(api_key=settings.TOGETHER_API_KEY)-- def submit(- self,- job,- training_file_path: str,- num_examples: int | None,- validation_file_path: str | None = None,- existing_file_id: str | None = None,- ) -> SubmissionResult:- """Upload training data and create a fine-tuning job via the Together SDK.-- The SDK takes flat keyword arguments — no nested ``training_type`` dict; LoRA is- ``lora=True`` plus the ``lora_*`` keys. ``existing_file_id`` reuses a previous- upload and skips that step.- """- client = self._client()-- if existing_file_id:- training_file_id = existing_file_id- uploaded_examples = num_examples- else:- if num_examples == 0:- raise RuntimeError("Dataset produced 0 training examples (all rows lack output).")- uploaded = client.files.upload(file=training_file_path, purpose="fine-tune")- training_file_id = getattr(uploaded, "id", None) or uploaded["id"]- uploaded_examples = num_examples-- hp = dict(job.hyperparameters or {})-- # Our DB nests training_type; the SDK wants it flattened into top-level kwargs.- training_type: dict[str, Any] = hp.pop("training_type", None) or {}- use_lora = training_type.get("type", "Lora") == "Lora"-- create_kwargs: dict[str, Any] = {- "training_file": training_file_id,- "model": job.base_model,- "suffix": together_suffix(job.name, fallback=f"ft-{str(job.id)[:8]}"),- "lora": use_lora,- # Only train on assistant turns — never on user inputs or system prompts.- "train_on_inputs": False,- }- if use_lora:- create_kwargs["lora_r"] = training_type.get("lora_r", 8)- create_kwargs["lora_alpha"] = training_type.get("lora_alpha", 16)- create_kwargs["lora_dropout"] = training_type.get("lora_dropout", 0.0)- create_kwargs["lora_trainable_modules"] = training_type.get(- "lora_trainable_modules", "all-linear"- )-- _skip = {"training_file", "model", "suffix", "lora", "monitoring"}- for key, value in hp.items():- normalised = self._HP_ALIASES.get(key, key)- if normalised in _skip:- continue- # Together documents a per-model minimum batch size; coerce to "max"- # rather than failing the job.- if normalised == "batch_size" and isinstance(value, int):- from overbae.services.recommendation import MODEL_MIN_BATCH-- min_bs = MODEL_MIN_BATCH.get(job.base_model, 8)- if value < min_bs:- logger.warning(- "batch_size=%d is below the minimum %d for %s; using 'max'",- value,- min_bs,- job.base_model,- )- value = "max"- create_kwargs[normalised] = value-- response = client.fine_tuning.create(**create_kwargs)- remote_id = getattr(response, "id", None) or response["id"]- return SubmissionResult(- remote_id=remote_id,- run_url=f"https://api.together.ai/playground/finetune/{remote_id}",- training_file_id=training_file_id,- num_examples=uploaded_examples,- )-- def poll(self, remote_id: str) -> PollSnapshot:- """Normalised snapshot of a Together job.-- ``FinetuneResponse`` maps as ``token_count`` → tokens_processed,- ``x_model_output_name`` → output_model_name, ``x_model_output_path`` →- weights_url. Series come from ``list_metrics`` / ``list_checkpoints``.- """- client = self._client()- ft = client.fine_tuning.retrieve(remote_id)-- state = str(getattr(ft, "status", "") or "").lower()-- # Output model fields use Pydantic aliases; access via the Python attr names.- output_model_name = (- getattr(ft, "x_model_output_name", None) or getattr(ft, "model_output_name", None) or ""- )- weights_url = (- getattr(ft, "x_model_output_path", None) or getattr(ft, "model_output_path", None) or ""- )-- # Fallback: parse loss/step from checkpoint_save events on the retrieve payload.- error_msg = ""- train_loss: float | None = None- eval_loss: float | None = None- latest_step: int | None = None- events = getattr(ft, "events", None) or []- for evt in events:- evt_type = (getattr(evt, "type", "") or "").lower()- if evt_type == "job_error":- error_msg = getattr(evt, "message", "") or ""- if evt_type == "checkpoint_save":- msg = getattr(evt, "message", "") or ""- step_val = getattr(evt, "step", None)- if step_val is not None:- latest_step = int(step_val)- m_train = re.search(r"train_loss=([0-9.]+)", msg)- m_eval = re.search(r"eval_loss=([0-9.]+)", msg)- if m_train:- train_loss = float(m_train.group(1))- if m_eval:- eval_loss = float(m_eval.group(1))-- loss_series: list[dict[str, Any]] = []- lr_series: list[dict[str, Any]] = []- grad_series: list[dict[str, Any]] = []- try:- metrics_resp = client.fine_tuning.list_metrics(remote_id)- raw_rows = (- getattr(metrics_resp, "metrics", None)- or getattr(metrics_resp, "data", None)- or (metrics_resp if isinstance(metrics_resp, list) else [])- )- loss_series, lr_series, grad_series = parse_together_metrics(list(raw_rows or []))- if loss_series:- last = loss_series[-1]- latest_step = last.get("step", latest_step)- train_loss = last.get("train_loss", train_loss)- eval_loss = last.get("eval_loss", eval_loss)- except Exception as exc: # noqa: BLE001 — metrics are best-effort during poll- logger.warning("Together list_metrics failed for %s: %s", remote_id, exc)-- checkpoints: list[dict[str, Any]] = []- try:- ckpt_resp = client.fine_tuning.list_checkpoints(remote_id)- raw_ckpts = (- getattr(ckpt_resp, "data", None)- or getattr(ckpt_resp, "checkpoints", None)- or (ckpt_resp if isinstance(ckpt_resp, list) else [])- )- checkpoints = parse_together_checkpoints(list(raw_ckpts or []))- except Exception as exc: # noqa: BLE001- logger.warning("Together list_checkpoints failed for %s: %s", remote_id, exc)-- total_steps = getattr(ft, "total_steps", None) or getattr(ft, "n_evals", None)- estimated_finish = None- seconds_remaining = getattr(ft, "seconds_remaining", None)- if seconds_remaining is not None:- estimated_finish = int(time.time()) + int(seconds_remaining)-- return PollSnapshot(- state=state,- epochs_completed=getattr(ft, "epochs_completed", None),- tokens_processed=getattr(ft, "token_count", None),- phase=state,- train_loss=train_loss,- eval_loss=eval_loss,- step=latest_step,- total_steps=int(total_steps) if total_steps is not None else None,- estimated_finish=estimated_finish,- loss_series=loss_series,- learning_rate_series=lr_series,- grad_norm_series=grad_series,- checkpoints=checkpoints,- output_model_name=output_model_name or "",- weights_url=weights_url or "",- error=error_msg,- )-- def cancel(self, remote_id: str) -> None:- client = self._client()- client.fine_tuning.cancel(id=remote_id)---class BasetenRunner(BaseFinetuningRunner):- """Runner backed by Baseten training jobs.-- Submits via the ``truss_train`` SDK: script, progress callback and dataset are- packaged into a temp directory and pushed, with config.py env vars carrying every- hyperparameter. ``remote_id`` is ``"{project_id}:{job_id}"``.-- Requires ``BASETEN_API_KEY`` and ``truss_train`` on the Celery worker.- """-- _API_BASE = "https://api.baseten.co"-- _TERMINAL_OK = {"succeeded"}- _TERMINAL_FAIL = {"failed"}- _TERMINAL_CANCELLED = {"cancelled"}-- _PHASE_MAP: dict[str, str] = {- "TRAINING_JOB_QUEUED": "queued",- "TRAINING_JOB_INITIALIZING": "queued",- "TRAINING_JOB_RUNNING": "training",- "TRAINING_JOB_COMPLETED": "finalizing",- "TRAINING_JOB_FAILED": "failed",- "TRAINING_JOB_STOPPED": "cancelled",- "TRAINING_JOB_CANCELED": "cancelled",- }-- # LoRA GPU tiers, ``(max_params_b, gpu, count)``. ≤72B stays on 1×H100 via QLoRA:- # the multi-GPU device_map="balanced" pipeline split OOMed on the hottest stage even- # in 4-bit, so _training_env forces LOAD_IN_4BIT instead.- # Context above 32k upgrades 1×H100 → 1×H200.- _LONG_CONTEXT_H200 = 32768- _GPU_TABLE = [- (7, "H100", 1),- (14, "H100", 1),- (32, "H100", 1),- (72, "H100", 1),- (float("inf"), "H100", 4),- ]-- # Full FT holds weights + grads + 8-bit optimizer states (~6 bytes/param), so every- # tier needs roughly 3× the LoRA VRAM.- _GPU_TABLE_FULL = [- (9, "H100", 1),- (20, "H200", 1), # Gemma4's multi-GPU device_map is broken- (32, "H100", 4),- (float("inf"), "H200", 4),- ]-- # Shared with ModalRunner — sft_assets/train.py is the entrypoint both runners plug into.- _ASSETS_DIR = Path(__file__).parent / "sft_assets"- _ASSET_FILES = tuple(sorted(path.name for path in _ASSETS_DIR.glob("*.py"))) + ("run.sh",)-- def _api_key(self) -> str:- key = getattr(settings, "BASETEN_API_KEY", "") or ""- if not key:- raise RuntimeError("BASETEN_API_KEY is not configured in Django settings.")- return key-- def _ensure_trussrc(self) -> None:- """(Re)write the trussrc file ``truss_train.push`` authenticates from.-- Worker containers have HOME == TMPDIR, so the periodic tmp sweep can delete the- trussrc the entrypoint wrote; rewriting before every push self-heals auth.- """- # Imported at call time so the path constant comes from truss itself, which is- # installed on workers only.- from truss.remote import remote_factory # noqa: PLC0415-- path = remote_factory.USER_TRUSSRC_PATH- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(- "[baseten]\n"- "remote_provider = baseten\n"- "auth_type = api_key\n"- f"api_key = {self._api_key()}\n"- "remote_url = https://app.baseten.co\n"- )- path.chmod(0o600)-- def _headers(self) -> dict:- return {"Authorization": f"Bearer {self._api_key()}"}-- def _get_job(self, project_id: str, job_id: str) -> dict:- import requests # noqa: PLC0415-- resp = requests.get(- f"{self._API_BASE}/v1/training_projects/{project_id}/jobs/{job_id}",- headers=self._headers(),- timeout=30,- )- resp.raise_for_status()- return resp.json().get("training_job", {})-- def _fetch_logs(self, project_id: str, job_id: str, start_ms: int = 0) -> list[dict]:- """Fetch ALL log entries from Baseten, ascending by timestamp.-- Pagination is mandatory: per-step telemetry plus startup noise overflows the- API's 1000-line page, and a single ascending page silently drops the NEWEST- entries. Entry timestamps are nanoseconds while the cursor is milliseconds, so- each page re-fetches the last millisecond and duplicates are dropped by ns.- """- import requests # noqa: PLC0415-- out: list[dict] = []- cursor_ms = start_ms- last_ns = -1- for _ in range(30):- resp = requests.get(- f"{self._API_BASE}/v1/training_projects/{project_id}/jobs/{job_id}/logs",- headers=self._headers(),- params={- "limit": 1000, # Baseten API max is 1000- "direction": "asc",- "start_epoch_millis": cursor_ms,- },- timeout=30,- )- resp.raise_for_status()- page = resp.json().get("logs", [])- fresh = (- [e for e in page if int(e.get("timestamp") or 0) > last_ns]- if last_ns >= 0- else page- )- out.extend(fresh)- if len(page) < 1000 or (last_ns >= 0 and not fresh):- break- last_ns = int(page[-1].get("timestamp") or 0)- cursor_ms = last_ns // 1_000_000- return out-- @staticmethod- def _parse_remote_id(remote_id: str) -> tuple[str, str]:- project_id, job_id = remote_id.split(":", 1)- return project_id, job_id-- @staticmethod- def _normalise_status(raw: str) -> str:- mapping = {- "TRAINING_JOB_COMPLETED": "succeeded",- "TRAINING_JOB_FAILED": "failed",- "TRAINING_JOB_STOPPED": "cancelled",- "TRAINING_JOB_CANCELED": "cancelled",- }- if raw in mapping:- return mapping[raw]- return raw.lower().replace("training_job_", "")-- @staticmethod- def _job_training_type(job) -> str:- hp = dict(getattr(job, "hyperparameters", None) or {})- return str((hp.get("training_type") or {}).get("type") or "Lora")-- def _select_training_gpu(self, job, *, context_length: int = 0) -> tuple[str, int]:- """The smallest GPU tier that can train the model."""- try:- from overbae.modal.model_registry import get_model_config_any_backend # noqa: PLC0415-- cfg = get_model_config_any_backend(job.base_model) or {}- # Catalog entries carry total_params_b (billions); the raw num_parameters- # count exists only on DeployedModel rows.- params_b = (- float(cfg.get("total_params_b") or 0) or (cfg.get("num_parameters") or 0) / 1e9- )- except Exception: # noqa: BLE001- logger.warning("BasetenRunner: could not look up model params for %s", job.base_model)- params_b = 0-- table = self._GPU_TABLE if self._job_training_type(job) == "Lora" else self._GPU_TABLE_FULL- for max_b, gpu, count in table:- if params_b <= max_b:- if context_length > self._LONG_CONTEXT_H200 and count == 1 and gpu == "H100":- gpu = "H200"- return clamp_gemma4_training_gpu(job.base_model, gpu, count)- return clamp_gemma4_training_gpu(job.base_model, "H200", 4)-- def _dataset_type(self, training_file_path: str) -> str:- """``"tool"`` when any row carries a ``tools`` key, else ``"chat"``."""- try:- with open(training_file_path) as f:- for line in f:- row = json.loads(line)- if row.get("tools"):- return "tool"- except Exception: # noqa: BLE001- pass- return "chat"-- @staticmethod- def _training_env(- job,- dataset_type: str,- plan: BasetenTrainingPlan,- *,- gpu_type: str = "H100",- gpu_count: int = 1,- params_b: float = 0,- ) -> dict[str, str]:- """Env vars for train.py — the plan serialised 1:1, nothing invented here."""- from overbae.modal.model_registry import get_hf_base # noqa: PLC0415-- env = {- "MODEL_ID": get_hf_base(str(job.base_model)),- "DATASET_TYPE": dataset_type,- "TRAINING_TYPE": plan.training_type,- "MAX_LENGTH": str(plan.context_length),- "LORA_R": str(plan.lora_r),- "LORA_ALPHA": str(plan.lora_alpha),- "LORA_DROPOUT": str(plan.lora_dropout),- "LORA_TARGET_MODULES": plan.lora_target_modules,- "PER_DEVICE_BATCH": str(plan.per_device_batch),- "GRAD_ACCUM": str(plan.grad_accum),- "N_EPOCHS": str(plan.n_epochs),- "LEARNING_RATE": str(plan.learning_rate),- "WARMUP_RATIO": str(plan.warmup_ratio),- "WEIGHT_DECAY": str(plan.weight_decay),- "PACKING": "1" if plan.packing else "0",- # Assistant-only loss masking needs TRL's chat templating, which only the- # conversational path has; the tool path pre-renders text and trains the- # full sequence.- "ASSISTANT_ONLY_LOSS": "1" if dataset_type == "chat" else "0",- "SEED": str(plan.seed),- }- if (job.hyperparameters or {}).get("monitoring") is not None:- env["TRAINING_MONITORING"] = json.dumps(job.hyperparameters["monitoring"])- env["TRAINING_MONITOR_LOGS"] = "1"- from overbae.modal.model_registry import get_unsloth_image # noqa: PLC0415-- env["UNSLOTH_IMAGE"] = get_unsloth_image(str(job.base_model))- # gpt-oss Unsloth LoRA must be QLoRA even when 20B bf16 "fits" H100 —- # the BF16 load path is numerically broken (see families/gpt_oss.py).- from modal_shared.modelfam import family_key # noqa: PLC0415-- is_gpt_oss = family_key(str(job.base_model)) == "gpt_oss"- if plan.training_type == "Lora" and (plan.load_in_4bit or is_gpt_oss):- env["LOAD_IN_4BIT"] = "1"- if is_gpt_oss:- # Must be set before train.py imports unsloth (import-time constant).- env["UNSLOTH_COMPILE_DISABLE"] = "1"- try:- from overbae.modal.model_registry import get_model_config_any_backend # noqa: PLC0415-- hidden = int(- (get_model_config_any_backend(str(job.base_model)) or {}).get("hidden_size") or 0- )- if hidden > 0:- env["HIDDEN_SIZE"] = str(hidden)- except Exception: # noqa: BLE001- pass- _ = params_b # GPU selection already applied; plan.load_in_4bit is authoritative- return env-- def _build_config_source(- self,- job,- gpu_type: str,- gpu_count: int,- dataset_type: str,- plan: BasetenTrainingPlan,- project_name: str = "",- ) -> str:- # truss 0.18.x TrainingProject is extra="forbid" with {name, job, team_name} and- # no `id`; push upserts BY NAME, so BASETEN_PROJECT goes on TrainingProject.name- # and the per-job label on TrainingJob.name.- job_name = re.sub(r"[^a-zA-Z0-9_-]", "-", (job.name or "ft-job"))[:50]- project = re.sub(r"[^a-zA-Z0-9_-]", "-", project_name or "overmind-finetuning")[:50]- params_b = 0.0- try:- from overbae.modal.model_registry import get_model_config_any_backend # noqa: PLC0415-- cfg = get_model_config_any_backend(job.base_model) or {}- params_b = (- float(cfg.get("total_params_b") or 0) or (cfg.get("num_parameters") or 0) / 1e9- )- except Exception: # noqa: BLE001- pass- env = self._training_env(- job, dataset_type, plan, gpu_type=gpu_type, gpu_count=gpu_count, params_b=params_b- )- # Baseten does not auto-inject workspace secrets into training jobs: without an- # explicit SecretReference, gated HF downloads 401 even when the secret exists.- env_items = ", ".join(f"{k!r}: {v!r}" for k, v in env.items())- env_literal = (- "{"- f"{env_items}, "- '"HF_TOKEN": SecretReference(name="HF_ACCESS_TOKEN"), '- '"HUGGING_FACE_HUB_TOKEN": SecretReference(name="HF_ACCESS_TOKEN")'- "}"- )- return (- "from truss_train import CheckpointingConfig, CacheConfig, Compute, Image, Runtime, SecretReference, TrainingJob, TrainingProject\n"- "from truss.base.truss_config import AcceleratorSpec\n\n"- "training_project = TrainingProject(\n"- f' name="{project}",\n'- " job=TrainingJob(\n"- f' name="{job_name}",\n'- ' image=Image(base_image="pytorch/pytorch:2.7.0-cuda12.8-cudnn9-runtime"),\n'- f" compute=Compute(accelerator=AcceleratorSpec(accelerator={gpu_type!r}, count={gpu_count})),\n"- " runtime=Runtime(\n"- ' start_commands=["chmod +x ./run.sh && ./run.sh"],\n'- f" environment_variables={env_literal},\n"- " cache_config=CacheConfig(enabled=True),\n"- " checkpointing_config=CheckpointingConfig(enabled=True),\n"- " ),\n"- " ),\n"- ")\n"- )-- def submit(- self,- job,- training_file_path: str,- num_examples: int | None,- validation_file_path: str | None = None,- ) -> SubmissionResult:- import shutil- import tempfile-- try:- from truss_train import push as truss_push # noqa: PLC0415- except ImportError as exc:- raise RuntimeError(- "truss_train is not installed on the Celery worker. Run: pip install truss-train"- ) from exc-- self._ensure_trussrc()-- if num_examples == 0:- raise RuntimeError("Dataset produced 0 training examples.")-- # An impossible plan must raise here, before any provider spend.- from overbae.modal.model_registry import get_model_config_any_backend # noqa: PLC0415- from overbae.modal.training_type import training_context_length # noqa: PLC0415-- model_cfg = get_model_config_any_backend(job.base_model) or {}- ft_cfg = model_cfg.get("finetuning") or {}- stats = dict((job.cell.stats if job.cell_id else None) or {})- try:- max_row_tokens = int(stats.get("max_token_length") or 0)- except (TypeError, ValueError):- max_row_tokens = 0- hp = dict(job.hyperparameters or {})- training_kind = "full" if str(hp.get("training_type", {}).get("type")) == "Full" else "lora"- model_max = training_context_length(model_cfg, training_kind)- requested_ctx = int(hp.get("context_length") or 0) or None- early_ctx = baseten_context_length(- max_row_tokens, model_max=model_max, requested=requested_ctx- )- gpu_type, gpu_count = self._select_training_gpu(job, context_length=early_ctx)- plan = derive_baseten_training_plan(- hyperparameters=job.hyperparameters,- num_train_examples=int(num_examples or 0),- dataset_stats=stats,- params_b=float(model_cfg.get("total_params_b") or 0),- model_max_context=model_max,- model_min_batch=int(ft_cfg.get("min_batch_size") or 1),- model_max_batch=int(ft_cfg["max_batch_size"]) if ft_cfg.get("max_batch_size") else None,- gpu_type=gpu_type,- gpu_count=gpu_count,- model_id=job.base_model,- hidden_size=int(model_cfg.get("hidden_size") or 0),- )- for note in plan.notes:- logger.info("BasetenRunner plan (job %s): %s", job.id, note)-- # Persist the resolved knobs so the monitor shows what was trained with,- # not "auto".- from overbae.models import FinetuningJob as _FTJob # noqa: PLC0415-- _FTJob.objects.filter(pk=job.pk).update(- hyperparameters={- **(dict(job.hyperparameters) or {}),- "context_length": plan.context_length,- "n_epochs": plan.n_epochs,- "batch_size": plan.batch_size,- "learning_rate": plan.learning_rate,- "warmup_ratio": plan.warmup_ratio,- "packing": plan.packing,- }- )-- dataset_type = self._dataset_type(training_file_path)-- config_src = self._build_config_source(- job=job,- gpu_type=gpu_type,- gpu_count=gpu_count,- dataset_type=dataset_type,- plan=plan,- project_name=getattr(settings, "BASETEN_PROJECT", "") or "",- )-- with tempfile.TemporaryDirectory(prefix="bt_ft_") as tmpdir:- tmp = Path(tmpdir)-- for asset in self._ASSET_FILES:- shutil.copy2(self._ASSETS_DIR / asset, tmp / asset)- (tmp / "run.sh").chmod(0o755)- # TrainerHooks + family registry (pure stdlib) for the training container.- families_src = self._ASSETS_DIR / "families"- if families_src.is_dir():- shutil.copytree(families_src, tmp / "families")- # modal_shared lives outside overbae on purpose — overbae/__init__.py- # imports Celery, which the bare Baseten container can't configure.- shared_src = Path(__file__).resolve().parents[2] / "modal_shared"- shutil.copytree(- shared_src,- tmp / "modal_shared",- ignore=shutil.ignore_patterns("__pycache__", "*.pyc"),- )- # Hand-patched {% generation %} chat templates.- for template_dir in (- "llama_templates",- "antares_templates",- "olmo_templates",- "qwen_templates",- ):- src = self._ASSETS_DIR / template_dir- if src.is_dir():- shutil.copytree(src, tmp / template_dir)-- shutil.copy2(training_file_path, tmp / "data.jsonl")- if validation_file_path:- shutil.copy2(validation_file_path, tmp / "val.jsonl")- else:- # Write a minimal val file to keep TRL happy- (tmp / "val.jsonl").write_text("")-- (tmp / "config.py").write_text(config_src)-- logger.info(- "BasetenRunner: pushing job %s — model=%s gpu=%s×%d ctx=%d "- "batch=%d×%d epochs=%d packing=%s",- job.id,- job.base_model,- gpu_type,- gpu_count,- plan.context_length,- plan.per_device_batch,- plan.grad_accum,- plan.n_epochs,- plan.packing,- )- resp = truss_push(config=tmp / "config.py")-- job_id = resp["id"]- project_id = resp["training_project"]["id"]- remote_id = f"{project_id}:{job_id}"-- logger.info(- "BasetenRunner: submitted job_id=%s project_id=%s remote_id=%s",- job_id,- project_id,- remote_id,- )- return SubmissionResult(- remote_id=remote_id,- run_url=f"https://app.baseten.co/training/{project_id}/{job_id}",- training_file_id="",- num_examples=num_examples,- )-- def poll(self, remote_id: str) -> PollSnapshot:- import json as _json # noqa: PLC0415, F811-- project_id, job_id = self._parse_remote_id(remote_id)- raw_job = self._get_job(project_id, job_id)- raw_status = raw_job.get("current_status", "")- state = self._normalise_status(raw_status)- phase = self._PHASE_MAP.get(raw_status, "running")-- logs = self._fetch_logs(project_id, job_id, start_ms=0)-- trained_steps: int | None = None- total_steps: int | None = None- train_loss: float | None = None- eval_loss: float | None = None- learning_rate: float | None = None- token_accuracy: float | None = None- eval_token_accuracy: float | None = None- current_epoch: float | None = None- eta_s: float | None = None- tokens_processed: int | None = None- metrics_history: list[dict] = []- eval_history: list[dict] = []- checkpoint_history: list[dict] = []-- for entry in logs:- msg = (entry.get("message") or "").strip()- if msg.startswith("BT_MONITORING "):- try:- raw_job["monitoring"] = _json.loads(msg[len("BT_MONITORING ") :])- except _json.JSONDecodeError:- raw_job["monitoring_collection_error"] = (- "Provider truncated a monitoring receipt"- )- elif msg.startswith("BT_PROGRESS "):- try:- rec = _json.loads(msg[len("BT_PROGRESS ") :])- trained_steps = rec.get("step")- total_steps = rec.get("total_steps")- train_loss = rec.get("loss")- learning_rate = rec.get("lr")- token_accuracy = rec.get("token_accuracy")- current_epoch = rec.get("epoch")- eta_s = rec.get("eta_s")- if rec.get("num_tokens") is not None:- tokens_processed = int(rec["num_tokens"])- point: dict = {"step": trained_steps, "epoch": current_epoch}- if train_loss is not None:- point["train_loss"] = round(train_loss, 6)- if token_accuracy is not None:- point["token_accuracy"] = round(token_accuracy, 6)- if learning_rate is not None:- point["lr"] = learning_rate- if rec.get("grad_norm") is not None:- point["grad_norm"] = float(rec["grad_norm"])- metrics_history.append(point)- except _json.JSONDecodeError:- pass- elif msg.startswith("BT_CHECKPOINT "):- try:- rec = _json.loads(msg[len("BT_CHECKPOINT ") :])- checkpoint_history.append(- {- "step": rec.get("step"),- "epoch": rec.get("epoch"),- "path": str(rec.get("path") or ""),- "timestamp": entry.get("timestamp"),- }- )- except _json.JSONDecodeError:- pass- elif msg.startswith("BT_EVAL "):- try:- rec = _json.loads(msg[len("BT_EVAL ") :])- eval_loss = rec.get("eval_loss")- eval_token_accuracy = rec.get("eval_token_accuracy")- eval_point: dict = {- "step": rec.get("step"),- "epoch": rec.get("epoch"),- }- if eval_loss is not None:- eval_point["eval_loss"] = round(eval_loss, 6)- if eval_token_accuracy is not None:- eval_point["eval_token_accuracy"] = round(eval_token_accuracy, 6)- eval_history.append(eval_point)- except _json.JSONDecodeError:- pass-- stage, download = parse_download_stage(logs)-- import time as _time # noqa: PLC0415-- estimated_finish = int(_time.time() + eta_s) if eta_s is not None and eta_s > 0 else None-- error = raw_job.get("error_message", "") or ""-- # Map the BT_* histories onto the monitor's series contract- # (progress_from_snapshot → job.progress.metrics.*).- loss_by_step: dict[int, dict[str, Any]] = {}- lr_series: list[dict[str, Any]] = []- grad_series: list[dict[str, Any]] = []- ta_by_step: dict[int, dict[str, Any]] = {}- for point in metrics_history:- p_step = point.get("step")- if p_step is None:- continue- if point.get("train_loss") is not None:- loss_by_step.setdefault(p_step, {"step": p_step})["train_loss"] = point[- "train_loss"- ]- if point.get("lr") is not None:- lr_series.append({"step": p_step, "value": point["lr"]})- if point.get("grad_norm") is not None:- grad_series.append({"step": p_step, "value": point["grad_norm"]})- if point.get("token_accuracy") is not None:- ta_by_step.setdefault(p_step, {"step": p_step})["train"] = point["token_accuracy"]- eval_by_step: dict[int, dict[str, Any]] = {}- for ev in eval_history:- e_step = ev.get("step")- if e_step is None:- continue- if ev.get("eval_loss") is not None:- loss_by_step.setdefault(e_step, {"step": e_step})["eval_loss"] = ev["eval_loss"]- eval_by_step[int(e_step)] = ev- if ev.get("eval_token_accuracy") is not None:- ta_by_step.setdefault(e_step, {"step": e_step})["eval"] = ev["eval_token_accuracy"]- loss_series = [loss_by_step[s] for s in sorted(loss_by_step)]- token_accuracy_series = [ta_by_step[s] for s in sorted(ta_by_step)]-- # Baseten checkpoints are volume artifacts, not chat-callable endpoints.- checkpoints: list[dict[str, Any]] = []- for ckpt in checkpoint_history:- c_step = ckpt.get("step")- if c_step is None:- continue- c_step = int(c_step)- ev = eval_by_step.get(c_step, {})- train_point = loss_by_step.get(c_step, {})- checkpoints.append(- {- "id": ckpt["path"] or f"checkpoint-{c_step}",- "step": c_step,- "type": "checkpoint",- "path": ckpt["path"],- "train_loss": train_point.get("train_loss"),- "valid_loss": ev.get("eval_loss"),- "valid_mean_token_accuracy": ev.get("eval_token_accuracy"),- "result_files": [],- "file_count": 0,- "created_at": ckpt.get("timestamp"),- "resumable": True,- "has_eval": ev.get("eval_loss") is not None,- "upload_status": "uploaded",- }- )- checkpoints.sort(key=lambda r: r["step"])-- # Baseten has no provider-side model name, so synthesise a stable id: the- # final-eval/deployment pipeline needs a non-empty artifact ref, while the- # weights are fetched by remote_id through the checkpoint API.- output_model_name = f"baseten/{job_id}/final" if state in self._TERMINAL_OK else ""-- return PollSnapshot(- state=state,- epochs_completed=int(current_epoch) if current_epoch is not None else None,- tokens_processed=tokens_processed,- trained_steps=trained_steps,- step=trained_steps,- total_steps=total_steps,- phase=phase,- train_loss=train_loss,- eval_loss=eval_loss,- learning_rate=learning_rate,- token_accuracy=token_accuracy,- eval_token_accuracy=eval_token_accuracy,- current_epoch=current_epoch,- eta_s=eta_s,- estimated_finish=estimated_finish,- loss_series=loss_series,- learning_rate_series=lr_series,- grad_norm_series=grad_series,- token_accuracy_series=token_accuracy_series,- checkpoints=checkpoints,- metrics_history=metrics_history,- eval_history=eval_history,- activity=filter_activity_logs(logs),- stage=stage,- download=download,- output_model_name=output_model_name,- error=error,- raw=raw_job,- )-- def cancel(self, remote_id: str) -> None:- """Stop the remote training job (POST …/jobs/{id}/stop → TRAINING_JOB_STOPPED)."""- import requests # noqa: PLC0415-- project_id, job_id = self._parse_remote_id(remote_id)- resp = requests.post(- f"{self._API_BASE}/v1/training_projects/{project_id}/jobs/{job_id}/stop",- headers=self._headers(),- json={},- timeout=30,- )- resp.raise_for_status()-- def fetch_epoch_losses(self, remote_id: str) -> list[dict]:- import json as _json # noqa: PLC0415, F811-- project_id, job_id = self._parse_remote_id(remote_id)- logs = self._fetch_logs(project_id, job_id, start_ms=0)-- evals: list[dict] = []- for entry in logs:- msg = (entry.get("message") or "").strip()- if msg.startswith("BT_EVAL "):- try:- rec = _json.loads(msg[len("BT_EVAL ") :])- evals.append(rec)- except _json.JSONDecodeError:- pass-- # Train loss per epoch = the last BT_PROGRESS in that epoch bucket.- epoch_train: dict[int, float] = {}- for entry in logs:- msg = (entry.get("message") or "").strip()- if msg.startswith("BT_PROGRESS "):- try:- rec = _json.loads(msg[len("BT_PROGRESS ") :])- epoch_int = int(rec.get("epoch", 0)) # floor epoch- loss = rec.get("loss")- if loss is not None:- epoch_train[epoch_int] = float(loss)- except _json.JSONDecodeError:- pass-- result = []- for i, ev in enumerate(evals, start=1):- epoch_float = ev.get("epoch", float(i))- epoch_int = int(epoch_float)- t_loss = epoch_train.get(epoch_int) or epoch_train.get(epoch_int - 1)- result.append(- {- "epoch": i,- "train_loss": t_loss,- "valid_loss": ev.get("eval_loss"),- }- )-- return result-- def is_terminal_ok(self, state: str) -> bool:- return state in self._TERMINAL_OK-- def is_terminal_fail(self, state: str) -> bool:- return state in self._TERMINAL_FAIL-- def is_terminal_cancelled(self, state: str) -> bool:- return state in self._TERMINAL_CANCELLED--class ModalRunner(BaseFinetuningRunner):"""Runner backed by Modal Functions in our own ``overmind-sft`` app.@@ -1678,7 +607,7 @@ class ModalRunner(BaseFinetuningRunner):A Modal Function's image is fixed at deploy time, so the family's train stackselects between prebuilt Functions (``sft_{stack}``) instead of branching- inside one the way BasetenRunner's run.sh does.+ inside one.``remote_id`` is ``"{run_id}:{function_call_id}"``. Requires the ``modal`` SDK plusits tokens on the worker, and ``overmind-sft`` deployed.@@ -1718,7 +647,7 @@ class ModalRunner(BaseFinetuningRunner):"cancelled": "cancelled",}- # Same tiers as BasetenRunner. ≤72B LoRA stays on 1×H100 with QLoRA: 2–3×H100+ # ≤72B LoRA stays on 1×H100 with QLoRA: 2–3×H100# device_map="balanced" splits OOMed on the last stage during Unsloth# gradient-checkpoint recompute.# Context above 32k upgrades 1×H100 → 1×H200 (141 GB vs 80 GB activation headroom).@@ -1748,7 +677,7 @@ class ModalRunner(BaseFinetuningRunner):def model_config(model_id: str) -> dict[str, Any]:from overbae.modal.model_registry import get_all_models_by_backend # noqa: PLC0415- config = get_all_models_by_backend("baseten").get(model_id) or get_all_models_by_backend(+ config = get_all_models_by_backend("modal").get(model_id) or get_all_models_by_backend("decision", include_disabled=False).get(model_id)if not config:@@ -1779,7 +708,7 @@ class ModalRunner(BaseFinetuningRunner):@staticmethoddef _training_env(- plan: BasetenTrainingPlan,+ plan: TrainingPlan,model_id: str,*,gpu_type: str = "H100",@@ -1865,17 +794,16 @@ class ModalRunner(BaseFinetuningRunner):max_row_tokens = 0hp = dict(job.hyperparameters or {})training_kind = "full" if str(hp.get("training_type", {}).get("type")) == "Full" else "lora"- # Modal reuses the Baseten catalog — models.json has no "modal" rows.# Exact preprocessing, not the character estimate, owns the chosen context.max_row_tokens = 0stats["max_token_length"] = 0model_max = training_context_length(model_cfg, training_kind)requested_ctx = int(hp.get("context_length") or 0) or None- early_ctx = baseten_context_length(+ early_ctx = snap_context_length(max_row_tokens, model_max=model_max, requested=requested_ctx)gpu_type, gpu_count = self._select_training_gpu(job, context_length=early_ctx)- plan = derive_baseten_training_plan(+ plan = derive_training_plan(hyperparameters=job.hyperparameters,num_train_examples=int(num_examples or 0),dataset_stats=stats,@@ -2278,12 +1206,10 @@ class ModalRunner(BaseFinetuningRunner):_RUNNER_REGISTRY: dict[str, type[BaseFinetuningRunner]] = {- "together": TogetherAIRunner,- "baseten": BasetenRunner,"modal": ModalRunner,}-_DEFAULT_RUNNER = "baseten"+_DEFAULT_RUNNER = "modal"def get_runner(backend: str | None = None, *, job=None) -> BaseFinetuningRunner:@@ -2292,8 +1218,6 @@ def get_runner(backend: str | None = None, *, job=None) -> BaseFinetuningRunner:"modal" if job is not None and (job.requested_configuration or {}).get("runtime") else None)key = backend or pinned_backend or getattr(settings, "FINETUNING_BACKEND", _DEFAULT_RUNNER)- if key == "together_ai":- key = "together"cls = _RUNNER_REGISTRY.get(key)if cls is None:raise ValueError(diff --git a/overbae/services/finetuning_tool_validation.py b/overbae/services/finetuning_tool_validation.pyindex a9e52973..7484d4cd 100644--- a/overbae/services/finetuning_tool_validation.py+++ b/overbae/services/finetuning_tool_validation.py@@ -1,6 +1,6 @@"""Local validation for tool-calling conversational fine-tuning rows.-Together AI rejects datasets whose tool ``tool_call_id`` values do not match the+Training rejects datasets whose tool ``tool_call_id`` values do not match thepreceding assistant ``tool_calls``, that carry orphan tool messages, or whosetool-call counts do not line up. These checks run before upload so the user seesthe problem at dataset selection time.@@ -174,7 +174,7 @@ def _check_tool_names(messages: list[dict[str, Any]],row: dict[str, Any],) -> list[str]:- """Together requires tool_calls / tool message names to match ``tools`` exactly."""+ """tool_calls / tool message names must match ``tools`` exactly."""tool_names = tool_names_from_row(row)if not tool_names:return []diff --git a/overbae/services/finetuning_validator.py b/overbae/services/finetuning_validator.pyindex 3e9308ed..3c82a23e 100644--- a/overbae/services/finetuning_validator.py+++ b/overbae/services/finetuning_validator.py@@ -3,9 +3,8 @@Two accepted formats: conversational ``{"messages": [...]}`` and instruction``{"prompt": ..., "completion": ...}``.-Runs entirely in-process — no SDK, no network. The checks replicate what Together's-``check_file`` does locally (UTF-8, JSON per line, minimum samples) and add the-semantic validation Together otherwise defers to its server.+Runs entirely in-process — no SDK, no network: UTF-8, JSON per line, minimum+samples, and the semantic validation the training worker would otherwise fail on."""from __future__ import annotations@@ -324,9 +323,7 @@ def _long_row_warning_threshold() -> int | None:from overbae.modal.model_registry import min_sft_context_lengthbackend = getattr(settings, "FINETUNING_BACKEND", None)- # Modal reuses the Baseten catalog verbatim — models.json has no "modal" rows.- catalog_backend = "baseten" if backend == "modal" else backend- return min_sft_context_length(catalog_backend) if catalog_backend else None+ return min_sft_context_length(backend) if backend else Nonedef _apply_tool_calling_checks(diff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.pyindex f955bdf1..96d059b3 100644--- a/overbae/services/mcp/__init__.py+++ b/overbae/services/mcp/__init__.py@@ -1,3 +1,3 @@"""MCP protocol and catalog services."""-CONTRACT_VERSION = "10.0.0"+CONTRACT_VERSION = "11.0.0"diff --git a/overbae/services/mcp/contracts/model_catalog.py b/overbae/services/mcp/contracts/model_catalog.pyindex dbe277a1..c1d7a893 100644--- a/overbae/services/mcp/contracts/model_catalog.py+++ b/overbae/services/mcp/contracts/model_catalog.py@@ -4,14 +4,13 @@ from __future__ import annotationsfrom typing import Literal-from pydantic import Field, StrictBool, StrictInt+from pydantic import Field, StrictBoolfrom overbae.services.mcp.contracts.common import MCPModelclass GetModelCatalogInput(MCPModel):has_tool_calling: StrictBool = False- max_context: StrictInt | None = Field(default=None, gt=0, le=10_000_000)class ModelCatalogTrainingMethod(MCPModel):@@ -44,9 +43,8 @@ class ModelCatalogModel(MCPModel):class GetModelCatalogOutput(MCPModel):summary: str = Field(min_length=1, max_length=240)- backend: Literal["together", "baseten", "modal"]+ backend: Literal["modal"]tiers: list[Literal["compact", "small", "mid", "large"]]models: dict[str, list[ModelCatalogModel]]has_tool_calling: bool- max_context: int | None = Field(gt=0, le=10_000_000)monitoring: dictdiff --git a/overbae/services/mcp/prompts.py b/overbae/services/mcp/prompts.pyindex e7553746..870a75d6 100644--- a/overbae/services/mcp/prompts.py+++ b/overbae/services/mcp/prompts.py@@ -503,8 +503,8 @@ PROMPTS = ("or expose any presigned URL. On the coding agent's filesystem, run `overmind model ""download-checkpoint DEPLOYMENT --json`. Replace DEPLOYMENT with the exact deployment id ""resolved through MCP as one shell argument. Parse the result and report its local `path` "- "and `bytes_written`. Only archived checkpoints for supported fine-tune providers "- "(baseten or modal) are downloadable. The CLI refuses to overwrite an existing file."+ "and `bytes_written`. Only archived checkpoints of fine-tuned models are downloadable. "+ "The CLI refuses to overwrite an existing file."),),)diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.pyindex 9171b19a..ca892193 100644--- a/overbae/services/mcp/resources.py+++ b/overbae/services/mcp/resources.py@@ -352,9 +352,9 @@ def _checkpoint_download_resource(uri: str) -> dict:"download URL is used only by the local CLI and must never be exposed to model context."),"availability": (- "Only archived checkpoints for deployed models linked to fine-tuning jobs from the "- "supported providers baseten or modal are downloadable. Deployments without a "- "fine-tuning job, unsupported providers, and archives that are not ready are unavailable."+ "Only archived checkpoints for deployed models linked to fine-tuning jobs are "+ "downloadable. Deployments without a fine-tuning job and archives that are not ready "+ "are unavailable."),"output": "Parse the JSON result and report the local path and bytes_written.","overwrite": "The CLI refuses to overwrite an existing local file.",diff --git a/overbae/services/mcp/tools_model_catalog.py b/overbae/services/mcp/tools_model_catalog.pyindex bbf66e34..d435e53d 100644--- a/overbae/services/mcp/tools_model_catalog.py+++ b/overbae/services/mcp/tools_model_catalog.py@@ -13,10 +13,7 @@ from overbae.services.mcp.contracts.model_catalog import (@sync_to_async(thread_sensitive=True)def _get_model_catalog(payload, _context):- catalog = fetch_finetuning_model_catalog(- has_tool_calling=payload.has_tool_calling,- max_context=payload.max_context,- )+ catalog = fetch_finetuning_model_catalog(has_tool_calling=payload.has_tool_calling)count = sum(len(models) for models in catalog["models"].values())return GetModelCatalogOutput(summary=f"{count} fine-tuning catalog entries returned for {catalog['backend']}.",diff --git a/overbae/services/model_library.py b/overbae/services/model_library.pyindex 451ea3fb..eb441e1a 100644--- a/overbae/services/model_library.py+++ b/overbae/services/model_library.py@@ -174,16 +174,8 @@ def public_library_filters() -> dict[str, Any]:def public_model_catalog() -> list[dict[str, Any]]:- """Every model available on the platform: open-weight + frontier.-- ``together`` entries are left out: training runs on Modal from the Baseten- catalog, so a Together-only id can be neither trained nor served.- """- by_id = {- cfg["id"]: cfg- for cfg in all_model_entries()- if not cfg.get("disabled") and cfg.get("backend") != "together"- }+ """Every model available on the platform: open-weight + frontier."""+ by_id = {cfg["id"]: cfg for cfg in all_model_entries() if not cfg.get("disabled")}open_weight = [_open_weight_entry(cfg) for cfg in by_id.values()]frontier = [_frontier_entry(m) for m in library_models()]diff --git a/overbae/services/recommendation/__init__.py b/overbae/services/recommendation/__init__.pyindex 9af43758..bbd93873 100644--- a/overbae/services/recommendation/__init__.py+++ b/overbae/services/recommendation/__init__.py@@ -17,7 +17,7 @@ from overbae.services.training_contract import dataset_objective, validate_effecfrom .analysis import build_analysis, dataset_summaryfrom .candidates import build_candidate, dataset_total_tokens-from .catalog import MODEL_MIN_BATCH, active_backend, find_catalog_model, tier_models+from .catalog import active_backend, find_catalog_model, tier_modelslogger = logging.getLogger(__name__)@@ -119,7 +119,7 @@ def estimate_for_hyperparams(from overbae.services.finetuning_pricing import estimate_training_run # noqa: PLC0415dataset = Dataset.objects.get(pk=dataset_id)- if active_backend() in {"modal", "baseten"}:+ if active_backend() == "modal":validate_effective_batch(hyperparameters or {})stats = dataset_stats(dataset, cell)selected = cell or dataset.active_cell@@ -135,7 +135,7 @@ def estimate_for_hyperparams(if not training_enabled(entry, kind):raise ValueError(f"Model {base_model} does not support {kind_label} fine-tuning")requested_context = (hyperparameters or {}).get("context_length")- if active_backend() in {"modal", "baseten"} and requested_context is not None:+ if active_backend() == "modal" and requested_context is not None:from overbae.services.finetuning_policy import validate_requested_context_lengthvalidate_requested_context_length(@@ -144,7 +144,7 @@ def estimate_for_hyperparams(max_tokens = int(stats.get("max_token_length") or 0)if max_tokens:model_max = training_context_length(entry, kind)- headroom = context_headroom("baseten")+ headroom = context_headroom(active_backend())if model_max is not None and model_max < max_tokens + headroom:raise ValueError(f"Longest dataset row is ≈{max_tokens:,} tokens but {base_model}'s "@@ -182,9 +182,7 @@ def estimate_for_hyperparams("forecast": measured,"cost_estimate": {"usd": cost[1],- "price_per_million_usd": None,"trained_tokens": tokens,- "minimum_applied": False,}if costelse None,@@ -226,7 +224,7 @@ def recommend_hyperparams_for_model(from overbae.modal.model_registry import context_headroomfrom overbae.modal.training_type import training_context_length, usable_training_kinds- headroom = context_headroom("baseten")+ headroom = context_headroom(active_backend())if not usable_training_kinds(entry, max_tokens=max_tokens, headroom=headroom):model_max = max(training_context_length(entry, kind) or 0 for kind in ("lora", "full"))raise ValueError(@@ -294,7 +292,6 @@ def _profile(dataset) -> dict[str, Any]:__all__ = [- "MODEL_MIN_BATCH","estimate_for_hyperparams","find_catalog_model","get_recommendation",diff --git a/overbae/services/recommendation/candidates.py b/overbae/services/recommendation/candidates.pyindex 3c3d42a4..c6a45c29 100644--- a/overbae/services/recommendation/candidates.py+++ b/overbae/services/recommendation/candidates.py@@ -24,7 +24,7 @@ from overbae.services.finetuning_pricing import (humanize_duration,)-from .catalog import active_backend, catalog_backend, gpu_config+from .catalog import active_backend, gpu_configfrom .hyperparams import compute_hyperparams, hyperparam_provenancefrom .ranking import MIN_COHORT, Ranked@@ -61,7 +61,7 @@ def build_candidate(max_tokens = int(stats.get("max_token_length") or 0)training_type = dataset_training_type(- model_entry, max_tokens=max_tokens or None, headroom=context_headroom("baseten")+ model_entry, max_tokens=max_tokens or None, headroom=context_headroom(backend))supports_lora = training_type["lora"]["enabled"]supports_full = training_type["full"]["enabled"]@@ -117,9 +117,7 @@ def build_candidate("hyperparams": hyperparams,"use_lora": use_lora,"training_type": training_type,- # gpu_config reads the Baseten inference rows because models.json has no "modal"- # ones; the cost estimate keeps the literal backend so Modal's branch wins.- "gpu_config": gpu_config(model_entry["id"], catalog_backend()),+ "gpu_config": gpu_config(model_entry["id"], backend),"cost_estimate": estimate_training_cost(trained_tokens,total_params_b=params_b,diff --git a/overbae/services/recommendation/catalog.py b/overbae/services/recommendation/catalog.pyindex 1abd6d24..53bdd974 100644--- a/overbae/services/recommendation/catalog.py+++ b/overbae/services/recommendation/catalog.py@@ -13,18 +13,13 @@ from overbae.modal.model_registry import get_all_models_by_backend, get_tier_moddef active_backend() -> str:- return getattr(settings, "FINETUNING_BACKEND", "baseten")---def catalog_backend() -> str:- """models.json backend key for FINETUNING_BACKEND — Modal reuses Baseten's rows."""- backend = active_backend()- return "baseten" if backend == "modal" else backend+ """models.json backend key for ``FINETUNING_BACKEND``."""+ return getattr(settings, "FINETUNING_BACKEND", "modal")def tier_models(*, backend: str | None = None) -> dict[str, list[dict[str, Any]]]:"""Tier catalog for ``backend``, defaulting to the active one."""- return get_tier_models(backend=backend or catalog_backend())+ return get_tier_models(backend=backend or active_backend())def find_catalog_model(model_id: str, *, decision: bool = False) -> dict[str, Any] | None:@@ -45,11 +40,3 @@ def gpu_config(model_id: str, backend: str) -> dict[str, Any]:"num_gpus": 1,"max_model_len": inference.get("max_model_len"),}---# Together-only lookup — used by TogetherAIRunner for min-batch coercion.-MODEL_MIN_BATCH: dict[str, int] = {- m["id"]: m["min_batch_size"]- for models in get_tier_models(backend="together").values()- for m in models-}diff --git a/overbae/services/recommendation/constraints.py b/overbae/services/recommendation/constraints.pyindex 83b8c046..67d31fbc 100644--- a/overbae/services/recommendation/constraints.py+++ b/overbae/services/recommendation/constraints.py@@ -15,7 +15,7 @@ from overbae.modal.training_type import (usable_training_kinds,)-from .catalog import tier_models+from .catalog import active_backend, tier_models@dataclass(frozen=True, slots=True)@@ -73,7 +73,7 @@ def _rejection(if max_row_tokens:from overbae.modal.model_registry import context_headroom- headroom = context_headroom("baseten")+ headroom = context_headroom(active_backend())if not usable_training_kinds(entry, max_tokens=max_row_tokens, headroom=headroom):sft_context = max(training_context_length(entry, kind) or 0 for kind in ("lora", "full")diff --git a/overbae/services/recommendation/hyperparams.py b/overbae/services/recommendation/hyperparams.pyindex cbb4db0e..774f412b 100644--- a/overbae/services/recommendation/hyperparams.py+++ b/overbae/services/recommendation/hyperparams.py@@ -1,6 +1,6 @@"""Hyperparameter defaults for a (dataset, model) pair, and one line of why per knob.-Every number is delegated to finetuning_policy, the module the Baseten runner gap-fills+Every number is delegated to finetuning_policy, the module the training runner gap-fillsfrom at submission time: the wizard's numbers ARE the training script's numbers."""@@ -10,7 +10,6 @@ from typing import Anyfrom overbae.modal.training_type import training_context_lengthfrom overbae.services.finetuning_policy import (- baseten_context_length,default_epochs,estimated_training_context_length,openai_batch_size,@@ -18,7 +17,7 @@ from overbae.services.finetuning_policy import (qlora_lora_params,)-from .catalog import active_backend, catalog_backend+from .catalog import active_backenddef compute_hyperparams(@@ -30,8 +29,8 @@ def compute_hyperparams() -> dict[str, Any]:"""Data-size-adaptive hyperparameters for a specific model.- On Baseten, ``context_length`` snaps up from the dataset's longest row: it is the- training MAX_LENGTH, and rows over it would be truncated by TRL.+ On Modal, ``context_length`` snaps up from the dataset's longest row: it is the+ training MAX_LENGTH, and rows over it would be truncated."""if num_examples <= 0:num_examples = 1@@ -45,14 +44,9 @@ def compute_hyperparams(params_b: float = entry.get("total_params_b", 7.0)context_length: int | None = None- if catalog_backend() == "baseten":+ if active_backend() == "modal":model_max = training_context_length(entry, "lora" if use_lora else "full")- choose_context = (- estimated_training_context_length- if active_backend() == "modal"- else baseten_context_length- )- context_length = choose_context(+ context_length = estimated_training_context_length(max_row_tokens,model_max=int(model_max) if model_max else None,)diff --git a/overbae/services/sft_assets/catalog.py b/overbae/services/sft_assets/catalog.pyindex c938cd18..8005f83f 100644--- a/overbae/services/sft_assets/catalog.py+++ b/overbae/services/sft_assets/catalog.py@@ -3,7 +3,7 @@The registry lives in ``modal_shared/`` at the repo root, deliberately outside``overbae`` so it stays pure stdlib and never drags Celery/Django into a trainingcontainer. This file only bootstraps the import so the same code works from the-local source tree and from a Modal/Baseten container (``modal_shared`` at /root).+local source tree and from a Modal container (``modal_shared`` at /root)."""from __future__ import annotationsdiff --git a/overbae/services/sft_assets/common.py b/overbae/services/sft_assets/common.pyindex ede48c39..9e98b70a 100644--- a/overbae/services/sft_assets/common.py+++ b/overbae/services/sft_assets/common.py@@ -250,7 +250,7 @@ class ProgressCallback(TrainerCallback):sys.stdout.flush()if self.metrics_path is not None:# "event" carries the BT_* prefix so a poller reading metrics.jsonl- # dispatches exactly as BasetenRunner.poll does off the stdout prefix.+ # dispatches exactly as it would off the stdout prefix.payload = {"event": prefix, **record}with self.metrics_path.open("a") as f:f.write(json.dumps(payload) + "\n")diff --git a/overbae/services/sft_assets/engine_unsloth.py b/overbae/services/sft_assets/engine_unsloth.pyindex 333cf393..67edde38 100644--- a/overbae/services/sft_assets/engine_unsloth.py+++ b/overbae/services/sft_assets/engine_unsloth.py@@ -241,8 +241,7 @@ LOAD_IN_4BIT = os.getenv("LOAD_IN_4BIT", "0") == "1" and USE_LORA# flattens the micro-batch into one sequence and Unsloth truncates it.# Default off: Modal omitted this env and the old default ("1") packed every job# to MAX_LENGTH, OOMing Gemma4 12B/26B on flex_attention (no FA2, GC forced off).-# Honor PACKING too — BasetenRunner sets that name for the stock engine.-PACK_ROWS = os.getenv("PACK_ROWS", os.getenv("PACKING", "0")) == "1"+PACK_ROWS = os.getenv("PACK_ROWS", "0") == "1"def _pack_rows(rows: list[dict], max_length: int) -> list[dict]:@@ -292,7 +291,7 @@ def _build_dataset(emit_stage(stage, completed=0, total=len(rows), unit="rows")out: list[dict] = []for i, row in enumerate(rows):- # Baseten receives conversations; Modal receives the CPU-validated artifact.+ # Conversation rows are tokenized here; the CPU-validated artifact arrives pretokenized.if "messages" in row and "input_ids" not in row:row["key"] = row_key(row)row.update(pretok_row(tok, MODEL_ID, row["messages"], row.get("tools")))diff --git a/overbae/services/sft_assets/train.py b/overbae/services/sft_assets/train.pyindex 842a445b..c04c1903 100644--- a/overbae/services/sft_assets/train.py+++ b/overbae/services/sft_assets/train.py@@ -1,4 +1,4 @@-"""Shared SFT entrypoint for Baseten and Modal.+"""Shared SFT entrypoint for the Modal training workers.CRITICAL: do NOT import torch/transformers/trl/peft/datasets at this module's toplevel. unsloth must be the process's first heavyweight import (see engine_unsloth.py),diff --git a/overbae/services/training_contract.py b/overbae/services/training_contract.pyindex 44980789..f7c9782f 100644--- a/overbae/services/training_contract.py+++ b/overbae/services/training_contract.py@@ -54,7 +54,7 @@ def contract(cell, hyperparameters=None):if nativeelse {"assistant_tokens": "cross_entropy"},"methods": ["lora"] if native else ["lora", "full"],- "providers": ["modal"] if native else ["modal", "baseten", "together_ai"],+ "providers": ["modal"],"metrics": ["cross_entropy","brier",diff --git a/overbae/services/training_monitoring.py b/overbae/services/training_monitoring.pyindex c6c30399..e55459d1 100644--- a/overbae/services/training_monitoring.py+++ b/overbae/services/training_monitoring.py@@ -99,10 +99,6 @@ def resolve(hyperparameters, *, has_development, provider, monitoring=None):generation = policy["generation"]if generation and native:raise ValueError("Native decisions use probability metrics, not generation probes")- if generation and provider == "baseten":- raise ValueError(- "Baseten generation evidence collection is not qualified; use loss monitoring or Modal"- )if generation and generation["kind"] == "json_schema":schema = generation["schema"]try:diff --git a/overbae/services/training_preparation.py b/overbae/services/training_preparation.pyindex dd9819e8..72f91436 100644--- a/overbae/services/training_preparation.py+++ b/overbae/services/training_preparation.py@@ -34,8 +34,8 @@ from overbae.services import operational_progress, training_releasefrom overbae.services.datasets import rows as row_storefrom overbae.services.datasets import use as dataset_usefrom overbae.services.finetuning_policy import (- baseten_context_length,estimated_training_context_length,+ snap_context_length,validate_requested_context_length,)from overbae.services.finetuning_validator import row_to_finetuning_line@@ -201,7 +201,7 @@ def _adopt_measured_context(prep):return prepif not _matches_estimate(context, _estimated_tokens(prep.cell, prep.validation_cell), maximum):return prep- raised = baseten_context_length(model_max=maximum, requested=exact)+ raised = snap_context_length(model_max=maximum, requested=exact)if raised == context:return prepmeasured = request_preparation(@@ -557,7 +557,7 @@ def for_job(job):and (maximum is None or exact_tokens <= maximum)):# Recheck every row at the measured size; length can coexist with other errors.- context = baseten_context_length(model_max=maximum, requested=exact_tokens)+ context = snap_context_length(model_max=maximum, requested=exact_tokens)prep = request_preparation(job.cell,job.base_model,diff --git a/overbae/settings.py b/overbae/settings.pyindex e01840d3..75feab19 100644--- a/overbae/settings.py+++ b/overbae/settings.py@@ -347,7 +347,7 @@ SPECTACULAR_SETTINGS = {"COMPONENT_SPLIT_REQUEST": True,"SCHEMA_PATH_PREFIX": r"/api/","ENUM_NAME_OVERRIDES": {- "BackendEnum": [("together", "together"), ("baseten", "baseten"), ("modal", "modal")],+ "BackendEnum": [("modal", "modal")],"IntentEnum": "overbae.models.datasets.Dataset.Intent","CellStateEnum": "overbae.models.datasets.Cell.State",# Lane provenance shares the field name with finetuning evidence; pinned so@@ -527,11 +527,6 @@ CELERY_BEAT_SCHEDULE = {"task": "overbae.tasks.finetuning_reconciler.reconcile_finetuning_jobs","schedule": 15.0,},- # Hourly because Baseten's billing lags the job.- "sync-baseten-finetuning-costs": {- "task": "overbae.tasks.baseten_billing_sync.sync_baseten_finetuning_costs",- "schedule": 3600.0,- },# Fails runs stuck in RUNNING with no row progress and no healthy generation wait."reap-stalled-eval-runs": {"task": "overbae.tasks.innermind.reap_stalled_runs",@@ -727,11 +722,6 @@ LOGGING = {},}-TOGETHER_API_KEY = os.environ.get("TOGETHER_API_KEY", "")--BASETEN_API_KEY = os.environ.get("BASETEN_API_KEY", "")-BASETEN_PROJECT = os.environ.get("BASETEN_PROJECT", "")-HF_TOKEN = os.environ.get("HF_TOKEN", "")# Durable home for a fine-tune's checkpoint.zip / job_logs.txt / metrics.json.diff --git a/overbae/tasks/__init__.py b/overbae/tasks/__init__.pyindex a8b33eef..d5b69e36 100644--- a/overbae/tasks/__init__.py+++ b/overbae/tasks/__init__.py@@ -4,7 +4,6 @@ from overbae.api.otlp import process_spanfrom . import ( # noqa: E402assistant,- baseten_billing_sync,capability_rebind,cleanup_modal,cleanup_tmp,@@ -28,7 +27,6 @@ from .dataset_context import refresh_dataset_context__all__ = ["assistant",- "baseten_billing_sync","capability_rebind","cleanup_modal","cleanup_tmp",diff --git a/overbae/tasks/baseten_billing_sync.py b/overbae/tasks/baseten_billing_sync.pydeleted file mode 100644index 23058e07..00000000--- a/overbae/tasks/baseten_billing_sync.py+++ /dev/null@@ -1,31 +0,0 @@-import logging--from celery import shared_task--from overbae.tasks.utils.task_lock import with_task_lock--logger = logging.getLogger(__name__)---@shared_task(name="overbae.tasks.baseten_billing_sync.sync_baseten_finetuning_costs")-@with_task_lock(lock_name="baseten_billing_sync", timeout=1800)-def sync_baseten_finetuning_costs(*, lookback_days: int = 14) -> dict:- """Beat: hourly. Refreshes recent/active Baseten training costs onto FinetuningJob."""- from overbae.services.baseten_billing import sync_recent_finetuning_costs-- result = sync_recent_finetuning_costs(lookback_days=lookback_days)- logger.info("Baseten finetuning cost sync: %s", result)- return result---@shared_task(name="overbae.tasks.baseten_billing_sync.sync_baseten_job_cost")-def sync_baseten_job_cost(*, job_id: str) -> dict | None:- from overbae.models.finetuning import FinetuningJob- from overbae.services.baseten_billing import sync_job_cost_window-- try:- job = FinetuningJob.objects.get(pk=job_id)- except FinetuningJob.DoesNotExist:- logger.warning("sync_baseten_job_cost: job %s not found", job_id)- return None- return sync_job_cost_window(job)diff --git a/overbae/tasks/cleanup_tmp.py b/overbae/tasks/cleanup_tmp.pyindex e1c65fdc..15da0e50 100644--- a/overbae/tasks/cleanup_tmp.py+++ b/overbae/tasks/cleanup_tmp.py@@ -28,7 +28,7 @@ def cleanup_data_tmp() -> dict[str, int]:for entry in os.scandir(tmpdir):# HOME == TMPDIR in our containers — dotfiles are config- # (.trussrc, .aws, …), not scratch. Never sweep them.+ # (.aws, .cache, …), not scratch. Never sweep them.if entry.name.startswith("."):continuetry:diff --git a/overbae/tasks/finetuning.py b/overbae/tasks/finetuning.pyindex 5ff91a5d..942d7745 100644--- a/overbae/tasks/finetuning.py+++ b/overbae/tasks/finetuning.py@@ -67,19 +67,6 @@ def collect_training_evidence(self, job_id):raise self.retry(exc=exc, countdown=min(30 * 2**self.request.retries, 300)) from exc-def _enqueue_baseten_cost_sync(job) -> None:- from overbae.models import FinetuningJob-- if job.provider != FinetuningJob.Provider.BASETEN or not job.remote_job_id:- return- try:- from overbae.tasks.baseten_billing_sync import sync_baseten_job_cost-- sync_baseten_job_cost.delay(job_id=str(job.id))- except Exception: # noqa: BLE001 — cost sync must never fail the training job- logger.warning("Failed to enqueue Baseten cost sync for job %s", job.id, exc_info=True)--def _training_line(row) -> str:from overbae.services.finetuning_validator import row_to_finetuning_line@@ -455,7 +442,6 @@ def _finalize_success(job, runner, snap, remote: str) -> dict[str, Any]:logger.info("Queued inference deployment for job %s", job.id)except Exception: # noqa: BLE001logger.exception("Failed to queue inference deployment for job %s — continuing", job.id)- _enqueue_baseten_cost_sync(job)return {"status": "deploying", "job_id": remote}@@ -500,11 +486,10 @@ def run_finetuning(*, job_id: str) -> dict[str, Any]:backend = ("modal"if (job.requested_configuration or {}).get("runtime")- else getattr(settings, "FINETUNING_BACKEND", "baseten")+ else getattr(settings, "FINETUNING_BACKEND", "modal"))- # Baseten and Modal are self-hosted-script backends whose train.py reads an- # optional val.jsonl; Together needs its own separate eval dataset API.- supports_validation = backend in {"baseten", "modal"}+ # Modal's train.py reads an optional val.jsonl.+ supports_validation = backend == "modal"# An existing remote id means this is a re-drive — skip submission, go to polling.existing_remote_id = _remote_id(job)@@ -513,11 +498,7 @@ def run_finetuning(*, job_id: str) -> dict[str, Any]:try:from overbae.services.finetuning_eval import start_before_evals- provider = {- "together": FinetuningJob.Provider.TOGETHER_AI,- "baseten": FinetuningJob.Provider.BASETEN,- "modal": FinetuningJob.Provider.MODAL,- }.get(backend, FinetuningJob.Provider.BASETEN)+ provider = {"modal": FinetuningJob.Provider.MODAL}[backend]FinetuningJob.objects.filter(pk=job.pk).update(provider=provider)job.provider = providerif backend == "modal":@@ -776,13 +757,11 @@ def observe_finetuning_job(job) -> dict[str, Any]:if runner.is_terminal_cancelled(snap.state):if job.status != FinetuningJob.Status.CANCELLED:_transition(job, FinetuningJob.Status.CANCELLED, message="Fine-tuning cancelled")- _enqueue_baseten_cost_sync(job)return {"status": "cancelled", "job_id": remote}job.refresh_from_db(fields=["status", "progress"])if job.status == FinetuningJob.Status.CANCELLED:_cancel_remote(runner, remote)- _enqueue_baseten_cost_sync(job)return {"status": "cancelled"}if _stalled(job.progress if isinstance(job.progress, dict) else {}):@@ -813,4 +792,3 @@ def _handle_failure(job, error: str) -> None:return_transition(job, FinetuningJob.Status.FAILED, error=error)- _enqueue_baseten_cost_sync(job)diff --git a/overmind/overmind/__init__.py b/overmind/overmind/__init__.pyindex de1ad2e3..c0405a27 100644--- a/overmind/overmind/__init__.py+++ b/overmind/overmind/__init__.py@@ -10,7 +10,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Any-__version__ = "0.1.124"+__version__ = "0.1.125"from .client import Client, ModelDeleted, OvermindInferenceErrordiff --git a/overmind/pyproject.toml b/overmind/pyproject.tomlindex c22b1f96..f686fb9a 100644--- a/overmind/pyproject.toml+++ b/overmind/pyproject.toml@@ -46,7 +46,7 @@ license = { text = "MIT" }name = "overmind"readme = "README.md"requires-python = ">=3.10,<4" # todo; remove the upper bound-version = "0.1.124"+version = "0.1.125"[project.urls]"Agent setup" = "https://console.overmindlab.ai/setup.md"diff --git a/overmind/skills/overmind-training/SKILL.md b/overmind/skills/overmind-training/SKILL.mdindex 81375f69..783c7ef9 100644--- a/overmind/skills/overmind-training/SKILL.md+++ b/overmind/skills/overmind-training/SKILL.md@@ -186,7 +186,7 @@ eval dataset. Context warnings do not automatically block launch or changemodel selection. An approved preview's `judge_model` becomes`eval_judge_model` on `start_finetune`; omission preserves the set's judges.-For Modal/Baseten, `batch_size` means the effective optimizer batch. The runtime+For Modal, `batch_size` means the effective optimizer batch. The runtimederives micro-batching and accumulation; `gradient_accumulation_steps` and`per_device_train_batch_size` are rejected. Native decision readiness supplieseligible models, not a chat-benchmark ranking or an unmeasured price promise.@@ -198,8 +198,8 @@ with `start_decision_job`. Use `start_finetune` for chat models. Native decisionkeep the four chat evaluation flags false and preserve the declared probabilityobjective; both tools share the same durable training lifecycle.-Freeze `hyperparameters.monitoring` with the rest of the recipe. Modal and Baseten-support loss monitoring with adaptive/steps/epoch/off schedules; discover current+Freeze `hyperparameters.monitoring` with the rest of the recipe. Modal supports loss+monitoring with adaptive/steps/epoch/off schedules; discover currentprovider capabilities from the model catalogue. Modal also accepts explicitclassification labels, exact matching, JSON Schema and `json_fields` generation probes. Theagent supplies task semantics; the platform never invents labels or a success@@ -315,9 +315,9 @@ through MCP, then run `overmind model download-checkpoint DEPLOYMENT --json` oncoding agent's filesystem with the deployment id supplied by MCP. The CLIauthenticates with `X-Api-Key` from `--api-key`, the saved local project credentialor `OVERMIND_API_KEY`, and uses the base URL from `OVERMIND_API_URL`, `--api-url` or-`overmind.toml`. Only archived checkpoints for `baseten` and `modal` fine-tune-providers are downloadable. Deployments without a fine-tuning job, unsupported-providers and archives that are not ready are unavailable. The presigned S3 URL+`overmind.toml`. Only archived checkpoints of fine-tuned models are downloadable.+Deployments without a fine-tuning job and archives that are not ready are+unavailable. The presigned S3 URLstays inside the server/CLI flow and must not enter model context. Parse the JSONresult and report its local `path` and `bytes_written`; the CLI refuses to overwritean existing file.diff --git a/overmind/uv.lock b/overmind/uv.lockindex da5ab46b..94036ec7 100644--- a/overmind/uv.lock+++ b/overmind/uv.lock@@ -923,7 +923,7 @@ wheels = [[[package]]name = "overmind"-version = "0.1.124"+version = "0.1.125"source = { editable = "." }dependencies = [{ name = "packaging" },diff --git a/pyproject.toml b/pyproject.tomlindex eb223400..d37372c0 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -34,7 +34,6 @@ dependencies = ["scipy>=1.14.0","python-json-logger>=3.3.0","redis>=5.0.0",- "together>=1.3.0","django-storages>=1.14.6","watchdog>=4.0.0","modal>=1.6.1",@@ -129,7 +128,6 @@ extend-exclude = ["overbae/migrations/*","__pycache__/*","merps",- "baseten_testing/*","experiments/*",# SDK has its own pyproject / ruff / CI job under overmind/"overmind",diff --git a/tests/settings.py b/tests/settings.pyindex 1aee5f63..c21cca36 100644--- a/tests/settings.py+++ b/tests/settings.py@@ -12,8 +12,6 @@ os.environ.setdefault("INFERENCE_API_URL", "http://inference.test")os.environ.setdefault("INFERENCE_API_KEY", "testing")os.environ.setdefault("FINETUNING_BACKEND", "modal")os.environ.setdefault("HF_TOKEN", "testing")-os.environ.setdefault("BASETEN_API_KEY", "testing")-os.environ.setdefault("TOGETHER_API_KEY", "testing")os.environ.setdefault("MODAL_ENVIRONMENT", "overmind-dev")os.environ.setdefault("MODAL_TOKEN_ID", "testing")os.environ.setdefault("MODAL_TOKEN_SECRET", "testing")diff --git a/tests/test_baseten_billing.py b/tests/test_baseten_billing.pydeleted file mode 100644index 7b8f668a..00000000--- a/tests/test_baseten_billing.py+++ /dev/null@@ -1,219 +0,0 @@-from __future__ import annotations--import uuid-from datetime import UTC, datetime, timedelta-from decimal import Decimal-from unittest.mock import patch--import pytest-from conftest import TRAIN_ROWS, frozen_dataset--from overbae.models import Project-from overbae.models.finetuning import FinetuningJob-from overbae.services.baseten_billing import (- EARLIEST_QUERYABLE,- accumulate_training_costs,- project_finetuning_costs,- sync_finetuning_job_costs,- usage_summary_chunks,-)--pytestmark = [pytest.mark.django_db, pytest.mark.covers("ledger")]---def _training_summary(*items: dict) -> dict:- return {- "training_usage": {"breakdown": list(items), "total": 0, "credits_used": 0, "subtotal": 0}- }---def _item(resource_id: str, *, subtotal: float, minutes: int, kind: str = "TRAINING_JOB") -> dict:- return {- "billable_resource": {"id": resource_id, "kind": kind, "is_deleted": False},- "subtotal": subtotal,- "minutes": minutes,- }---def _job(**kwargs) -> FinetuningJob:- project = kwargs.pop("project", None) or Project.objects.create(- name=f"billing-{uuid.uuid4().hex[:6]}",- slug=f"billing-{uuid.uuid4().hex[:8]}",- )- dataset = kwargs.pop("dataset", None) or frozen_dataset(- project, TRAIN_ROWS, name="ds", contract="train"- )- defaults = {- "project": project,- "dataset": dataset,- "base_model": "Qwen/Qwen3-8B",- "provider": FinetuningJob.Provider.BASETEN,- "remote_job_id": "btproj:job-a",- "status": FinetuningJob.Status.SUCCEEDED,- }- defaults.update(kwargs)- return FinetuningJob.objects.create(**defaults)---def test_chunks_never_exceed_31_days():- since = datetime(2026, 1, 1, tzinfo=UTC)- until = datetime(2026, 4, 15, tzinfo=UTC)- chunks = usage_summary_chunks(since, until)- assert chunks- for start, end in chunks:- assert end - start <= timedelta(days=31)- assert (end - start).days <= 30 or end == until---def test_chunks_clamp_to_earliest_queryable():- since = datetime(2025, 6, 1, tzinfo=UTC)- until = datetime(2026, 1, 10, tzinfo=UTC)- chunks = usage_summary_chunks(since, until)- assert chunks[0][0] == EARLIEST_QUERYABLE---def test_chunks_empty_when_until_before_since():- assert (- usage_summary_chunks(- datetime(2026, 2, 1, tzinfo=UTC),- datetime(2026, 1, 1, tzinfo=UTC),- )- == []- )---def test_accumulate_sums_same_resource_across_chunks():- s1 = _training_summary(_item("job-a", subtotal=3.25, minutes=30))- s2 = _training_summary(_item("job-a", subtotal=6.50, minutes=60))- costs = accumulate_training_costs([s1, s2])- assert costs["job-a"].cost_usd == Decimal("9.75")- assert costs["job-a"].billed_minutes == 90---def test_accumulate_ignores_non_training_kinds():- s = _training_summary(- _item("dep-1", subtotal=100, minutes=10, kind="MODEL_DEPLOYMENT"),- _item("job-a", subtotal=1.5, minutes=15),- )- costs = accumulate_training_costs([s])- assert set(costs) == {"job-a"}- assert costs["job-a"].cost_usd == Decimal("1.5")---def test_sync_matches_remote_job_id_suffix():- job = _job(remote_job_id="proj123:job-a")- together = _job(- project=job.project,- dataset=job.dataset,- provider=FinetuningJob.Provider.TOGETHER_AI,- remote_job_id="together-ft-xyz",- )- other = _job(- project=job.project,- dataset=job.dataset,- remote_job_id="proj123:job-other",- )-- summary = _training_summary(- _item("job-a", subtotal=12.34, minutes=100),- _item("unknown", subtotal=9, minutes=9),- )-- with (- patch("overbae.services.baseten_billing._api_key", return_value="test-key"),- patch(- "overbae.services.baseten_billing.fetch_usage_summary",- return_value=summary,- ) as fetch,- patch(- "overbae.services.baseten_billing.usage_summary_chunks",- return_value=[(datetime(2026, 6, 1, tzinfo=UTC), datetime(2026, 6, 15, tzinfo=UTC))],- ),- ):- result = sync_finetuning_job_costs(- since=datetime(2026, 6, 1, tzinfo=UTC),- until=datetime(2026, 6, 15, tzinfo=UTC),- )-- assert result["matched"] == 1- assert result["updated"] == 1- fetch.assert_called_once()-- job.refresh_from_db()- assert job.cost_usd == Decimal("12.3400")- assert job.billed_minutes == 100- assert job.cost_synced_at is not None-- together.refresh_from_db()- assert together.cost_usd is None- other.refresh_from_db()- assert other.cost_usd is None---def test_sync_noop_without_api_key():- _job(remote_job_id="proj:job-a")- with patch("overbae.services.baseten_billing._api_key", return_value=""):- result = sync_finetuning_job_costs(- since=datetime(2026, 6, 1, tzinfo=UTC),- until=datetime(2026, 6, 15, tzinfo=UTC),- )- assert result == {"fetched": 0, "matched": 0, "updated": 0, "chunks": 0}---def test_sync_accumulates_across_real_chunks():- job = _job(remote_job_id="p:long-job")-- def fake_fetch(*, start, end):- mid = datetime(2026, 2, 1, tzinfo=UTC)- if end <= mid:- return _training_summary(_item("long-job", subtotal=2.0, minutes=20))- return _training_summary(_item("long-job", subtotal=3.0, minutes=30))-- with (- patch("overbae.services.baseten_billing._api_key", return_value="k"),- patch(- "overbae.services.baseten_billing.fetch_usage_summary",- side_effect=fake_fetch,- ),- ):- result = sync_finetuning_job_costs(- since=datetime(2026, 1, 1, tzinfo=UTC),- until=datetime(2026, 3, 1, tzinfo=UTC),- )-- assert result["chunks"] >= 2- job.refresh_from_db()- assert job.cost_usd == Decimal("5.0000")- assert job.billed_minutes == 50---def test_project_finetuning_costs_sums_only_that_project():- p1 = Project.objects.create(name="p1", slug=f"p1-{uuid.uuid4().hex[:8]}")- p2 = Project.objects.create(name="p2", slug=f"p2-{uuid.uuid4().hex[:8]}")- ds1 = frozen_dataset(p1, TRAIN_ROWS, name="d1", contract="train")- ds2 = frozen_dataset(p2, TRAIN_ROWS, name="d2", contract="train")-- _job(project=p1, dataset=ds1, cost_usd=Decimal("10.5"), billed_minutes=50, remote_job_id="a:1")- _job(project=p1, dataset=ds1, cost_usd=Decimal("2.25"), billed_minutes=10, remote_job_id="a:2")- _job(project=p1, dataset=ds1, remote_job_id="a:3")- _job(- project=p2,- dataset=ds2,- cost_usd=Decimal("100"),- billed_minutes=999,- remote_job_id="b:1",- )- _job(- project=p1,- dataset=ds1,- provider=FinetuningJob.Provider.TOGETHER_AI,- cost_usd=Decimal("999"),- remote_job_id="tog-1",- )-- agg = project_finetuning_costs(p1.id)- assert agg["job_count"] == 3 # baseten only- assert agg["jobs_with_cost"] == 2- assert agg["jobs_missing_cost"] == 1- assert agg["cost_usd"] == Decimal("12.75")- assert agg["billed_minutes"] == 60diff --git a/tests/test_completions_api.py b/tests/test_completions_api.pyindex 85e4f3cc..46d8f2d3 100644--- a/tests/test_completions_api.py+++ b/tests/test_completions_api.py@@ -1124,7 +1124,7 @@ class TestActiveModelValidation:capability=sibling,dataset=frozen_dataset(p, TRAIN_ROWS, name="t", contract="train"),base_model="Qwen/Qwen3-8B",- provider=FinetuningJob.Provider.BASETEN,+ provider=FinetuningJob.Provider.MODAL,)m.save(update_fields=["finetuning_job"])@@ -1145,7 +1145,7 @@ class TestBenchmarkSelection:capability=capability,dataset=frozen_dataset(project, TRAIN_ROWS, name="t", contract="train"),base_model="Qwen/Qwen3-8B",- provider=FinetuningJob.Provider.BASETEN,+ provider=FinetuningJob.Provider.MODAL,baseline_model="", # not snapshotted yet → resolve live)diff --git a/tests/test_dataset_gate.py b/tests/test_dataset_gate.pyindex 9edb2891..db4440fc 100644--- a/tests/test_dataset_gate.py+++ b/tests/test_dataset_gate.py@@ -13,7 +13,7 @@ from factories import make_matrix_rowfrom rest_framework.test import APIClientfrom overbae.api.serializers import FinetuningJobSerializer-from overbae.modal.model_registry import baseten_finetuning_catalog+from overbae.modal.model_registry import finetuning_catalogfrom overbae.models import (Capability,Cell,@@ -54,7 +54,7 @@ def _job(project, capability, user, train, evaluation, **fields):"eval_dataset": str(evaluation.id),"eval_set": str(eval_set.id),"base_model": next(- m["id"] for tier in baseten_finetuning_catalog().values() for m in tier+ m["id"] for tier in finetuning_catalog("modal").values() for m in tier),"hyperparameters": {"training_type": {"type": "Lora"}},**fields,diff --git a/tests/test_finetuning_baseline_target.py b/tests/test_finetuning_baseline_target.pyindex a620bdc9..b897848f 100644--- a/tests/test_finetuning_baseline_target.py+++ b/tests/test_finetuning_baseline_target.py@@ -55,7 +55,7 @@ def _job(*, incumbent: str = "") -> FinetuningJob:eval_set=eset,base_model="Qwen/Qwen3-8B",status=FinetuningJob.Status.RUNNING,- provider=FinetuningJob.Provider.BASETEN,+ provider=FinetuningJob.Provider.MODAL,baseline_model=incumbent,eval_incumbent_before=True,eval_model_before=False,@@ -151,7 +151,7 @@ def test_resolve_baseline_prefers_snapshot_over_live_capability():capability=capability,dataset=dataset,base_model="Qwen/Qwen3-8B",- provider=FinetuningJob.Provider.BASETEN,+ provider=FinetuningJob.Provider.MODAL,baseline_model="", # not snapshotted yet → live capability model)assert resolve_baseline_model(job) == "anthropic/claude-sonnet-5"diff --git a/tests/test_finetuning_baseten_runner.py b/tests/test_finetuning_baseten_runner.pydeleted file mode 100644index 80bb15bf..00000000--- a/tests/test_finetuning_baseten_runner.py+++ /dev/null@@ -1,391 +0,0 @@-from __future__ import annotations--import json-from types import SimpleNamespace-from unittest.mock import patch--import pytest--from overbae.services.finetuning_runner import (- MAX_ACTIVITY_LINES,- BasetenRunner,- filter_activity_logs,- get_runner,- progress_from_snapshot,-)--pytestmark = pytest.mark.covers("model-runtime")--_REMOTE_ID = "proj-1:job-9"---def _bt_logs():- """Log entries exactly as baseten_callback.py prints them."""- lines = [- "BT_PROGRESS "- + json.dumps(- {- "step": 5,- "total_steps": 30,- "epoch": 0.5,- "epochs": 3,- "loss": 2.51,- "lr": 1e-5,- "elapsed_s": 45.2,- "eta_s": 225.8,- "grad_norm": 1.9,- "token_accuracy": 0.61,- "num_tokens": 4096,- }- ),- "BT_EVAL "- + json.dumps(- {- "step": 10,- "epoch": 1.0,- "eval_loss": 3.12,- "eval_runtime_s": 2.3,- "eval_token_accuracy": 0.58,- }- ),- "BT_CHECKPOINT " + json.dumps({"step": 10, "epoch": 1.0, "path": "checkpoint-10"}),- "BT_PROGRESS "- + json.dumps(- {- "step": 10,- "total_steps": 30,- "epoch": 1.0,- "epochs": 3,- "loss": 2.10,- "lr": 9e-6,- "elapsed_s": 90.0,- "eta_s": 180.0,- "grad_norm": 1.4,- "token_accuracy": 0.65,- "num_tokens": 8192,- }- ),- ]- return [{"message": m, "timestamp": 1_700_000_000_000 + i} for i, m in enumerate(lines)]---def _poll(state="TRAINING_JOB_RUNNING", logs=None):- runner = BasetenRunner()- with (- patch.object(BasetenRunner, "_get_job", return_value={"current_status": state}),- patch.object(BasetenRunner, "_fetch_logs", return_value=logs or _bt_logs()),- ):- return runner.poll(_REMOTE_ID)---def test_filter_activity_logs_keeps_stage_lines_drops_noise():- """Fixture lines are verbatim raw output from Baseten job wnr4pyq."""- logs = [- # ns timestamp, as the Baseten API returns it- {"message": "Creating the training job.", "timestamp": "1784323432231601977"},- {"message": "Image pulled successfully for g00r0", "timestamp": "2"},- {"message": "Collecting trl>=1.4.0", "timestamp": "3"},- {"message": " Downloading trl-1.8.0-py3-none-any.whl.metadata (12 kB)", "timestamp": "4"},- {- "message": "Requirement already satisfied: jinja2 in /opt/conda/lib/python3.11/site-packages (from trl>=1.4.0) (3.1.6)",- "timestamp": "5",- },- {- "message": " \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501 863.2/863.2 kB 45.1 MB/s eta 0:00:00",- "timestamp": "6",- },- {"message": "Successfully installed accelerate-1.14.0 aiohttp-3.14.1", "timestamp": "7"},- {- "message": "Warning: You are sending unauthenticated requests to the HF Hub.",- "timestamp": "8",- },- {- "message": "[transformers] `torch_dtype` is deprecated! Use `dtype` instead!",- "timestamp": "9",- },- {- "message": "\rFetching 5 files: 0%| | 0/5 [00:00<?, ?it/s]\rFetching 5 files: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 5/5 [02:18<00:00, 27.69s/it] ",- "timestamp": "10",- },- {- "message": "\r 0%| | 0/1 [00:00<?, ?it/s]\x1b[A\r ",- "timestamp": "11",- },- {- "message": "\rMap: 0%| | 0/22 [00:00<?, ? examples/s]\rMap: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 22/22 [00:00<00:00, 1267.49 examples/s]",- "timestamp": "12",- },- {"message": "Model=Qwen/Qwen3-8B type=tool lr=0.0001 seed=42", "timestamp": "13"},- {"message": "Loaded: 22 train / 6 val (type=tool)", "timestamp": "14"},- {- "message": 'BT_PROGRESS {"step": 1, "total_steps": 21, "loss": 0.1959, "lr": 0.0}',- "timestamp": "15",- },- {- "message": "{'loss': '0.1959', 'grad_norm': '0.3122', 'learning_rate': '0', 'mean_token_accuracy': '0.9617', 'epoch': '0.3636'}",- "timestamp": "16",- },- {- "message": "{'eval_loss': '0.09065', 'eval_runtime': '5.037', 'eval_samples_per_second': '1.191'}",- "timestamp": "17",- },- {- "message": 'BT_EVAL {"step": 21, "epoch": 7.0, "eval_loss": 0.09065335988998413, "eval_runtime_s": 5.04, "eval_token_accuracy": 0.9747}',- "timestamp": "18",- },- {- "message": 'BT_CHECKPOINT {"step": 21, "epoch": 7.0, "path": "checkpoint-21"}',- "timestamp": "19",- },- {- "message": "{'train_runtime': '272.8', 'train_samples_per_second': '0.565', 'train_steps_per_second': '0.077', 'train_loss': '0.1258', 'epoch': '7'}",- "timestamp": "20",- },- {"message": "Adapter saved \u2192 /mnt/ckpts", "timestamp": "21"},- {"message": "Job already completed successfully, terminating job...", "timestamp": "22"},- ]- out = filter_activity_logs(logs)- messages = [line["message"] for line in out]- assert messages == [- "Creating the training job.",- "Image pulled successfully for g00r0",- "Model=Qwen/Qwen3-8B type=tool lr=0.0001 seed=42",- "Loaded: 22 train / 6 val (type=tool)",- "Eval @ step 21 — loss 0.09065, token acc 97.5%",- "Checkpoint saved: checkpoint-21 (step 21)",- "Training finished — train loss 0.1258, 273s",- "Adapter saved \u2192 /mnt/ckpts",- "Job already completed successfully, terminating job...",- ]- assert out[0]["ts"] == 1784323432231- assert all("\x1b" not in m and "\r" not in m and "\u2588" not in m for m in messages)-- many = [{"message": f"line {i}", "timestamp": i} for i in range(MAX_ACTIVITY_LINES + 10)]- capped = filter_activity_logs(many)- assert len(capped) == MAX_ACTIVITY_LINES- assert capped[-1]["message"] == f"line {MAX_ACTIVITY_LINES + 9}"---def test_poll_exposes_activity_feed():- """BT_EVAL / BT_CHECKPOINT surface as readable stage events; BT_PROGRESS stays chart-only."""- logs = [- {"message": "Training job status updated to TRAINING_JOB_RUNNING.", "timestamp": 1},- *_bt_logs(),- {"message": "Loading checkpoint shards: done", "timestamp": 2_000_000_000_000},- ]- snap = _poll(logs=logs)- assert [a["message"] for a in snap.activity] == [- "Training job status updated to TRAINING_JOB_RUNNING.",- "Eval @ step 10 — loss 3.12, token acc 58.0%",- "Checkpoint saved: checkpoint-10 (step 10)",- "Loading checkpoint shards: done",- ]---def test_provider_logs_transport_monitoring_without_training_examples():- payload = {- "policy_fingerprint": "frozen",- "checks": [{"key": "1:development:2", "state": "completed", "metrics": {"eval_loss": 0.2}}],- }- logs = [*_bt_logs(), {"message": "BT_MONITORING " + json.dumps(payload), "timestamp": 123}]- snapshot = _poll(logs=logs)- assert snapshot.raw["monitoring"] == payload- assert not any("BT_MONITORING" in item["message"] for item in snapshot.activity)- progress = progress_from_snapshot(snapshot)- assert progress["activity"] == snapshot.activity---def test_poll_maps_histories_into_monitor_series():- snap = _poll()- assert snap.state == "running"- assert snap.step == snap.trained_steps == 10- assert snap.total_steps == 30- assert snap.loss_series == [- {"step": 5, "train_loss": 2.51},- {"step": 10, "train_loss": 2.1, "eval_loss": 3.12},- ]- assert snap.learning_rate_series == [- {"step": 5, "value": 1e-5},- {"step": 10, "value": 9e-6},- ]- assert snap.grad_norm_series == [- {"step": 5, "value": 1.9},- {"step": 10, "value": 1.4},- ]- assert snap.token_accuracy_series == [- {"step": 5, "train": 0.61},- {"step": 10, "train": 0.65, "eval": 0.58},- ]- assert snap.tokens_processed == 8192- assert snap.estimated_finish is not None- assert snap.output_model_name == ""---def test_poll_maps_checkpoint_rows_with_losses():- snap = _poll()- assert len(snap.checkpoints) == 1- row = snap.checkpoints[0]- assert row["step"] == 10- assert row["path"] == "checkpoint-10"- assert row["train_loss"] == 2.1- assert row["valid_loss"] == 3.12- assert row["valid_mean_token_accuracy"] == 0.58- assert row["has_eval"] is True---def test_poll_success_sets_output_model_name():- snap = _poll(state="TRAINING_JOB_COMPLETED")- assert snap.state == "succeeded"- assert snap.output_model_name == "baseten/job-9/final"---def test_progress_from_snapshot_feeds_monitor_charts():- progress = progress_from_snapshot(_poll())- assert progress["trained_steps"] == 10- assert progress["total_steps"] == 30- assert [p["step"] for p in progress["metrics"]["loss"]] == [5, 10]- assert [p["value"] for p in progress["metrics"]["learning_rate"]] == [1e-5, 9e-6]- assert [p["value"] for p in progress["metrics"]["grad_norm"]] == [1.9, 1.4]- assert progress["metrics"]["token_accuracy"] == [- {"step": 5, "train": 0.61},- {"step": 10, "train": 0.65, "eval": 0.58},- ]- assert progress["latest_train_loss"] == 2.1- assert progress["latest_eval_loss"] == 3.12---def test_progress_from_snapshot_keeps_pr367_live_metric_contract():- """Flat keys + raw histories the FE reads (finetuning-progress.ts, LiveMetricsChart)."""- progress = progress_from_snapshot(_poll())- assert progress["train_loss"] == 2.1- assert progress["eval_loss"] == 3.12- assert progress["learning_rate"] == 9e-6- assert progress["token_accuracy"] == 0.65- assert progress["eval_token_accuracy"] == 0.58- assert progress["current_epoch"] == 1.0- assert progress["eta_s"] == 180.0- assert [p["step"] for p in progress["metrics_history"]] == [5, 10]- assert progress["metrics_history"][1]["grad_norm"] == 1.4- assert [p["step"] for p in progress["eval_history"]] == [10]- assert progress["eval_history"][0]["eval_token_accuracy"] == 0.58---def test_cancel_posts_stop_endpoint(settings):- settings.BASETEN_API_KEY = "test-key"- with patch("requests.post") as post:- post.return_value.raise_for_status.return_value = None- BasetenRunner().cancel(_REMOTE_ID)- url = post.call_args.args[0] if post.call_args.args else post.call_args.kwargs["url"]- assert url.endswith("/v1/training_projects/proj-1/jobs/job-9/stop")---def test_get_runner_registers_baseten(settings):- settings.FINETUNING_BACKEND = "baseten"- assert isinstance(get_runner(), BasetenRunner)---def _fake_plan():- from overbae.services.finetuning_policy import BasetenTrainingPlan-- return BasetenTrainingPlan(- context_length=4096,- n_epochs=3,- batch_size=8,- per_device_batch=1,- grad_accum=8,- learning_rate=1e-4,- warmup_ratio=0.05,- weight_decay=0.01,- lora_r=16,- lora_alpha=32,- lora_dropout=0.05,- lora_target_modules="all-linear",- packing=False,- )---def test_config_source_validates_against_installed_sdk(settings):- """TrainingProject is strict (extra='forbid'); the project value must land on ``name``,- because push upserts projects by name."""- pytest.importorskip("truss_train")- settings.BASETEN_PROJECT = "overmind-dev"-- job = SimpleNamespace(- id="j1", name="my ft job!", base_model="Qwen/Qwen3-8B", hyperparameters={}- )- src = BasetenRunner()._build_config_source(- job=job,- gpu_type="H100",- gpu_count=1,- dataset_type="chat",- plan=_fake_plan(),- project_name="overmind-dev",- )-- ns: dict = {}- exec(src, ns) # noqa: S102 — pydantic validation IS the assertion- tp = ns["training_project"]- assert tp.name == "overmind-dev"- assert tp.job.name == "my-ft-job-" # sanitised per-job label- assert tp.job.runtime.environment_variables["MAX_LENGTH"] == "4096"- assert tp.job.compute.accelerator.count == 1- # Gated HF models need the workspace secret wired explicitly.- from truss_train import SecretReference-- assert tp.job.runtime.environment_variables["HF_TOKEN"] == SecretReference(- name="HF_ACCESS_TOKEN"- )- assert tp.job.runtime.environment_variables["HUGGING_FACE_HUB_TOKEN"] == SecretReference(- name="HF_ACCESS_TOKEN"- )---def test_ensure_trussrc_rewrites_from_settings(settings, tmp_path, monkeypatch):- """HOME == TMPDIR in workers, so a swept /data/tmp must not break the next push."""- remote_factory = pytest.importorskip("truss.remote.remote_factory")- settings.BASETEN_API_KEY = "sk-test-123"- trussrc = tmp_path / ".trussrc"- monkeypatch.setattr(remote_factory, "USER_TRUSSRC_PATH", trussrc)-- BasetenRunner()._ensure_trussrc()-- content = trussrc.read_text()- assert "[baseten]" in content- assert "api_key = sk-test-123" in content- assert "remote_provider = baseten" in content- assert remote_factory.RemoteFactory.load_remote_config("baseten").configs["api_key"] == (- "sk-test-123"- )---def test_cleanup_tmp_never_sweeps_dotfiles(settings, tmp_path):- """HOME == TMPDIR in the containers, so dotfiles (.trussrc, .aws) are config, not scratch."""- import os-- from overbae.tasks.cleanup_tmp import cleanup_data_tmp-- settings.TMPDIR = str(tmp_path)- old = ("stale.txt", ".trussrc")- for name in old:- p = tmp_path / name- p.write_text("x")- os.utime(p, (0, 0)) # ancient mtime — eligible for sweep-- cleanup_data_tmp()-- assert not (tmp_path / "stale.txt").exists()- assert (tmp_path / ".trussrc").exists()---def test_config_source_has_no_id_kwarg():- job = SimpleNamespace(id="j1", name="ft", base_model="Qwen/Qwen3-8B", hyperparameters={})- src = BasetenRunner()._build_config_source(- job=job,- gpu_type="H100",- gpu_count=1,- dataset_type="chat",- plan=_fake_plan(),- project_name="overmind-dev",- )- assert 'name="overmind-dev"' in src- assert "id=" not in srcdiff --git a/tests/test_finetuning_catalog.py b/tests/test_finetuning_catalog.pyindex 06f90238..25029cb0 100644--- a/tests/test_finetuning_catalog.py+++ b/tests/test_finetuning_catalog.py@@ -36,8 +36,7 @@ _GENERATION_PATTERNS = (@pytest.mark.django_db[email protected]("backend", ["baseten", "modal", "together"])-def test_api_models_endpoint_matches_shared_catalog_service(backend):+def test_api_models_endpoint_matches_shared_catalog_service():user = User.objects.create_user(email=f"catalog-{uuid.uuid4().hex[:8]}@example.com",password="pass",@@ -48,7 +47,7 @@ def test_api_models_endpoint_matches_shared_catalog_service(backend):client = APIClient()client.force_authenticate(user=user)- with override_settings(FINETUNING_BACKEND=backend):+ with override_settings(FINETUNING_BACKEND="modal"):response = client.get(reverse("finetuningjob-models"), {"has_tool_calling": "true"})expected = fetch_finetuning_model_catalog(has_tool_calling=True)@@ -63,7 +62,6 @@ def test_api_catalog_response_schema_accepts_modal_backend():"tiers": [],"models": {},"has_tool_calling": False,- "max_context": None,"monitoring": {"schedule_modes": ["adaptive", "steps", "epoch", "off"]},})@@ -74,7 +72,7 @@ def test_api_catalog_response_schema_accepts_modal_backend():def test_catalog_carries_no_capability_scores():assert [m["id"] for m in _CATALOG if "capabilities" in m] == []- with override_settings(FINETUNING_BACKEND="baseten"):+ with override_settings(FINETUNING_BACKEND="modal"):exported = [m for models in tier_models().values() for m in models]assert [m["id"] for m in exported if "capabilities" in m] == []diff --git a/tests/test_finetuning_context_length.py b/tests/test_finetuning_context_length.pyindex fe32dc79..8e8b520f 100644--- a/tests/test_finetuning_context_length.py+++ b/tests/test_finetuning_context_length.py@@ -18,51 +18,49 @@ from overbae.modal.model_registry import (min_sft_context_length,)from overbae.models import Capability, EvalSet-from overbae.services.finetuning_runner import baseten_context_length+from overbae.services.finetuning_runner import snap_context_lengthfrom overbae.services.recommendation.analysis import build_analysisfrom overbae.services.recommendation.constraints import eligible_modelsfrom overbae.services.recommendation.hyperparams import compute_hyperparamspytestmark = pytest.mark.covers("plans")-_POLICY = get_training_context_policy("baseten")+_POLICY = get_training_context_policy("modal")_BUCKETS = sorted(int(b) for b in _POLICY["context_buckets"])_HEADROOM = int(_POLICY["context_headroom"])class TestCatalogContextPolicy:def test_policy_comes_from_catalog(self):- assert _BUCKETS, "baseten context buckets must be defined in models.json"+ assert _BUCKETS, "modal context buckets must be defined in models.json"assert _HEADROOM > 0def test_unknown_backend_raises(self):with pytest.raises(KeyError):get_training_context_policy("no-such-backend")- def test_baseten_models_are_not_uniformly_capped(self):- assert get_sft_context_length("Qwen/Qwen3-8B", backend="baseten") == 40960- assert get_sft_context_length("Qwen/Qwen2.5-7B-Instruct", backend="baseten") == 32768- assert (- get_sft_context_length("meta-llama/Llama-3.1-8B-Instruct", backend="baseten") == 131072- )- assert get_sft_context_length("Qwen/Qwen3.5-9B", backend="baseten") == 262144- assert get_sft_context_length("fdtn-ai/antares-1b", backend="baseten") == 131072+ def test_modal_models_are_not_uniformly_capped(self):+ assert get_sft_context_length("Qwen/Qwen3-8B", backend="modal") == 40960+ assert get_sft_context_length("Qwen/Qwen2.5-7B-Instruct", backend="modal") == 32768+ assert get_sft_context_length("meta-llama/Llama-3.1-8B-Instruct", backend="modal") == 131072+ assert get_sft_context_length("Qwen/Qwen3.5-9B", backend="modal") == 262144+ assert get_sft_context_length("fdtn-ai/antares-1b", backend="modal") == 131072def test_min_sft_context_length(self):- smallest = min_sft_context_length("baseten")+ smallest = min_sft_context_length("modal")assert smallest is not Noneassert smallest >= _BUCKETS[0]class TestRecommendFiltersByDatasetContext:- @override_settings(FINETUNING_BACKEND="baseten")+ @override_settings(FINETUNING_BACKEND="modal")def test_eligible_models_drop_short_context(self):# 50k tokens: Qwen2.5 (32k) and Qwen3 dense (40k) drop; Llama/Qwen3.5 remain.filtered, excluded = eligible_models(has_tool_calling=False, max_row_tokens=50_000)surviving = {m["id"] for models in filtered.values() for m in models}assert surviving, "some models must still fit at 50k"assert all(- (get_sft_context_length(mid, backend="baseten") or 0) >= 50_000 + _HEADROOM+ (get_sft_context_length(mid, backend="modal") or 0) >= 50_000 + _HEADROOMfor mid in surviving)assert "Qwen/Qwen2.5-7B-Instruct" not in surviving@@ -72,7 +70,7 @@ class TestRecommendFiltersByDatasetContext:reasons = {e.model: e.reason for e in excluded}assert "50,000" in reasons["Qwen/Qwen3-8B"]- @override_settings(FINETUNING_BACKEND="baseten")+ @override_settings(FINETUNING_BACKEND="modal")def test_analysis_excludes_short_context_models(self):stats = {"num_examples": 100,@@ -85,13 +83,13 @@ class TestRecommendFiltersByDatasetContext:assert analysis["candidates"]for row in analysis["candidates"]:- model_max = get_sft_context_length(row["model"], backend="baseten")+ model_max = get_sft_context_length(row["model"], backend="modal")assert model_max is not None and model_max >= 50_000 + _HEADROOMassert any("50,000" in e["reason"] for e in analysis["excluded"])- @override_settings(FINETUNING_BACKEND="baseten")+ @override_settings(FINETUNING_BACKEND="modal")def test_no_candidate_survives_rows_past_every_context_limit(self):- # Past every baseten SFT max.+ # Past every SFT max.max_tokens = 1_000_000eligible, _excluded = eligible_models(has_tool_calling=False, max_row_tokens=max_tokens)assert not eligible@@ -115,33 +113,33 @@ class TestRecommendFiltersByDatasetContext:)-class TestBasetenContextLength:+class TestSnapContextLength:def test_default_is_smallest_bucket(self):- assert baseten_context_length(0) == _BUCKETS[0]- assert baseten_context_length(100) == _BUCKETS[0]+ assert snap_context_length(0) == _BUCKETS[0]+ assert snap_context_length(100) == _BUCKETS[0]def test_snaps_up_never_down(self):# A row over a bucket boundary must land in the next bucket — TRL would# silently truncate it (corrupting targets) if we snapped down.- assert baseten_context_length(_BUCKETS[0] + 1) == _BUCKETS[1]- assert baseten_context_length(11051) == 16384+ assert snap_context_length(_BUCKETS[0] + 1) == _BUCKETS[1]+ assert snap_context_length(11051) == 16384def test_headroom_pushes_boundary_rows_up(self):- assert baseten_context_length(_BUCKETS[1] - _HEADROOM) == _BUCKETS[1]- assert baseten_context_length(_BUCKETS[1]) == _BUCKETS[2]+ assert snap_context_length(_BUCKETS[1] - _HEADROOM) == _BUCKETS[1]+ assert snap_context_length(_BUCKETS[1]) == _BUCKETS[2]def test_requested_wins_when_larger_than_need(self):- assert baseten_context_length(100, requested=32768) == 32768+ assert snap_context_length(100, requested=32768) == 32768def test_caps_at_model_max_when_rows_fit(self):# Requested context can still be clamped down when the dataset is short.- assert baseten_context_length(100, model_max=4096, requested=16384) == 4096+ assert snap_context_length(100, model_max=4096, requested=16384) == 4096def test_refuses_when_model_cannot_cover_longest_row(self):from overbae.services.finetuning_policy import TrainingPlanErrorwith pytest.raises(TrainingPlanError, match="refusing to clamp"):- baseten_context_length(20000, model_max=4096)+ snap_context_length(20000, model_max=4096)@pytest.mark.parametrize(("needed_tokens", "requested", "expected"),@@ -150,7 +148,7 @@ class TestBasetenContextLength:def test_uncapped_context_never_truncates_to_largest_bucket(self, needed_tokens, requested, expected):- assert baseten_context_length(needed_tokens, requested=requested) == expected+ assert snap_context_length(needed_tokens, requested=requested) == expectedclass TestRecommenderIncludesContext:@@ -162,24 +160,11 @@ class TestRecommenderIncludesContext:"max_batch_size": 8,}- def test_baseten_hyperparams_include_snapped_context(self):- with override_settings(FINETUNING_BACKEND="baseten"):+ def test_hyperparams_include_snapped_context(self):+ with override_settings(FINETUNING_BACKEND="modal"):hp = compute_hyperparams(500, model_entry=self._ENTRY, max_row_tokens=11051)assert hp["context_length"] == 16384- def test_baseten_context_refuses_short_catalog_max(self):- entry = {**self._ENTRY, "context_length_sft": 4096}- with (- override_settings(FINETUNING_BACKEND="baseten"),- pytest.raises(Exception, match="refusing to clamp|only supports"),- ):- compute_hyperparams(500, model_entry=entry, max_row_tokens=11051)-- def test_together_omits_context_length_key(self):- with override_settings(FINETUNING_BACKEND="together"):- hp = compute_hyperparams(500, model_entry=self._ENTRY, max_row_tokens=11051)- assert "context_length" not in hp-@pytest.mark.django_dbclass TestJobSerializerContextValidation:@@ -256,7 +241,7 @@ class TestJobSerializerContextValidation:return FinetuningJobSerializer(data=payload, context={"request": _Req(user)})- @override_settings(FINETUNING_BACKEND="baseten")+ @override_settings(FINETUNING_BACKEND="modal")def test_rows_within_model_max_pass(self):s = self._serializer(max_token_length=12309, base_model="Qwen/Qwen3-8B")assert s.is_valid(), s.errors@@ -273,14 +258,7 @@ class TestJobSerializerContextValidation:assert not s.is_valid()assert field in s.errors- @override_settings(FINETUNING_BACKEND="baseten")- def test_rows_over_model_max_still_rejected(self):- model_max = get_sft_context_length("Qwen/Qwen2.5-7B-Instruct", backend="baseten")- s = self._serializer(max_token_length=model_max + 1, base_model="Qwen/Qwen2.5-7B-Instruct")- assert not s.is_valid()- assert "dataset" in s.errors-- @override_settings(FINETUNING_BACKEND="baseten")+ @override_settings(FINETUNING_BACKEND="modal")def test_full_ft_rejected_when_catalog_disables_it(self):"""Gemma 4 31B has full.enabled=false — wizard must not be able to submit Full."""s = self._serializer(max_token_length=512, base_model="google/gemma-4-31B-it")@@ -291,40 +269,3 @@ class TestJobSerializerContextValidation:}assert not s.is_valid()assert "hyperparameters" in s.errors-- @override_settings(FINETUNING_BACKEND="baseten")- def test_full_rejected_lora_accepted_between_their_context_lengths(self):- """LoRA's lighter optimizer state can train at a longer context than full on the- same model — a dataset row between the two must only be submittable as LoRA."""- from unittest.mock import patch-- entry = {- "id": "Qwen/Qwen3-8B",- "display": "Qwen 3 8B",- "params": "8B",- "total_params_b": 8.2,- "context_length_sft": 131072,- "max_batch_size": 8,- "min_batch_size": 1,- "supports_tool_calling": True,- "training_type": {- "full": {"enabled": True, "context_length": 4096, "validated_context_length": True},- "lora": {- "enabled": True,- "context_length": 32768,- "validated_context_length": True,- },- },- }- with patch("overbae.services.recommendation.find_catalog_model", return_value=entry):- lora = self._serializer(max_token_length=10_000, base_model="Qwen/Qwen3-8B")- assert lora.is_valid(), lora.errors-- full = self._serializer(max_token_length=10_000, base_model="Qwen/Qwen3-8B")- full.initial_data["hyperparameters"] = {- "learning_rate": 2e-5,- "warmup_ratio": 0.05,- "training_type": {"type": "Full"},- }- assert not full.is_valid()- assert "Switch to LoRA" in full.errors["dataset"][0]diff --git a/tests/test_finetuning_context_reco.py b/tests/test_finetuning_context_reco.pyindex e2eb5bef..6ba3fe6f 100644--- a/tests/test_finetuning_context_reco.py+++ b/tests/test_finetuning_context_reco.py@@ -22,7 +22,6 @@ from overbae.services.finetuning_pricing import (estimate_training_cost,estimate_training_time_s,humanize_duration,- training_price_per_million,)from overbae.services.recommendation.analysis import build_analysisfrom overbae.services.recommendation.capability_context import collect_capability_context@@ -66,51 +65,16 @@ def _dataset()-def test_together_price_tiers_match_published_rates():- # together.ai/pricing SFT rates (retrieved 2026-07-13)- assert training_price_per_million(8, use_lora=True, backend="together") == 0.48- assert training_price_per_million(8, use_lora=False, backend="together") == 0.54- assert training_price_per_million(32, use_lora=True, backend="together") == 1.50- assert training_price_per_million(70, use_lora=True, backend="together") == 2.90- assert training_price_per_million(70, use_lora=False, backend="together") == 3.20- # >100B models are individually priced.- assert training_price_per_million(120, use_lora=True, backend="together") is None---def test_baseten_bills_per_gpu_minute_not_per_token():- assert training_price_per_million(8, use_lora=True, backend="baseten") is None- est = estimate_training_cost(1_000_000, total_params_b=8, use_lora=True, backend="baseten")- assert est is not None- assert est["usd"] > 0--def test_modal_estimate_uses_its_per_second_gpu_rate():tokens = 1_000_000seconds = estimate_training_time_s(tokens, total_params_b=4, use_lora=True)estimate = estimate_training_cost(tokens, total_params_b=4, use_lora=True, backend="modal")assert estimate["usd"] == pytest.approx(round(seconds * 0.001097, 4))- baseten = estimate_training_cost(tokens, total_params_b=4, use_lora=True, backend="baseten")- assert baseten["usd"] == pytest.approx(round(baseten["billed_minutes"] * 0.10833, 4))---def test_cost_estimate_applies_together_minimum_charge():- tiny = estimate_training_cost(1000, total_params_b=8, use_lora=True, backend="together")- assert tiny is not None- assert tiny["minimum_applied"] is True- assert tiny["usd"] == 4.00-- big = estimate_training_cost(100_000_000, total_params_b=8, use_lora=True, backend="together")- assert big is not None- assert big["minimum_applied"] is False- assert big["usd"] == pytest.approx(48.0)def test_cost_estimate_none_for_unpriced_backend_or_empty():- assert estimate_training_cost(0, total_params_b=8, use_lora=True, backend="together") is None- # >100B Together models are individually priced.- assert (- estimate_training_cost(1000, total_params_b=120, use_lora=True, backend="together") is None- )+ assert estimate_training_cost(0, total_params_b=8, use_lora=True, backend="modal") is None+ assert estimate_training_cost(1000, total_params_b=8, use_lora=True, backend="unknown") is Nonedef test_time_estimate_scales_with_model_size_and_tokens():@@ -139,21 +103,21 @@ def test_estimate_training_run_uses_epochs_and_lora():n_epochs=1,total_params_b=8,use_lora=True,- backend="together",+ backend="modal",)three = estimate_training_run(dataset_tokens=10_000,n_epochs=3,total_params_b=8,use_lora=True,- backend="together",+ backend="modal",)full = estimate_training_run(dataset_tokens=10_000,n_epochs=1,total_params_b=8,use_lora=False,- backend="together",+ backend="modal",)assert three["trained_tokens"] == one["trained_tokens"] * 3assert three["time_estimate"]["seconds"] > one["time_estimate"]["seconds"]@@ -210,7 +174,7 @@ def test_recommended_hyperparams_scale_with_dataset_size():)entry = {"min_batch_size": 1, "max_batch_size": 32, "total_params_b": 8.0}- with override_settings(FINETUNING_BACKEND="baseten"):+ with override_settings(FINETUNING_BACKEND="modal"):thousands = compute_hyperparams(5_000, model_entry=entry)large = compute_hyperparams(19_704, model_entry=entry)@@ -222,7 +186,7 @@ def test_recommended_hyperparams_scale_with_dataset_size():assert steps < 2_000reasons = hyperparam_provenance(- large, num_examples=19_704, params_b=8.0, use_lora=True, backend="baseten"+ large, num_examples=19_704, params_b=8.0, use_lora=True, backend="modal")assert "optimizer steps" in reasons["batch_size"]assert "at batch 1" in reasons["batch_size"]@@ -411,7 +375,7 @@ def test_recommendation_warns_without_excluding_models_for_evaluation_context():train = _dataset(project, capability, intent="ft", trace_ids=["train"])evaluation = frozen_dataset(project,- [{"input": "x" * 120000, "expected_output": "answer"}],+ [{"input": "x" * 1_200_000, "expected_output": "answer"}],capability=capability,contract="eval",)diff --git a/tests/test_finetuning_download_progress.py b/tests/test_finetuning_download_progress.pyindex 94913fc1..569a6800 100644--- a/tests/test_finetuning_download_progress.py+++ b/tests/test_finetuning_download_progress.py@@ -9,7 +9,6 @@ import pytestfrom overbae.services.finetuning_runner import (PollSnapshot,filter_activity_logs,- parse_download_stage,progress_from_snapshot,)@@ -20,25 +19,6 @@ def _logs(*messages: str) -> list[dict]:return [{"message": m, "timestamp": str(1_000_000 + i)} for i, m in enumerate(messages)]-def test_parse_download_stage_reads_latest_stage_and_download():- logs = _logs(- 'BT_STAGE {"stage": "downloading_base_model", "model": "Qwen/Qwen2.5-14B-Instruct"}',- 'BT_DOWNLOAD {"pct": 12, "downloaded_gb": 3.4, "total_gb": 28.0}',- 'BT_DOWNLOAD {"pct": 42, "downloaded_gb": 11.8, "total_gb": 28.0}',- 'BT_STAGE {"stage": "loading_model"}',- )- stage, download = parse_download_stage(logs)- assert stage == "loading_model"- assert download == {"pct": 42, "downloaded_gb": 11.8, "total_gb": 28.0}---def test_parse_download_stage_backward_compatible():- # Old jobs and Together emit neither line.- logs = _logs("+ python -u train.py", 'BT_PROGRESS {"step": 1, "total_steps": 30, "loss": 2.5}')- assert parse_download_stage(logs) == ("", None)- assert parse_download_stage([]) == ("", None)--def test_filter_activity_logs_keeps_stage_lines_only():logs = _logs('BT_STAGE {"stage": "downloading_base_model", "model": "Qwen"}',diff --git a/tests/test_finetuning_in_training_eval.py b/tests/test_finetuning_in_training_eval.pyindex 8cc3a57d..db71d36b 100644--- a/tests/test_finetuning_in_training_eval.py+++ b/tests/test_finetuning_in_training_eval.py@@ -59,7 +59,7 @@ def _setup(*, with_eval_link=True):eval_incumbent_before=True,eval_model_before=False,status=FinetuningJob.Status.RUNNING,- provider=FinetuningJob.Provider.BASETEN,+ provider=FinetuningJob.Provider.MODAL,remote_job_id="proj-1:job-x",triggered_by=u,)@@ -291,7 +291,7 @@ def test_cancel_revokes_related_eval_runs(sft, fake_modal):@override_settings(INFERENCE_API_URL="https://gateway.example.modal.run")def test_group_jobs_share_one_baseline_eval_run(django_capture_on_commit_callbacks):_, p, job_a, eval_ds, eset = _setup()- _basetenify(job_a)+ _qwen3_job(job_a)gid = uuid.uuid4()job_a.group_id = gidjob_a.baseline_model = "openai/gpt-5.6-sol"@@ -307,7 +307,7 @@ def test_group_jobs_share_one_baseline_eval_run(django_capture_on_commit_callbaceval_incumbent_before=True,eval_model_before=False,status=FinetuningJob.Status.RUNNING,- provider=FinetuningJob.Provider.BASETEN,+ provider=FinetuningJob.Provider.MODAL,group_id=gid,baseline_model="openai/gpt-5.6-sol",triggered_by=job_a.triggered_by,@@ -322,7 +322,7 @@ def test_group_jobs_share_one_baseline_eval_run(django_capture_on_commit_callbaceval_incumbent_before=True,eval_model_before=False,status=FinetuningJob.Status.RUNNING,- provider=FinetuningJob.Provider.BASETEN,+ provider=FinetuningJob.Provider.MODAL,group_id=gid,baseline_model="openai/gpt-5.6-sol",triggered_by=job_a.triggered_by,@@ -364,7 +364,7 @@ def test_cancel_leaves_shared_group_baseline_running():eval_set=eset,base_model="other/model",status=FinetuningJob.Status.RUNNING,- provider=FinetuningJob.Provider.BASETEN,+ provider=FinetuningJob.Provider.MODAL,group_id=gid,triggered_by=u,)@@ -400,8 +400,8 @@ def test_cancel_leaves_shared_group_baseline_running():assert FinetuningJobEval.objects.get(job=job_b).status == FinetuningJobEval.Status.RUNNING-def _basetenify(job):- job.provider = FinetuningJob.Provider.BASETEN+def _qwen3_job(job):+ job.provider = FinetuningJob.Provider.MODALjob.base_model = "Qwen/Qwen3-8B"job.remote_job_id = f"proj-1:{job.id}"job.save(update_fields=["provider", "base_model", "remote_job_id"])@@ -438,12 +438,12 @@ def _ready_base_deployment(project, base="Qwen/Qwen3-8B"):@override_settings(INFERENCE_API_URL="https://gateway.example.modal.run")-def test_baseten_baseline_uses_an_existing_ready_base_deployment(+def test_baseline_uses_an_existing_ready_base_deployment(django_capture_on_commit_callbacks, fake_llm):fake_llm.catalog_models = []_, _, job, _, _ = _setup()- _basetenify(job)+ _qwen3_job(job)dep = _ready_base_deployment(job.project)# The enqueue is deferred to transaction.on_commit — execute the callbacks.@@ -474,7 +474,7 @@ def test_baseten_baseline_uses_an_existing_ready_base_deployment(def test_baseline_delta_computes_when_baseline_lands_after_final():_, _, job, _, _ = _setup()- _basetenify(job)+ _qwen3_job(job)final_run = EvalRun.objects.create(project=job.project,name="final",@@ -562,7 +562,7 @@ def test_deploy_base_model_for_eval_does_not_provision_an_unavailable_route(from overbae.tasks.model_deployment import deploy_base_model_for_eval_, _, job, _, _ = _setup()- _basetenify(job)+ _qwen3_job(job)calls: list = []_fake_modal(monkeypatch, calls)@@ -586,7 +586,7 @@ def test_deploy_base_model_dedupes_ready_deployment(from overbae.tasks.model_deployment import deploy_base_model_for_eval_, _, job, _, _ = _setup()- _basetenify(job)+ _qwen3_job(job)_ready_base_deployment(job.project)calls: list = []@@ -610,7 +610,7 @@ def test_deploy_base_model_skips_cancelled_job(monkeypatch):from overbae.tasks.model_deployment import deploy_base_model_for_eval_, _, job, _, _ = _setup()- _basetenify(job)+ _qwen3_job(job)job.status = FinetuningJob.Status.CANCELLEDjob.save(update_fields=["status"])@@ -625,15 +625,13 @@ def test_deploy_base_model_skips_cancelled_job(monkeypatch):@override_settings(INFERENCE_API_URL="https://gateway.example.modal.run")-def test_baseten_final_eval_fires_after_ready_deployment(- django_capture_on_commit_callbacks, fake_llm-):+def test_final_eval_fires_after_ready_deployment(django_capture_on_commit_callbacks, fake_llm):fake_llm.catalog_models = []from overbae.models import DeployedModel_, _, job, _, _ = _setup()- _basetenify(job)- job.output_model_name = "baseten/abc/final"+ _qwen3_job(job)+ job.output_model_name = "runs/abc/final"job.status = FinetuningJob.Status.SUCCEEDEDjob.save(update_fields=["output_model_name", "status"])@@ -655,7 +653,7 @@ def test_baseten_final_eval_fires_after_ready_deployment(assert apply.call_count == 1final = FinetuningJobEval.objects.get(job=job, kind=FinetuningJobEval.Kind.FINAL)- # Eval targets the served vLLM model id, not the synthetic baseten name.+ # Eval targets the served vLLM model id, not the job's output model name.assert final.model_id == "ft-abc-qwen3-8b"assert final.status == FinetuningJobEval.Status.RUNNINGref = final.eval_run.model_refdiff --git a/tests/test_finetuning_lifecycle.py b/tests/test_finetuning_lifecycle.pyindex abfac941..78f27cd8 100644--- a/tests/test_finetuning_lifecycle.py+++ b/tests/test_finetuning_lifecycle.py@@ -61,14 +61,13 @@ def test_backward_compat_missing_progress():def test_scrub_backend_names_redacts_all_providers():- assert scrub_backend_names("Client error: Secret hf_access_token not found in Baseten") == (+ assert scrub_backend_names("Client error: Secret hf_access_token not found in Modal") == ("Client error: Secret hf_access_token not found in the provider")assert scrub_backend_names("NEBIUS_API_KEY is not set") == "the provider_API_KEY is not set"assert (scrub_backend_names("Deployed via Modal Functions") == "Deployed via the provider Functions")- assert scrub_backend_names("Together AI job failed") == "the provider job failed"assert scrub_backend_names("") == ""assert scrub_backend_names("all good, no backend mentioned") == "all good, no backend mentioned"# A letter-only trailing boundary would rewrite identifiers like ``modal_shared``.diff --git a/tests/test_finetuning_monitor.py b/tests/test_finetuning_monitor.pyindex 374b2abb..9a4df23b 100644--- a/tests/test_finetuning_monitor.py+++ b/tests/test_finetuning_monitor.py@@ -13,7 +13,6 @@ from rest_framework_simplejwt.tokens import RefreshTokenfrom overbae.models import FinetuningJob, Project, ProjectMembership, Userfrom overbae.services.finetuning_runner import (PollSnapshot,- parse_together_metrics,progress_from_snapshot,)from overbae.tasks.finetuning import observe_finetuning_job@@ -40,30 +39,6 @@ def _setup():return u, p, ds-def test_parse_together_metrics_splits_series():- raw = [- {- "train/global_step": 1,- "train/loss": 2.43,- "train/grad_norm": 1.21,- "train/learning_rate": 1e-5,- },- {- "train/global_step": 2,- "train/loss": 2.11,- "train/grad_norm": 0.94,- "train/learning_rate": 9e-6,- },- {"train/global_step": 2, "eval/loss": 2.05},- ]- loss, lr, grad = parse_together_metrics(raw)- assert len(loss) == 2- assert loss[1]["train_loss"] == 2.11- assert loss[1]["eval_loss"] == 2.05- assert [p["value"] for p in lr] == [1e-5, 9e-6]- assert [p["value"] for p in grad] == [1.21, 0.94]--def test_progress_from_snapshot_computes_percent_and_eta():from datetime import datetime, timedelta@@ -145,7 +120,7 @@ def test_cancel_calls_remote_runner_and_sets_cancelled():dataset=ds,base_model="m",status=FinetuningJob.Status.RUNNING,- provider=FinetuningJob.Provider.BASETEN,+ provider=FinetuningJob.Provider.MODAL,remote_job_id="proj-1:job-remote-1",celery_task_id="celery-abc",)@@ -172,7 +147,7 @@ def test_cancel_still_succeeds_when_remote_cancel_fails():dataset=ds,base_model="m",status=FinetuningJob.Status.RUNNING,- provider=FinetuningJob.Provider.BASETEN,+ provider=FinetuningJob.Provider.MODAL,remote_job_id="proj-1:job-xyz",)mock_runner = MagicMock()diff --git a/tests/test_finetuning_new.py b/tests/test_finetuning_new.pyindex 690f5b33..b084cd47 100644--- a/tests/test_finetuning_new.py+++ b/tests/test_finetuning_new.py@@ -3,8 +3,7 @@ from __future__ import annotationsimport gzipimport jsonimport uuid-from types import SimpleNamespace-from unittest.mock import MagicMock, patch+from unittest.mock import patchimport pytestfrom conftest import EVAL_ROWS, frozen_dataset@@ -20,7 +19,7 @@ from factories import (from rest_framework.test import APIClientfrom modal_shared.training_data import row_key-from overbae.modal.model_registry import baseten_finetuning_catalog+from overbae.modal.model_registry import finetuning_catalogfrom overbae.models import (Capability,Dataset,@@ -33,12 +32,7 @@ from overbae.models import ()from overbae.services.datasets.rows import row as _dataset_rowfrom overbae.services.datasets.rows import row_from_record-from overbae.services.finetuning_runner import (- BasetenRunner,- TogetherAIRunner,- get_runner,- together_suffix,-)+from overbae.services.finetuning_runner import ModalRunner, get_runnerfrom overbae.services.finetuning_tool_validation import check_tool_calling_rowsfrom overbae.services.finetuning_validator import (validate_dataset,@@ -232,8 +226,7 @@ class TestValidatorDB:class TestRecommenderLogic:pytestmark = pytest.mark.django_db(transaction=False)- def test_hyperparams_small_dataset(self, settings):- settings.FINETUNING_BACKEND = "together"+ def test_hyperparams_small_dataset(self):hp = compute_hyperparams(50, use_lora=True)assert hp["n_epochs"] == 2 # 100 // 50# OpenAI 0.2%-of-examples rule: round(0.002 * 50) → 0, floored to 1@@ -241,8 +234,7 @@ class TestRecommenderLogic:assert hp["learning_rate"] == 1e-4assert "training_type" in hp- def test_hyperparams_medium_dataset(self, settings):- settings.FINETUNING_BACKEND = "together"+ def test_hyperparams_medium_dataset(self):hp = compute_hyperparams(500, use_lora=True)assert hp["n_epochs"] == 3assert hp["batch_size"] == 1 # round(0.002 * 500) == 1@@ -275,18 +267,18 @@ class TestRecommenderLogic:assert hp["learning_rate"] == 5e-5def test_hyperparam_provenance_covers_stamped_knobs(self, settings):- settings.FINETUNING_BACKEND = "baseten"+ settings.FINETUNING_BACKEND = "modal"hp = compute_hyperparams(49, model_entry={"total_params_b": 8.0}, use_lora=True)reasons = hyperparam_provenance(- hp, num_examples=49, params_b=8.0, use_lora=True, backend="baseten"+ hp, num_examples=49, params_b=8.0, use_lora=True, backend="modal")assert {"n_epochs", "learning_rate", "batch_size", "warmup_ratio", "lora_r"} <= set(reasons)assert "49 examples" in reasons["n_epochs"]assert all(isinstance(v, str) and v for v in reasons.values())- def test_baseten_catalog_includes_batch_size_limits(self):+ def test_catalog_includes_batch_size_limits(self):# Model-agnostic: any entry can be disabled in models.json at any time.- entries = [m for tier in baseten_finetuning_catalog().values() for m in tier]+ entries = [m for tier in finetuning_catalog("modal").values() for m in tier]assert entriesfor m in entries:assert isinstance(m["min_batch_size"], int), m["id"]@@ -295,171 +287,15 @@ class TestRecommenderLogic:class TestRunnerAbstraction:- def test_get_runner_returns_together_runner_by_default(self, settings):- settings.FINETUNING_BACKEND = "together"- runner = get_runner()- assert isinstance(runner, TogetherAIRunner)+ def test_get_runner_returns_the_configured_backend(self):+ assert isinstance(get_runner(), ModalRunner)def test_get_runner_unknown_backend_raises(self):with pytest.raises(ValueError, match="Unknown fine-tuning backend"):get_runner("nonexistent_backend")- def test_together_suffix_strips_unsafe_characters(self):- assert (- together_suffix(- "huge rhinoceros · Qwen 2.5 7B Instruct",- fallback="ft-deadbeef",- )- == "huge-rhinoceros-qwen-2-5-7b-instruct"- )- assert together_suffix(None, fallback="ft-abc12345") == "ft-abc12345"- assert together_suffix(" ", fallback="ft-fallback1") == "ft-fallback1"-- def test_together_runner_submit_uploads_and_creates_job(self):- runner = TogetherAIRunner()-- job = SimpleNamespace(- id=uuid.uuid4(),- base_model="meta-llama/Llama-3.2-3B-Instruct",- name="smoke-test",- hyperparameters={- "n_epochs": 2,- "learning_rate": 1e-4,- "training_type": {- "type": "Lora",- "lora_r": 8,- "lora_alpha": 16,- "lora_dropout": 0.0,- "lora_trainable_modules": "all-linear",- },- },- )-- mock_client = MagicMock()- mock_client.files.upload.return_value = SimpleNamespace(id="file-123")- mock_client.fine_tuning.create.return_value = SimpleNamespace(id="ft-job-456")-- with patch.object(runner, "_client", return_value=mock_client):- result = runner.submit(- job=job,- training_file_path="/tmp/fake.jsonl",- num_examples=50,- )-- assert result.remote_id == "ft-job-456"- assert result.training_file_id == "file-123"- assert result.num_examples == 50- assert "ft-job-456" in result.run_url- mock_client.files.upload.assert_called_once_with(- file="/tmp/fake.jsonl", purpose="fine-tune"- )- assert mock_client.fine_tuning.create.call_args.kwargs["suffix"] == "smoke-test"-- def test_together_runner_submit_sanitizes_display_name_suffix(self):- runner = TogetherAIRunner()- job = SimpleNamespace(- id=uuid.uuid4(),- base_model="Qwen/Qwen2.5-7B-Instruct",- name="huge rhinoceros · Qwen 2.5 7B Instruct",- hyperparameters={"n_epochs": 1},- )- mock_client = MagicMock()- mock_client.files.upload.return_value = SimpleNamespace(id="file-123")- mock_client.fine_tuning.create.return_value = SimpleNamespace(id="ft-job-789")-- with patch.object(runner, "_client", return_value=mock_client):- runner.submit(job=job, training_file_path="/tmp/fake.jsonl", num_examples=10)-- assert (- mock_client.fine_tuning.create.call_args.kwargs["suffix"]- == "huge-rhinoceros-qwen-2-5-7b-instruct"- )-- def test_together_runner_submit_reuses_existing_file(self):- runner = TogetherAIRunner()-- job = SimpleNamespace(- id=uuid.uuid4(),- base_model="meta-llama/Llama-3.2-3B-Instruct",- name="reuse-test",- hyperparameters={"n_epochs": 1},- )-- mock_client = MagicMock()- mock_client.fine_tuning.create.return_value = SimpleNamespace(id="ft-reuse-789")-- with patch.object(runner, "_client", return_value=mock_client):- result = runner.submit(- job=job,- training_file_path="",- num_examples=None,- existing_file_id="file-already-uploaded",- )-- mock_client.files.upload.assert_not_called()- assert result.training_file_id == "file-already-uploaded"- assert result.remote_id == "ft-reuse-789"- assert result.num_examples is None-- def test_together_runner_poll_parses_response(self):- """Loss comes from event messages; step from the step field on each event."""- runner = TogetherAIRunner()- mock_client = MagicMock()-- fake_ft = SimpleNamespace(- status="running",- epochs_completed=1,- token_count=10000,- x_model_output_name=None,- x_model_output_path=None,- events=[- # Chronological order: oldest first (Together AI's natural order)- SimpleNamespace(- step=38,- type="checkpoint_save",- message="Step 38 train_loss=0.61",- ),- SimpleNamespace(- step=42,- type="checkpoint_save",- message="Step 42 train_loss=0.5432 eval_loss=0.6123",- ),- ],- )- mock_client.fine_tuning.retrieve.return_value = fake_ft-- with patch.object(runner, "_client", return_value=mock_client):- snap = runner.poll("ft-job-abc")-- assert snap.state == "running"- assert snap.train_loss == pytest.approx(0.5432)- assert snap.eval_loss == pytest.approx(0.6123)- assert snap.step == 42 # highest step from events-- def test_together_runner_poll_completed_state(self):- """x_model_output_name / x_model_output_path are the SDK's Pydantic field names."""- runner = TogetherAIRunner()- mock_client = MagicMock()-- fake_ft = SimpleNamespace(- status="completed",- epochs_completed=3,- token_count=50000,- x_model_output_name="myspace/llama-ft-abc",- x_model_output_path="https://weights.example.com/ft.bin",- events=[],- )- mock_client.fine_tuning.retrieve.return_value = fake_ft-- with patch.object(runner, "_client", return_value=mock_client):- snap = runner.poll("ft-job-done")-- assert runner.is_terminal_ok(snap.state)- assert snap.output_model_name == "myspace/llama-ft-abc"- assert snap.weights_url == "https://weights.example.com/ft.bin"-def test_terminal_state_classification(self):- runner = BasetenRunner()+ runner = ModalRunner()assert runner.is_terminal_ok("succeeded")assert not runner.is_terminal_ok("running")assert runner.is_terminal_fail("failed")@@ -574,23 +410,12 @@ class TestValidateDatasetEndpoint:class TestModelsEndpoint:- def test_models_returns_backend(self, settings):+ def test_models_returns_the_configured_backend(self):u, _, _ = _setup()- settings.FINETUNING_BACKEND = "together"r = auth_client(u).get(reverse("finetuningjob-models"))assert r.status_code == 200- assert r.data["backend"] == "together"- assert "tiers" in r.data- assert "models" in r.data-- def test_models_returns_baseten_backend(self, settings):- u, _, _ = _setup()- settings.FINETUNING_BACKEND = "baseten"-- r = auth_client(u).get(reverse("finetuningjob-models"))- assert r.status_code == 200- assert r.data["backend"] == "baseten"+ assert r.data["backend"] == "modal"assert set(r.data["tiers"]) == {"compact", "small", "mid", "large"}@@ -612,7 +437,7 @@ class TestRecommendEndpoint:assert 1 <= len(r.data["shown"]) <= 3def test_recommend_includes_provenance(self, settings):- settings.FINETUNING_BACKEND = "baseten"+ settings.FINETUNING_BACKEND = "modal"u, p, a = _setup()ds = _dataset_with_pairs(a, n=10)@@ -1366,20 +1191,19 @@ class TestGPUSelectorLogic:class TestModelRegistryAnyBackend:pytestmark = pytest.mark.django_db(transaction=False)- def test_together_model_is_found(self):+ def test_catalogued_model_is_found(self):from overbae.modal.model_registry import get_model_config_any_backendcfg = get_model_config_any_backend("Qwen/Qwen3-8B")assert cfg is not Noneassert cfg["id"] == "Qwen/Qwen3-8B"- def test_baseten_only_model_is_found(self):- """Qwen2.5-32B is baseten-only; must not return None."""+ def test_modal_model_is_found(self):from overbae.modal.model_registry import get_model_config_any_backendcfg = get_model_config_any_backend("Qwen/Qwen2.5-32B-Instruct")assert cfg is not None- assert cfg["backend"] == "baseten"+ assert cfg["backend"] == "modal"def test_arch_constants_present_on_result(self):from overbae.modal.model_registry import get_model_config_any_backend@@ -1402,10 +1226,10 @@ class TestModelRegistryAnyBackend:assert get_model_config_any_backend("totally-unknown/model-xyz") is None- def test_all_non_disabled_baseten_models_have_arch_constants(self):+ def test_all_non_disabled_modal_models_have_arch_constants(self):from overbae.modal.model_registry import get_all_models_by_backend- models = get_all_models_by_backend("baseten", include_disabled=False)+ models = get_all_models_by_backend("modal", include_disabled=False)assert modelsfor model_id, cfg in models.items():assert cfg.get("num_attn_layers") is not None, f"{model_id} missing num_attn_layers"@@ -1413,88 +1237,16 @@ class TestModelRegistryAnyBackend:assert cfg.get("head_dim") is not None, f"{model_id} missing head_dim"-class TestBasetenContextLengthPersistence:- """``submit()`` persists context_length so model_deployment can size the GPU.- The stubbed push response is Baseten's real push-API shape."""-+class TestTrainingPlan:pytestmark = pytest.mark.django_db- def _make_job(self, base_model: str = "Qwen/Qwen3-8B", max_token_length: int = 500):- _, p, a = _setup()- ds = _dataset_with_messages(a, n=5)- version = ds.active_cell- version.stats = {**version.stats, "max_token_length": max_token_length}- version.save(update_fields=["stats"])- return FinetuningJob.objects.create(- project=p,- dataset=ds,- cell=version,- base_model=base_model,- hyperparameters={"n_epochs": 2, "training_type": {"type": "Lora", "lora_r": 8}},- )-- @staticmethod- def _submit(job, tmp_path):- train = tmp_path / "train.jsonl"- train.write_text(- json.dumps(- {- "messages": [- {"role": "user", "content": "hi"},- {"role": "assistant", "content": "yo"},- ]- }- )- + "\n",- encoding="utf-8",- )- truss_train = MagicMock()- truss_train.push.return_value = {- "id": "bt-job-1",- "training_project": {"id": "bt-proj-1"},- }- runner = BasetenRunner()- # truss is a worker-only dep; stub auth rewrite + push at the boundary.- with (- patch.dict("sys.modules", {"truss_train": truss_train}),- patch.object(BasetenRunner, "_ensure_trussrc"),- ):- return runner.submit(job=job, training_file_path=str(train), num_examples=4)-- def test_submit_writes_context_length_to_db(self, tmp_path):- """11,051-token rows plus headroom snap up to the 16,384 bucket — well under- Qwen3-8B's catalog max of 40,960."""- job = self._make_job(max_token_length=11051)- assert "context_length" not in (job.hyperparameters or {})-- result = self._submit(job, tmp_path)- assert result.remote_id == "bt-proj-1:bt-job-1"-- job.refresh_from_db()- assert job.hyperparameters["context_length"] == 16384-- def test_submit_preserves_existing_hyperparameters(self, tmp_path):- job = self._make_job(max_token_length=500)- self._submit(job, tmp_path)-- job.refresh_from_db()- assert job.hyperparameters["n_epochs"] == 2- assert job.hyperparameters["context_length"] == 4096-def test_context_snap_helper_capped_by_model_max(self):from overbae.services.finetuning_policy import TrainingPlanError- from overbae.services.finetuning_runner import baseten_context_length+ from overbae.services.finetuning_runner import snap_context_length- assert baseten_context_length(11051, model_max=32768) == 16384+ assert snap_context_length(11051, model_max=32768) == 16384with pytest.raises(TrainingPlanError, match="refusing to clamp"):- baseten_context_length(999_999, model_max=32768)-- def test_training_gpu_scales_with_model_size(self):- runner = BasetenRunner()- small = SimpleNamespace(base_model="Qwen/Qwen3-8B")- big = SimpleNamespace(base_model="Qwen/Qwen2.5-72B-Instruct")- assert runner._select_training_gpu(small) == ("H100", 1)- assert runner._select_training_gpu(big) == ("H100", 1)+ snap_context_length(999_999, model_max=32768)def test_gemma4_full_never_gets_multi_gpu(self):from overbae.services.finetuning_runner import clamp_gemma4_training_gpu@@ -1569,8 +1321,7 @@ class TestDeploymentGPUDerivation:# At 16k context, 8B FP8 fits on L4assert gpu == "L4"- def test_baseten_only_model_selects_correctly(self):- """Qwen2.5-32B is baseten-only — get_model_config_any_backend must find it."""+ def test_qwen25_32b_selects_a_mid_range_gpu(self):gpu, conc = self._select("Qwen/Qwen2.5-32B-Instruct", 32768)# 32B dense model at 32k — mid-range GPU, not L4 or H200+.assert gpu in ("L40S", "A100-80GB")diff --git a/tests/test_finetuning_policy.py b/tests/test_finetuning_policy.pyindex b266512f..f3e5f487 100644--- a/tests/test_finetuning_policy.py+++ b/tests/test_finetuning_policy.py@@ -3,9 +3,9 @@ from __future__ import annotationsimport pytestfrom overbae.services.finetuning_policy import (- baseten_context_length,default_epochs,estimated_training_context_length,+ snap_context_length,)pytestmark = pytest.mark.covers("plans")@@ -32,4 +32,4 @@ def test_estimated_context_sizes_without_rejecting_unmeasured_data(estimate, reqdef test_context_above_largest_bucket_does_not_round_down():- assert baseten_context_length(model_max=1_000_000, requested=300_000) == 300_000+ assert snap_context_length(model_max=1_000_000, requested=300_000) == 300_000diff --git a/tests/test_inference_routing.py b/tests/test_inference_routing.pyindex 3a8904e5..1d4a156d 100644--- a/tests/test_inference_routing.py+++ b/tests/test_inference_routing.py@@ -320,12 +320,12 @@ def test_full_finetune_takes_the_merge_path():def test_non_modal_provider_takes_the_merge_path():- """Baseten and Nebius checkpoints come back through S3, not the sft Volume that+ """Nebius checkpoints come back through its own download, not the sft Volume thatpublish_adapter reads from."""from overbae.services.deployment import serves_as_adapterjob = FinetuningJob(- provider="baseten",+ provider="nebius",base_model="Qwen/Qwen3-1.7B",hyperparameters={"training_type": {"type": "Lora"}},)diff --git a/tests/test_llms.py b/tests/test_llms.pyindex 5c8ab34d..e5d830d1 100644--- a/tests/test_llms.py+++ b/tests/test_llms.py@@ -68,7 +68,7 @@ def test_call_llm_sends_the_response_schema(fake_llm):@pytest.fixturedef only_openrouter(monkeypatch):- for env in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY", "TOGETHER_API_KEY"):+ for env in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GEMINI_API_KEY"):monkeypatch.delenv(env, raising=False)monkeypatch.setenv("OPENROUTER_API_KEY", "or-key")@@ -95,11 +95,6 @@ def test_catalog_models_route_through_openrouter(fake_llm, only_openrouter, argu@pytest.mark.parametrize(("spec", "env", "url"),[- (- ModelSpec(provider="together", model_id="ft-model"),- "TOGETHER_API_KEY",- "https://api.together.xyz/v1/chat/completions",- ),(ModelSpec(provider="custom",@@ -111,7 +106,7 @@ def test_catalog_models_route_through_openrouter(fake_llm, only_openrouter, argu"https://models.example.test/v1/chat/completions",),],- ids=["together", "custom"],+ ids=["custom"],)def test_openai_compatible_specs_call_their_own_endpoint(fake_llm, monkeypatch, spec, env, url):monkeypatch.setenv(env, "provider-key")diff --git a/tests/test_mcp_model_catalog.py b/tests/test_mcp_model_catalog.pyindex e97f6164..8fd70851 100644--- a/tests/test_mcp_model_catalog.py+++ b/tests/test_mcp_model_catalog.py@@ -7,7 +7,6 @@ from django.test import override_settingsfrom mcp_fixtures import call_toolfrom overbae.models import APIToken, Project, User-from overbae.services.finetuning_catalog import fetch_finetuning_model_catalogfrom overbae.services.mcp.catalog import CATALOGfrom overbae.services.mcp.context import MCPContextfrom overbae.services.mcp.contracts.model_catalog import GetModelCatalogOutput@@ -45,10 +44,8 @@ def test_catalog_metadata_and_input_schema_are_read_only_and_bounded():assert definition.async_mode == "sync"schema = definition.as_mcp_tool().inputSchema- assert set(schema["properties"]) == {"has_tool_calling", "max_context"}+ assert set(schema["properties"]) == {"has_tool_calling"}assert schema["additionalProperties"] is False- assert schema["properties"]["max_context"]["maximum"] == 10_000_000- assert schema["properties"]["max_context"]["exclusiveMinimum"] == 0assert {tool.name for tool in CATALOG.tools(frozenset({"write"}))}.isdisjoint({"get_model_catalog"})@@ -66,7 +63,6 @@ def test_catalog_is_dataset_independent_and_returns_complete_model_metadata():"tiers","models","has_tool_calling",- "max_context","monitoring",}assert output["backend"] == "modal"@@ -79,7 +75,6 @@ def test_catalog_is_dataset_independent_and_returns_complete_model_metadata():]assert output["monitoring"]["runtime_qualification"] != "gpu_qualified"assert output["has_tool_calling"] is False- assert output["max_context"] is Noneassert output["summary"] == (f"{sum(len(models) for models in output['models'].values())} ""fine-tuning catalog entries returned for modal."@@ -120,8 +115,8 @@ def test_catalog_is_dataset_independent_and_returns_complete_model_metadata():assert training_schema["additionalProperties"] is False-def test_catalog_filters_tool_calling_and_preserves_together_context_semantics():- with override_settings(FINETUNING_BACKEND="baseten"):+def test_catalog_filters_tool_calling():+ with override_settings(FINETUNING_BACKEND="modal"):tool_result = _call({"has_tool_calling": True})assert tool_result.isError is Falsetool_models = [@@ -132,27 +127,12 @@ def test_catalog_filters_tool_calling_and_preserves_together_context_semantics()model["supports_tool_calling"] and not model.get("disabled") for model in tool_models)- with override_settings(FINETUNING_BACKEND="together"):- result = _call({"max_context": 50_000})- expected = fetch_finetuning_model_catalog(max_context=50_000)-- assert result.isError is False- assert result.structuredContent["models"] == expected["models"]- assert result.structuredContent["max_context"] == 50_000- assert all(- "context_length" not in model- for tier in result.structuredContent["models"].values()- for model in tier- )-@pytest.mark.parametrize("arguments",[{"has_tool_calling": "true"},{"has_tool_calling": 1},- {"max_context": "50000"},- {"max_context": 50000.0},],)def test_catalog_rejects_coercible_input_types(arguments):diff --git a/tests/test_mcp_prompts.py b/tests/test_mcp_prompts.pyindex b4e6b0f1..33e3dee2 100644--- a/tests/test_mcp_prompts.py+++ b/tests/test_mcp_prompts.py@@ -201,7 +201,7 @@ def test_checkpoint_prompt_uses_mcp_deployment_id_and_local_cli_boundary():)assert "deployment id supplied by MCP" in textassert "presigned URL" in text- assert "baseten or modal" in text+ assert "archived checkpoints" in textassert "local `path`" in textassert "`bytes_written`" in textassert "refuses to overwrite" in textdiff --git a/tests/test_mcp_resources.py b/tests/test_mcp_resources.pyindex 97a8697b..fe71e1ac 100644--- a/tests/test_mcp_resources.py+++ b/tests/test_mcp_resources.py@@ -243,7 +243,6 @@ def test_checkpoint_download_resource_describes_cli_boundary_and_availability():assert "--api-url" in resource["config"]assert "presigned S3" in resource["mcp_boundary"]assert "model context" in resource["mcp_boundary"]- assert "baseten or modal" in resource["availability"]assert "archived checkpoints" in resource["availability"]assert "path" in resource["output"]assert "bytes_written" in resource["output"]diff --git a/tests/test_modal_volume_retention.py b/tests/test_modal_volume_retention.pyindex eb1c0d2a..80738781 100644--- a/tests/test_modal_volume_retention.py+++ b/tests/test_modal_volume_retention.py@@ -178,8 +178,8 @@ def test_unknown_run_dir_is_reported_not_deleted():def test_non_modal_jobs_do_not_match_a_run_dir():- """Baseten run ids share the volume's namespace only by coincidence."""- run_id = _job(status=FinetuningJob.Status.FAILED, age_days=30, provider="baseten")+ """Other providers' run ids share the volume's namespace only by coincidence."""+ run_id = _job(status=FinetuningJob.Status.FAILED, age_days=30, provider="nebius")plan = _plan([run_id])diff --git a/tests/test_model_deployment_resume.py b/tests/test_model_deployment_resume.pyindex 682fee4b..89536507 100644--- a/tests/test_model_deployment_resume.py+++ b/tests/test_model_deployment_resume.py@@ -375,7 +375,7 @@ def test_notification_is_retried_after_worker_failure(deployed):def test_merged_weights_and_baseline_preserve_actual_quantization(deployed, fake_modal):- FinetuningJob.objects.filter(pk=deployed.finetuning_job_id).update(provider="baseten")+ FinetuningJob.objects.filter(pk=deployed.finetuning_job_id).update(provider="nebius")at_stage(deployed,fake_modal,diff --git a/tests/test_model_library.py b/tests/test_model_library.pyindex 7fa06da9..4412ae45 100644--- a/tests/test_model_library.py+++ b/tests/test_model_library.py@@ -2,7 +2,6 @@import pytest-from overbae.modal.model_registry import all_model_entriesfrom overbae.services.model_library import _provider_from_id, public_model_catalogpytestmark = pytest.mark.covers("model-runtime")@@ -22,13 +21,7 @@ def test_non_catalog_unsloth_ids_keep_org_fallback():assert _provider_from_id("unsloth/gpt-oss-20b-BF16") == "Unsloth"-def test_public_catalog_leaves_out_together_only_models():- # Training runs on Modal from the Baseten catalog, so these can be neither trained nor served.- entries = all_model_entries()- together_only = {c["id"] for c in entries if c.get("backend") == "together"} - {- c["id"] for c in entries if c.get("backend") != "together"- }+def test_public_catalog_lists_each_open_weight_model_once():listed = [m["id"] for m in public_model_catalog() if m["category"] == "open-weight"]- assert together_only- assert not together_only & set(listed)+ assert listedassert len(listed) == len(set(listed))diff --git a/tests/test_modelfam.py b/tests/test_modelfam.pyindex b78ba964..c591d942 100644--- a/tests/test_modelfam.py+++ b/tests/test_modelfam.py@@ -193,8 +193,6 @@ def test_finetune_hf_base_uses_unsloth_catalog_row() -> None:with override_settings(FINETUNING_BACKEND="modal"):assert get_hf_base("Qwen/Qwen3-8B") == "unsloth/Qwen3-8B"- with override_settings(FINETUNING_BACKEND="together"):- assert get_hf_base("Qwen/Qwen3-8B") == "Qwen/Qwen3-8B"def test_trust_and_llama31() -> None:@@ -495,10 +493,10 @@ def test_full_ft_disabled_above_30b() -> None:assert not hits, f"full FT must be off above 30B: {hits}"-def test_baseten_real_max_context_length() -> None:+def test_modal_real_max_context_length() -> None:data = json.loads(_MODELS_JSON.read_text())for entry in data["models"]:- if entry.get("backend") != "baseten":+ if entry.get("backend") != "modal":continueft = entry["finetuning"]real = ft.get("real_max_context_length")diff --git a/tests/test_recommendation_constraints.py b/tests/test_recommendation_constraints.pyindex 6f66a3c8..2921e8de 100644--- a/tests/test_recommendation_constraints.py+++ b/tests/test_recommendation_constraints.py@@ -140,7 +140,7 @@ def test_a_tier_that_loses_every_model_is_omitted_rather_than_empty(catalog):def test_the_real_catalog_rejects_each_model_at_most_once():- with override_settings(FINETUNING_BACKEND="baseten"):+ with override_settings(FINETUNING_BACKEND="modal"):eligible, exclusions = eligible_models(has_tool_calling=True, max_row_tokens=50_000)rejected = [exclusion.model for exclusion in exclusions]diff --git a/tests/test_recommendation_engine.py b/tests/test_recommendation_engine.pyindex 4924c256..3d116244 100644--- a/tests/test_recommendation_engine.py+++ b/tests/test_recommendation_engine.py@@ -48,7 +48,7 @@ def dataset(db) -> Dataset:def _recommend(dataset: Dataset) -> dict[str, Any]:- with override_settings(FINETUNING_BACKEND="baseten"):+ with override_settings(FINETUNING_BACKEND="modal"):return get_recommendation(str(dataset.id))@@ -60,7 +60,7 @@ def _set_stats(dataset: Dataset, **overrides: Any) -> None:def test_every_constraint_passing_model_is_returned_in_rank_order(dataset):analysis = _recommend(dataset)- with override_settings(FINETUNING_BACKEND="baseten"):+ with override_settings(FINETUNING_BACKEND="modal"):eligible, _exclusions = eligible_models(has_tool_calling=False, max_row_tokens=_STATS["max_token_length"])diff --git a/tests/test_register_artifact_layout.py b/tests/test_register_artifact_layout.pyindex 191fa1fa..6d765c39 100644--- a/tests/test_register_artifact_layout.py+++ b/tests/test_register_artifact_layout.py@@ -1,4 +1,4 @@-"""File layouts below are VERBATIM from two real Baseten jobs: qjx77gw (final+"""File layouts below are VERBATIM from two real fine-tune archives: qjx77gw (finaladapter at the root plus nested checkpoint-N/ dirs) and qzprr8w (ONLY nestedcheckpoint-N/ dirs — the root adapter save never synced to checkpoint storage)."""diff --git a/tests/test_training_monitoring.py b/tests/test_training_monitoring.pyindex a5359281..fb72166e 100644--- a/tests/test_training_monitoring.py+++ b/tests/test_training_monitoring.py@@ -41,7 +41,7 @@ def test_monitoring_requires_real_provider_and_development_support():with pytest.raises(ValueError, match="development"):resolve_policy({"mode": "adaptive"}, has_development=False, provider="modal")with pytest.raises(ValueError, match="provider"):- resolve_policy({"mode": "adaptive"}, has_development=True, provider="together_ai")+ resolve_policy({"mode": "adaptive"}, has_development=True, provider="nebius")assert resolve_policy(None, has_development=False, provider="modal")["mode"] == "off"diff --git a/tests/test_finetuning_baseten_plan.py b/tests/test_training_plan.pysimilarity index 98%rename from tests/test_finetuning_baseten_plan.pyrename to tests/test_training_plan.pyindex 55a9e4e7..2038c208 100644--- a/tests/test_finetuning_baseten_plan.py+++ b/tests/test_training_plan.py@@ -8,7 +8,7 @@ from overbae.api.serializers import FinetuningJobSerializerfrom overbae.services.finetuning_policy import (TrainingPlanError,default_epochs,- derive_baseten_training_plan,+ derive_training_plan,qlora_learning_rate,should_pack,)@@ -31,12 +31,12 @@ def _plan(**overrides):gpu_count=1,)kwargs.update(overrides)- return derive_baseten_training_plan(**kwargs)+ return derive_training_plan(**kwargs)def test_modal_plan_uses_its_catalog_bounds_for_shared_model_id():config = ModalRunner.model_config("Qwen/Qwen3.5-2B")- assert config["backend"] == "baseten"+ assert config["backend"] == "modal"plan = _plan(hyperparameters={"batch_size": 1},model_min_batch=config["finetuning"]["min_batch_size"],@@ -149,7 +149,7 @@ class TestExplicitValuesWin:)assert accepted["training_type"]["lora_r"] == 32- @override_settings(FINETUNING_BACKEND="baseten")+ @override_settings(FINETUNING_BACKEND="modal")def test_recommender_output_is_reproduced_exactly(self):entry = {"total_params_b": 8.0,diff --git a/tests/test_training_preparation.py b/tests/test_training_preparation.pyindex fc7fa1c9..acc48dd1 100644--- a/tests/test_training_preparation.py+++ b/tests/test_training_preparation.py@@ -630,7 +630,7 @@ def test_preparation_retry_skips_submitted_training_or_other_backends(retry_job,job, _, _, _ = retry_jobjob.remote_job_id = remoteif not remote:- settings.FINETUNING_BACKEND = "together"+ settings.FINETUNING_BACKEND = "other"with patch.object(preparation, "for_job") as request:preparation.retry_for_job(job)request.assert_not_called()diff --git a/tests/test_training_submission.py b/tests/test_training_submission.pyindex 67b3c8d4..9cfab750 100644--- a/tests/test_training_submission.py+++ b/tests/test_training_submission.py@@ -130,10 +130,10 @@ def test_preparation_steps_update_counts_without_duplicating_activity():],)def test_explicit_recipe_cannot_be_silently_changed(requested, field):- from overbae.services.finetuning_policy import TrainingPlanError, derive_baseten_training_plan+ from overbae.services.finetuning_policy import TrainingPlanError, derive_training_planwith pytest.raises(TrainingPlanError, match=field):- derive_baseten_training_plan(+ derive_training_plan(hyperparameters=requested,num_train_examples=100,dataset_stats={},@@ -144,9 +144,9 @@ def test_explicit_recipe_cannot_be_silently_changed(requested, field):def test_explicit_zero_warmup_and_disabled_packing_are_preserved():- from overbae.services.finetuning_policy import derive_baseten_training_plan+ from overbae.services.finetuning_policy import derive_training_plan- plan = derive_baseten_training_plan(+ plan = derive_training_plan(hyperparameters={"warmup_ratio": 0, "packing": False},num_train_examples=5000,dataset_stats={"avg_input_chars": 4},diff --git a/uv.lock b/uv.lockindex cfddbb21..148018cc 100644--- a/uv.lock+++ b/uv.lock@@ -316,7 +316,6 @@ dependencies = [{ name = "stripe" },{ name = "tenacity" },{ name = "tiktoken" },- { name = "together" },{ name = "unidecode" },{ name = "uvicorn", extra = ["standard"] },{ name = "uvicorn-worker" },@@ -416,7 +415,6 @@ requires-dist = [{ name = "stripe", specifier = ">=15.3.1" },{ name = "tenacity", specifier = ">=9.0.0" },{ name = "tiktoken", specifier = ">=0.14.0" },- { name = "together", specifier = ">=1.3.0" },{ name = "unidecode", specifier = ">=1.4.0" },{ name = "uvicorn", extras = ["standard"], specifier = ">=0.42.0" },{ name = "uvicorn-worker", specifier = ">=0.4.0" },@@ -952,21 +950,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" },]-[[package]]-name = "cyclopts"-version = "4.20.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "attrs" },- { name = "docstring-parser" },- { name = "rich" },- { name = "rich-rst" },-]-sdist = { url = "https://files.pythonhosted.org/packages/74/89/f4c775c651d91f9cd8149f70baec94c902a34e5f17a7a67881881bcfb244/cyclopts-4.20.0.tar.gz", hash = "sha256:1d819de2b12dc6b1c9f17ce0f4937d82922c0b83ac846eb4b3289c9c9f321c9f", size = 190236, upload-time = "2026-06-29T15:04:42.253Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/dd/d4/7243bc65d33c5ff5150569c42c8c1154aadae20b25638afe35f7f568489c/cyclopts-4.20.0-py3-none-any.whl", hash = "sha256:0b4337e9c11303d86b33d3f37c629dc01638f84591681e0e5611286bdd507646", size = 229383, upload-time = "2026-06-29T15:04:40.621Z" },-]-[[package]]name = "datasketch"version = "2.0.0"@@ -1129,15 +1112,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/84/d0/205d54408c08b13550c733c4b85429e7ead111c7f0014309637425520a9a/deprecated-1.3.1-py2.py3-none-any.whl", hash = "sha256:597bfef186b6f60181535a29fbe44865ce137a5079f295b479886c82729d5f3f", size = 11298, upload-time = "2025-10-30T08:19:00.758Z" },]-[[package]]-name = "detect-agent"-version = "0.3.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/6b/40/90675e9934cac99acb4d5df050dbed9418587775ed916f12844c71e6a53f/detect_agent-0.3.0.tar.gz", hash = "sha256:186e8a80638985574417ba752e74ca1b80341280dc6d4308b0a25b4e7bac50f3", size = 41995, upload-time = "2026-05-29T19:24:18.143Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/16/67/746fe6402fbe769431d09965f7808c586dcbb0764b4694d62785a88d8736/detect_agent-0.3.0-py3-none-any.whl", hash = "sha256:14c0ab0b90fca111eafea51d22f24fb187591e2a16eda8cbbe856a204ffdd7aa", size = 7815, upload-time = "2026-05-29T19:24:18.9Z" },-]-[[package]]name = "distlib"version = "0.4.3"@@ -1379,15 +1353,6 @@ format-pdf-docling = [{ name = "docling-parse" },]-[[package]]-name = "docstring-parser"-version = "0.18.0"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/e0/4d/f332313098c1de1b2d2ff91cf2674415cc7cddab2ca1b01ae29774bd5fdf/docstring_parser-0.18.0.tar.gz", hash = "sha256:292510982205c12b1248696f44959db3cdd1740237a968ea1e2e7a900eeb2015", size = 29341, upload-time = "2026-04-14T04:09:19.867Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/a7/5f/ed01f9a3cdffbd5a008556fc7b2a08ddb1cc6ace7effa7340604b1d16699/docstring_parser-0.18.0-py3-none-any.whl", hash = "sha256:b3fcbed555c47d8479be0796ef7e19c2670d428d72e96da63f3a40122860374b", size = 22484, upload-time = "2026-04-14T04:09:18.638Z" },-]-[[package]]name = "drf-spectacular"version = "0.29.0"@@ -4353,19 +4318,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" },]-[[package]]-name = "rich-rst"-version = "2.0.2"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "pygments" },- { name = "rich" },-]-sdist = { url = "https://files.pythonhosted.org/packages/0b/40/905f612e7bf105d7efefa923542e0c85b731cf29bcc1864331427dbc52b8/rich_rst-2.0.2.tar.gz", hash = "sha256:664a669801695c5a126151338f309ce3ea3e0ea081c89a4130b8a4f659911ed9", size = 300822, upload-time = "2026-06-25T17:24:14.298Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/cf/5f/62fdf0f574ec75af7ada8ad27c1a67e3723d491143bc88d5371c25673949/rich_rst-2.0.2-py3-none-any.whl", hash = "sha256:7bc2923929c9bbc61aadfef2069b742446823b306af84cf9e0f56b965a3d3035", size = 273082, upload-time = "2026-06-25T17:24:09.557Z" },-]-[[package]]name = "rpds-py"version = "2026.5.1"@@ -4829,33 +4781,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/cc/35/86e1f95600a353361ae138268aa53cc2d17e6404801827d4ec09dc59b1af/time_machine-3.5.1-cp315-cp315t-win_arm64.whl", hash = "sha256:1990c1a3234d1df441ce084618b68d3c4a083f17dea4fd47adcf68d6668b507b", size = 29399, upload-time = "2026-09-08T22:19:48.68Z" },]-[[package]]-name = "together"-version = "2.21.0"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "anyio" },- { name = "cyclopts" },- { name = "detect-agent" },- { name = "distro" },- { name = "filelock" },- { name = "httpx" },- { name = "pillow" },- { name = "pydantic" },- { name = "rich" },- { name = "sniffio" },- { name = "tabulate" },- { name = "tqdm" },- { name = "types-pyyaml" },- { name = "types-tabulate" },- { name = "types-tqdm" },- { name = "typing-extensions" },-]-sdist = { url = "https://files.pythonhosted.org/packages/1d/1d/3639c6c36ac5dd8d9e172aabc244bf3c27a3060b6220801aa12e04692712/together-2.21.0.tar.gz", hash = "sha256:dff5e01b9b51b1f70f8385e28a61a9360631d56f31547a86300bacb959775cc8", size = 617197, upload-time = "2026-06-29T15:26:04.14Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/d9/13/82912d557fba9b1e8f32ba515b40676ef9c84c89f9dc3e0645a1b5ca4102/together-2.21.0-py3-none-any.whl", hash = "sha256:f2bb06a6b1ba0dbbd25b42dd0bc7e209f1b4060c7cc37704c2966927c16ba916", size = 419444, upload-time = "2026-06-29T15:26:02.749Z" },-]-[[package]]name = "toml"version = "0.10.2"@@ -4974,36 +4899,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/b5/63/2463d89481e811f007b0e1cd0a91e52e141b47f9de724d20db7b861dcfec/types_certifi-2021.10.8.3-py3-none-any.whl", hash = "sha256:b2d1e325e69f71f7c78e5943d410e650b4707bb0ef32e4ddf3da37f54176e88a", size = 2136, upload-time = "2022-06-09T15:19:03.127Z" },]-[[package]]-name = "types-pyyaml"-version = "6.0.12.20260518"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/b8/83/4a1afc3fbfcf5b8d46fc390cd95ed6b0dc9010a265f4e9f46314efffa37a/types_pyyaml-6.0.12.20260518.tar.gz", hash = "sha256:d917f83fb38462550338c1297faedd860b3ec83912b96b1e3d73255f7473e466", size = 17850, upload-time = "2026-05-18T06:01:58.675Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/06/a2/c01db32be2ae7d6a1689972f3c492b149ee4e164b12fdfd9f64b50888215/types_pyyaml-6.0.12.20260518-py3-none-any.whl", hash = "sha256:d2150f75a231c9fe9c7463bd29487d93e60bac90400287351384bc2284eba7cd", size = 20312, upload-time = "2026-05-18T06:01:57.368Z" },-]--[[package]]-name = "types-requests"-version = "2.33.0.20260518"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "urllib3" },-]-sdist = { url = "https://files.pythonhosted.org/packages/e0/01/c5a19253fe1ac159159ddf9a3a07cec8bb5e486ec4d9002ad2821da0e5d2/types_requests-2.33.0.20260518.tar.gz", hash = "sha256:df7bd3bfe0ca8402dfb841e7d9be714bb5578203283d66d7dc4ef69343449a5e", size = 24752, upload-time = "2026-05-18T06:07:37.966Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/1c/bc/b139710a3b6018f7fb2b9508b35c8af564e61bf2bf4fa619d088f3e16f85/types_requests-2.33.0.20260518-py3-none-any.whl", hash = "sha256:626d697d1adaaff76e2044dc8c5c051d8f21abc157bdfe204a75558076fe0bf0", size = 21391, upload-time = "2026-05-18T06:07:37.044Z" },-]--[[package]]-name = "types-tabulate"-version = "0.10.0.20260508"-source = { registry = "https://pypi.org/simple" }-sdist = { url = "https://files.pythonhosted.org/packages/11/af/c100d86897d3fdb010d8f813569fa80355b5cb553f51080e37d4f3c451bb/types_tabulate-0.10.0.20260508.tar.gz", hash = "sha256:8e51f159e8b24976849706ae2ed1dc9adba8ebbd080b17e494ebb66a8cc92c74", size = 8395, upload-time = "2026-05-08T04:47:58.921Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/a0/36/443b700f54a585cf8ed4e76d8ad08b12df6914f8782a2788ecd0d8491519/types_tabulate-0.10.0.20260508-py3-none-any.whl", hash = "sha256:b1e1a2d0456fbd655a71690b09a7aaeffdf2978d32049184ea436492aa51d20a", size = 8137, upload-time = "2026-05-08T04:47:57.872Z" },-]-[[package]]name = "types-toml"version = "0.10.8.20260518"@@ -5013,18 +4908,6 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/91/25/489751806bf5c95e4007f8e17409199c54d31e49ffbea07c5729b1286c8e/types_toml-0.10.8.20260518-py3-none-any.whl", hash = "sha256:0e564ab05f6fde62a315b3b5a9b6624fda569399795d30a37e64705a70459303", size = 9669, upload-time = "2026-05-18T06:02:15.86Z" },]-[[package]]-name = "types-tqdm"-version = "4.68.0.20260608"-source = { registry = "https://pypi.org/simple" }-dependencies = [- { name = "types-requests" },-]-sdist = { url = "https://files.pythonhosted.org/packages/dc/e0/3facccb1ff69970c73fca7a8028286c233d4c1312c475a65fb3d896f56d9/types_tqdm-4.68.0.20260608.tar.gz", hash = "sha256:e1dfddf8770fbc30ecaf95ae57c286397831235064308f7dfc2b1d6684a76107", size = 18470, upload-time = "2026-06-08T06:26:06.661Z" }-wheels = [- { url = "https://files.pythonhosted.org/packages/53/e8/61d95bfd49d1609fb8e8c5e06f4a094183411988a6f448873f5de6602499/types_tqdm-4.68.0.20260608-py3-none-any.whl", hash = "sha256:450a6e7e9e9b604928968927c414b32970e40091213c4180e1ed470905b13eff", size = 24858, upload-time = "2026-06-08T06:26:05.741Z" },-]-[[package]]name = "typing-extensions"version = "4.16.0"