import {z} from 'zod' export type RLEncodedTextChunk = {tokens: Array}; export type RLModelInputChunk = {encoded_text: RLEncodedTextChunk}; export type RLModelInput = {chunks: Array}; export type RLTensorData = {data: Array, dtype: 'int64' | 'float32', shape?: Array | undefined, sparse_crow_indices?: Array | undefined, sparse_col_indices?: Array | undefined}; export type RLTrainingSample = {model_input: RLModelInput, loss_fn_inputs: {[key: string]: RLTensorData}, routed_experts_key?: string | undefined}; export type RLLossType = 'LOSS_TYPE_UNSPECIFIED' | 'LOSS_TYPE_CROSS_ENTROPY' | 'LOSS_TYPE_GRPO' | 'LOSS_TYPE_IMPORTANCE_SAMPLING' | 'LOSS_TYPE_PPO' | 'LOSS_TYPE_CISPO' | 'LOSS_TYPE_DRO' | 'LOSS_TYPE_DPPO'; export type RLCrossEntropyLossParams = Record; export type RLGRPOLossAggregationType = 'GRPO_LOSS_AGGREGATION_TYPE_UNSPECIFIED' | 'GRPO_LOSS_AGGREGATION_TYPE_FIXED_HORIZON' | 'GRPO_LOSS_AGGREGATION_TYPE_TOKEN_MEAN' | 'GRPO_LOSS_AGGREGATION_TYPE_SEQUENCE_MEAN'; export type RLGRPOLossRatioType = 'GRPO_LOSS_RATIO_TYPE_TOKEN' | 'GRPO_LOSS_RATIO_TYPE_SEQUENCE'; export type RLGRPOLossParams = {clip_low_threshold?: number | undefined, clip_high_threshold?: number | undefined, beta?: number | undefined, agg_type?: RLGRPOLossAggregationType | undefined, ratio_type?: RLGRPOLossRatioType | undefined}; export type RLPPOLossParams = {clip_low_threshold?: number | undefined, clip_high_threshold?: number | undefined}; export type RLCISPOLossParams = {clip_low_threshold?: number | undefined, clip_high_threshold?: number | undefined}; export type RLDROLossParams = {beta: number}; export type RLDPPOLossParams = {delta_low?: number | undefined, delta_high?: number | undefined}; export type RLLossConfig = {type: RLLossType, cross_entropy_params?: RLCrossEntropyLossParams | undefined, grpo_params?: RLGRPOLossParams | undefined, ppo_params?: RLPPOLossParams | undefined, cispo_params?: RLCISPOLossParams | undefined, dro_params?: RLDROLossParams | undefined, dppo_params?: RLDPPOLossParams | undefined}; export type RLForwardBackwardBody = {samples: Array, loss: RLLossConfig, return_loss_fn_outputs?: boolean | undefined, forward_only?: boolean | undefined}; export type CreateApiV1RlTrainingSessionsSessionIdOperationsForwardBackwardArgs = {session_id: string, 'Idempotency-Key': string, body: RLForwardBackwardBody}; export type CreateApiV1RlTrainingSessionsSessionIdOperationsForwardBackwardOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const rLTrainingOperationStatus = z.enum(["TRAINING_OPERATION_STATUS_UNSPECIFIED", "TRAINING_OPERATION_STATUS_PENDING", "TRAINING_OPERATION_STATUS_RUNNING", "TRAINING_OPERATION_STATUS_COMPLETED", "TRAINING_OPERATION_STATUS_FAILED"]); export const rLTensorData = z.object({data: z.array(z.number()), dtype: z.enum(["int64", "float32"]), shape: z.array(z.number().int()).optional(), sparse_crow_indices: z.array(z.number().int()).optional(), sparse_col_indices: z.array(z.number().int()).optional()}); export const rLLossFnOutput = z.object({tensors: z.record(z.string(), rLTensorData)}); export const rLForwardBackwardResult = z.object({loss: z.number(), metrics: z.record(z.string(), z.number()).optional(), loss_fn_outputs: z.array(rLLossFnOutput).optional()}); export const rLTrainingOperationErrorCode = z.enum(["TRAINING_OPERATION_ERROR_CODE_UNSPECIFIED", "TRAINING_OPERATION_ERROR_CODE_RESOURCE_EXHAUSTED", "TRAINING_OPERATION_ERROR_CODE_TIMEOUT", "TRAINING_OPERATION_ERROR_CODE_INTERNAL_ERROR", "TRAINING_OPERATION_ERROR_CODE_SESSION_NOT_ACTIVE", "TRAINING_OPERATION_ERROR_CODE_INVALID_INPUT", "TRAINING_OPERATION_ERROR_CODE_NON_FINITE_LOSS"]); export const rLTrainingOperationError = z.object({code: rLTrainingOperationErrorCode.optional(), message: z.string().optional()}); export const rLForwardBackwardOperation = z.object({id: z.string(), status: rLTrainingOperationStatus, output: rLForwardBackwardResult.optional(), error: rLTrainingOperationError.optional()}); 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 }; /** * Forward-backward pass * * POST /v1/rl/training-sessions/{session_id}/operations/forward-backward */ export const createApiV1RlTrainingSessionsSessionIdOperationsForwardBackward = async (args: CreateApiV1RlTrainingSessionsSessionIdOperationsForwardBackwardArgs, options?: CreateApiV1RlTrainingSessionsSessionIdOperationsForwardBackwardOptions) => { const {baseUrl = "https://api.together.ai", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/rl/training-sessions/${encodeURIComponent(String(args.session_id))}/operations/forward-backward${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(rLForwardBackwardOperation, await res.json()) };