import {z} from 'zod' export type HFCheckpointParametersRequestInput = {type?: (string | 'hf') | undefined, repo: string, revision?: (string | null) | undefined, token?: (string | null) | undefined}; export type FTCheckpointParameters = {type?: (string | 'ft') | undefined}; export type SupervisedHParameters = {batch_size?: number | undefined, learning_rate?: number | undefined, n_epochs?: number | undefined, warmup_ratio?: number | undefined, weight_decay?: number | undefined, packing?: boolean | undefined, max_grad_norm?: number | undefined, context_length?: number | undefined, lora?: boolean | undefined, lora_r?: number | undefined, lora_alpha?: number | undefined, lora_dropout?: number | undefined} | {[key: string]: unknown}; export type SupervisedConfig = {hyperparameters: SupervisedHParameters}; export type SupervisedMethodConfig = {type?: 'supervised' | undefined, supervised: SupervisedConfig}; export type SpecDraftLossParams = {type?: ('kl' | 'lk_alpha' | 'lk_hybrid') | undefined}; export type SpecDraftHParameters = {batch_size?: number | undefined, learning_rate?: number | undefined, n_epochs?: number | undefined, warmup_ratio?: number | undefined, weight_decay?: number | undefined, packing?: boolean | undefined, max_grad_norm?: number | undefined, context_length?: number | undefined, architecture?: string | undefined, num_decoding_heads?: number | undefined, loss?: SpecDraftLossParams | undefined} | {[key: string]: unknown}; export type SpecDraftConfig = {hyperparameters: SpecDraftHParameters}; export type SpecDraftMethodConfig = {type?: 'spec-draft' | undefined, spec_draft: SpecDraftConfig}; export type WandbConfigRequest = {project: string, name?: (string | null) | undefined, entity?: (string | null) | undefined, tags?: Array | undefined, api_key: string}; export type WandbIntegrationRequest = {type?: (string | 'wandb') | undefined, wandb: WandbConfigRequest}; export type MlflowConfigRequest = {tracking_uri: string, experiment_name: string | null, run_name: string | null, tags?: {[key: string]: string} | undefined, certificate_file: string, certificate_file_id?: (string | null) | undefined, username: string, password: string}; export type MlflowIntegrationRequest = {type?: 'mlflow' | undefined, mlflow: MlflowConfigRequest}; export type HfExportConfigRequest = {output_repo_name: string, api_token: string}; export type HfExportIntegrationRequest = {type?: (string | 'hf') | undefined, hf: HfExportConfigRequest}; export type FineTuningRequest = {model: string, from_checkpoint?: (HFCheckpointParametersRequestInput | FTCheckpointParameters | null) | undefined, training_file: string, validation_file?: (string | null) | undefined, hyperparameters?: (SupervisedHParameters | null) | undefined, method?: (SupervisedMethodConfig | SpecDraftMethodConfig | null) | undefined, integrations?: (Array | null) | undefined, seed?: (number | null) | undefined, suffix?: (string | null) | undefined, tags?: (Array | null) | undefined, extra_body?: ({[key: string]: unknown} | null) | undefined} | {[key: string]: unknown}; export type CreateApiV1FineTuningJobsArgs = {ai_project_id?: (string | null) | undefined, body: FineTuningRequest}; export type CreateApiV1FineTuningJobsOptions = {baseUrl?: string | undefined, HTTPBearer?: string | undefined, fetch?: typeof fetch | undefined}; export const error = z.object({error: z.union([z.string(), z.object({}), z.array(z.object({}))]), status: z.number().int().optional(), traceback: z.array(z.string()).optional()}); export const supervisedHParameters = z.object({batch_size: z.number().int().gte(1).lte(64).optional(), learning_rate: z.number().gte(0).optional(), n_epochs: z.number().int().gte(1).lte(20).optional(), warmup_ratio: z.number().gte(0).lte(1).optional(), weight_decay: z.number().gte(0).optional(), packing: z.boolean().optional(), max_grad_norm: z.number().gt(0).optional(), context_length: z.number().int().gte(8192).lte(131072).optional(), lora: z.boolean().optional(), lora_r: z.number().int().gte(8).lte(128).optional(), lora_alpha: z.number().int().gte(8).optional(), lora_dropout: z.number().gte(0).lte(1).optional()}).and(z.record(z.string(), z.unknown())); export const supervisedConfig = z.object({hyperparameters: supervisedHParameters}); export const supervisedMethodConfig = z.object({type: z.literal("supervised").optional(), supervised: supervisedConfig}); export const specDraftLossParams = z.object({type: z.enum(["kl", "lk_alpha", "lk_hybrid"]).optional()}); export const specDraftHParameters = z.object({batch_size: z.number().int().gte(1).lte(64).optional(), learning_rate: z.number().gt(0).lt(1).optional(), n_epochs: z.number().int().gte(1).lte(20).optional(), warmup_ratio: z.number().gte(0).lte(1).optional(), weight_decay: z.number().gte(0).optional(), packing: z.boolean().optional(), max_grad_norm: z.number().gt(0).optional(), context_length: z.number().int().gte(8192).lte(131072).optional(), architecture: z.string().optional(), num_decoding_heads: z.number().int().gte(1).lte(10).optional(), loss: specDraftLossParams.optional()}).and(z.record(z.string(), z.unknown())); export const specDraftConfig = z.object({hyperparameters: specDraftHParameters}); export const specDraftMethodConfig = z.object({type: z.literal("spec-draft").optional(), spec_draft: specDraftConfig}); export const wandbConfigResponse = z.object({project: z.string(), name: z.string().nullable().optional(), entity: z.string().nullable().optional(), tags: z.array(z.string()).optional()}); export const wandbIntegrationResponse = z.object({type: z.union([z.string(), z.literal("wandb")]).optional(), wandb: wandbConfigResponse}); export const mlflowConfigResponse = z.object({tracking_uri: z.string(), experiment_name: z.string().nullable(), run_name: z.string().nullable(), tags: z.record(z.string(), z.string()).optional()}); export const mlflowIntegrationResponse = z.object({type: z.literal("mlflow").optional(), mlflow: mlflowConfigResponse}); export const hfExportConfigResponse = z.object({output_repo_name: z.string()}); export const hfExportIntegrationResponse = z.object({type: z.union([z.string(), z.literal("hf")]).optional(), hf: hfExportConfigResponse}); export const hFCheckpointParametersResponse = z.object({type: z.union([z.string(), z.literal("hf")]).optional(), repo: z.string(), revision: z.string().nullable().optional()}); export const fTCheckpointParameters = z.object({type: z.union([z.string(), z.literal("ft")]).optional()}); export const fineTuningJob = z.object({id: z.string(), created_at: z.number().int(), error: error.nullable().optional(), finished_at: z.number().int().nullable().optional(), hyperparameters: supervisedHParameters.nullable().optional(), method: z.union([supervisedMethodConfig, specDraftMethodConfig]).nullable().optional(), integrations: z.array(z.union([wandbIntegrationResponse, mlflowIntegrationResponse, hfExportIntegrationResponse])).nullable().optional(), from_checkpoint: z.union([hFCheckpointParametersResponse, fTCheckpointParameters]).nullable().optional(), model: z.string(), object: z.literal("fine_tuning.job").optional(), organization_id: z.string().optional(), result_files: z.array(z.string()).optional(), seed: z.number().int().optional(), suffix: z.string().max(64).nullable().optional(), status: z.enum(["validating_files", "queued", "running", "succeeded", "failed", "cancelled"]), trained_tokens: z.number().int().nullable().optional(), training_file: z.string(), validation_file: z.string().nullable().optional(), estimated_finish: z.number().int().nullable().optional(), trained_steps: z.number().int().nullable().optional(), total_steps: z.number().int().nullable().optional()}).and(z.record(z.string(), z.unknown())); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Create a fine-tuning job * * POST /v1/fine_tuning/jobs */ export const createApiV1FineTuningJobs = async (args: CreateApiV1FineTuningJobsArgs, options?: CreateApiV1FineTuningJobsOptions) => { const {baseUrl = "https://api.tokenfactory.nebius.com", fetch: fetchFn = fetch, HTTPBearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.ai_project_id != null) query.append("ai_project_id", String(args.ai_project_id)) if (HTTPBearer !== undefined) headers.set('authorization', `Bearer ${HTTPBearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/fine_tuning/jobs${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(fineTuningJob, await res.json()) };