Dashboard

Cookbook Recipe

Compute & Structured Data

Prepare training data on CPU, fine-tune on GPU

Use a CPU instance to build and validate a JSONL fine-tuning dataset on a Network Volume, then attach the same volume to a GPU instance for training.

POSThttps://api.devupai.com/v1/chat/completions

What you'll build

Data preparation and API-driven synthetic data generation are I/O-bound and network-bound rather than GPU-bound. By creating a Network Volume first and attaching it to a CPU instance, you generate, validate, and write /workspace/datasets/train.jsonl without paying for idle GPU time. Once the file is ready, you terminate the CPU instance and deploy a GPU instance in the same data center with the same Network Volume attached — your dataset is mounted immediately at /workspace/datasets/train.jsonl.

Before you start

  • An API key (sk-devup-...) exported as DEVUP_API_KEY. See Authentication.
  • A Network Volume created in a data center that also offers your target GPU model (see Regions & Data Residency), attached to a running CPU instance at /workspace.
  • Python 3.11 or later, or Node.js 22 or later.
pip install devupai

The complete program

Run this script on your CPU instance to generate schema-validated JSONL records and flush them to /workspace/datasets/train.jsonl.

"""Generate a validated JSONL training dataset on a CPU instance and write it to /workspace."""

import json
import os
from pathlib import Path
import sys

from devupai import APIConnectionError, DevupAI, DevupAPIError

MODEL = "deepseek-ai/DeepSeek-V4-Flash"
TIMEOUT_S = 60.0
OUTPUT_PATH = Path(os.environ.get("DATASET_PATH", "/workspace/datasets/train.jsonl"))

TOPICS = [
    "Explain how a Network Volume persists data across CPU and GPU instances.",
    "Summarize when to pause an instance versus when to terminate it.",
    "Describe how SSH local port forwarding exposes a service running on an instance.",
]

EXAMPLE_SCHEMA = {
    "type": "object",
    "additionalProperties": False,
    "required": ["instruction", "input", "output"],
    "properties": {
        "instruction": {"type": "string"},
        "input": {"type": "string"},
        "output": {"type": "string"},
    },
}


def validate_example(raw: str) -> dict[str, str]:
    """Parse and check one generated training record against the required non-empty string fields."""
    record = json.loads(raw)
    if not isinstance(record, dict):
        raise ValueError("Model reply is not a JSON object.")
    out: dict[str, str] = {}
    for field in ("instruction", "input", "output"):
        value = record.get(field)
        if not isinstance(value, str) or not value.strip():
            raise ValueError(f"Field '{field}' is missing or empty.")
        out[field] = value.strip()
    return out


def generate_example(client: DevupAI, topic: str) -> dict[str, str]:
    """Request one schema-constrained instruction example from Chat Completions."""
    completion = client.chat.completions.create(
        model=MODEL,
        messages=[
            {
                "role": "system",
                "content": "Create one concise instruction-tuning example for the given topic.",
            },
            {"role": "user", "content": topic},
        ],
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "training_example",
                "strict": True,
                "schema": EXAMPLE_SCHEMA,
            },
        },
        temperature=0.2,
    )
    if not completion.choices:
        raise ValueError("The response contained no choices.")
    content = completion.choices[0].message.content
    if not isinstance(content, str) or not content.strip():
        raise ValueError("The response contained no message text.")
    return validate_example(content)


def error_line(error: Exception) -> str:
    """Format one diagnostic line including x-request-id when available."""
    if isinstance(error, APIConnectionError):
        return f"No response from the API: {error}"
    if isinstance(error, DevupAPIError):
        return f"The API answered {error.status} {error.code or 'no code'} (x-request-id: {error.request_id or 'none'})."
    return str(error)


def main() -> None:
    if not os.environ.get("DEVUP_API_KEY", "").strip():
        print("Set DEVUP_API_KEY.", file=sys.stderr)
        sys.exit(1)

    client = DevupAI(api_key=os.environ["DEVUP_API_KEY"], max_retries=0, timeout=TIMEOUT_S)
    OUTPUT_PATH.parent.mkdir(parents=True, exist_ok=True)

    try:
        written = 0
        with OUTPUT_PATH.open("w", encoding="utf-8") as handle:
            for topic in TOPICS:
                example = generate_example(client, topic)
                handle.write(json.dumps(example, ensure_ascii=False) + "\n")
                handle.flush()
                written += 1
        print(f"Wrote {written} examples to {OUTPUT_PATH}")
    except Exception as exc:
        print(error_line(exc), file=sys.stderr)
        sys.exit(1)


if __name__ == "__main__":
    main()
Output shape
Plain text
Wrote 3 examples to /workspace/datasets/train.jsonl

How it works

1Request schema-constrained examples

Each call passes response_format: { type: "json_schema", ... } with strict: true and additionalProperties: false so every reply matches the instruction, input, and output schema. The program still validates each parsed object locally before writing it to the dataset file.

    completion = client.chat.completions.create(
        model=MODEL,
        messages=[
            {
                "role": "system",
                "content": "Create one concise instruction-tuning example for the given topic.",
            },
            {"role": "user", "content": topic},
        ],
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "training_example",
                "strict": True,
                "schema": EXAMPLE_SCHEMA,
            },
        },
        temperature=0.2,
    )

2Flush to the Network Volume at /workspace

Records are written line-by-line to /workspace/datasets/train.jsonl. In Node.js, the program waits for the write stream's finish event (await once(out, "finish")) before exiting so every byte is flushed to the Network Volume.

        with OUTPUT_PATH.open("w", encoding="utf-8") as handle:
            for topic in TOPICS:
                example = generate_example(client, topic)
                handle.write(json.dumps(example, ensure_ascii=False) + "\n")
                handle.flush()
                written += 1

3Switch the Network Volume from CPU to GPU

Once the script finishes on the CPU instance, terminate the CPU instance from My Compute. Its Container Disk is deleted, while the Network Volume retains /workspace/datasets/train.jsonl. Next, open Deploy New Instance under GPU, select your GPU model and the DEVUP AI PyTorch 2.4.0 template, attach the same Network Volume, and read /workspace/datasets/train.jsonl directly in your training job.

Next steps