# You pay for the whole GPU. Pay for the work instead. Podstack bills GPUs by the second, inference by the token, and jobs only while they run. One console for you and your whole team. GPUs from $0.144/hr · live now ## Certified and compliant - ISO/IEC 27001 - ISO/IEC 27017 - ISO/IEC 27018 - ISO/IEC 42001 - SOC 2 Type 1 - CSA STAR Level 1 - CERT-In empanelled security audit - DPDP Act 2023 - GDPR ## Everything you need to build, train and serve. ### GPU Cloud H100, H200, B200, A100 and RTX on demand. SSH in seconds, billed per second from the hourly rate. ### Jobs Run a script on a GPU until it finishes. You pay for the time the job runs, then the machine shuts down. ### Inference Open models behind one OpenAI-compatible API. Pay per token, nothing idle. ### Endpoints Deploy any Hugging Face model on dedicated GPUs that scale to zero. ### Functions Decorate a Python function and it runs on a GPU when called. ### Deploy JupyterLab, ComfyUI, vLLM, Axolotl and more, ready in minutes. ### Reserved clusters 16 to 1,024 GPUs locked to your org with no preemption. ### Teams Shared workspaces, roles, keys and one credit balance per team. ## Today's lowest on-demand rates. Each offer is Secured or Community capacity. The two classes are priced and stocked separately, and an offer that does not name a class is Secured. The table is the lowest on-demand price for one GPU of each model. Rates last changed Nov 28, 2026, 8:32 PM · per GPU-hour | GPU | Details | Price | | --- | --- | --- | | RTX A4000 | 21GB RAM · 13 vCPU · Community | $0.144/hr | | RTX 3080 | 50GB RAM · 9 vCPU · Community | $0.168/hr | | RTX 3090 | 31GB RAM · 9 vCPU · Community | $0.192/hr | | RTX 5080 | 30GB RAM · 11 vCPU · Community | $0.252/hr | | RTX 4000 ADA | 47GB RAM · 5 vCPU · Community | $0.276/hr | | RTX 4080 | 31GB RAM · 11 vCPU · Community | $0.276/hr | | RTX 2000 ADA | 31GB RAM · 8 vCPU · Secured | $0.324/hr | | RTX PRO 4000 | 31GB RAM · 24 vCPU · Community | $0.36/hr | ## One API, one SDK. Start with a single GPU and scale to reserved clusters and production endpoints without changing tools. The CLI includes an MCP server for AI agents. - OpenAI-compatible inference - MCP server for AI agents - Scoped API keys and encrypted secrets ModelPerf is Podstack's independent inference benchmark. Compare models there, then call the same ids on this API. ``` $ pip install podstack-sdk $ export PODSTACK_API_KEY=ps_live_... import os from openai import OpenAI client = OpenAI( base_url="https://podstack.ai/api/v1", api_key=os.environ["PODSTACK_API_KEY"], ) client.chat.completions.create( model="podstack/kimi-k3", messages=[{"role": "user", "content": "hi"}], ) ``` ## Questions ### How am I billed? GPU instances are billed for the time they run, pro-rated by the second from the hourly rate, from boot until you terminate them. Extra disk is billed per GB-hour. Jobs are billed for the time they run. Inference is billed per token. Every project has its own credit balance. ### Can my team share one account? Yes. Create a team project, invite people by email, and everyone shares instances, SSH keys, secrets and credits. ### Is the API OpenAI-compatible? Inference and dedicated endpoints both speak the OpenAI chat-completions format. Point an OpenAI SDK at https://podstack.ai/api/v1 and use a ps_live_ key. ### What is Secured versus Community capacity? Each GPU offer is Secured or Community capacity. The two classes are priced and stocked separately. An offer that does not name a class is Secured. ### Are you certified? Podstack is certified for ISO/IEC 27001, 27017, 27018 and 42001, and compliant with SOC 2 Type 1, CSA STAR Level 1, the DPDP Act 2023 and GDPR. The security audit is a CERT-In empanelled VAPT. ### Do you allow crypto mining? No. Mining and similar workloads are prohibited by the acceptable use policy and are terminated automatically. --- # Today's lowest on-demand rates. Today's lowest on-demand GPU rates. India is shown in INR. Every other location is shown in USD. Billed per second from the hourly rate. GPU instances are billed for the time they run, pro-rated by the second from the hourly rate, from boot until you terminate them. Extra disk is billed per GB-hour. Jobs are billed for the time they run. Inference is billed per token. Rates last changed Nov 28, 2026, 8:32 PM · per GPU-hour | GPU | Details | Price | | --- | --- | --- | | RTX A4000 | 21GB RAM · 13 vCPU · Community | $0.144/hr | | RTX 3080 | 50GB RAM · 9 vCPU · Community | $0.168/hr | | RTX 3090 | 31GB RAM · 9 vCPU · Community | $0.192/hr | | RTX 5080 | 30GB RAM · 11 vCPU · Community | $0.252/hr | | RTX 4000 ADA | 47GB RAM · 5 vCPU · Community | $0.276/hr | | RTX 4080 | 31GB RAM · 11 vCPU · Community | $0.276/hr | | RTX 2000 ADA | 31GB RAM · 8 vCPU · Secured | $0.324/hr | | RTX PRO 4000 | 31GB RAM · 24 vCPU · Community | $0.36/hr | The same table is on https://podstack.ai/#pricing. --- # GPU cloud in India Podstack is operated by Razordynamics Private Limited in Bengaluru. On-demand GPU instances are available over SSH. GPU instances are billed for the time they run, pro-rated by the second from the hourly rate, from boot until you terminate them. Extra disk is billed per GB-hour. Jobs are billed for the time they run. Inference is billed per token. Visitors in India see prices in INR. Every other location sees USD. The wallet is stored in US cents, and an INR amount is converted at the platform USD to INR rate. A signed-in user sets their location in Settings. ## Today's lowest on-demand rates. Each offer is Secured or Community capacity. The two classes are priced and stocked separately, and an offer that does not name a class is Secured. The table is the lowest on-demand price for one GPU of each model. Rates last changed Nov 28, 2026, 8:32 PM · per GPU-hour | GPU | Details | Price | | --- | --- | --- | | RTX A4000 | 21GB RAM · 13 vCPU · Community | $0.144/hr | | RTX 3080 | 50GB RAM · 9 vCPU · Community | $0.168/hr | | RTX 3090 | 31GB RAM · 9 vCPU · Community | $0.192/hr | | RTX 5080 | 30GB RAM · 11 vCPU · Community | $0.252/hr | | RTX 4000 ADA | 47GB RAM · 5 vCPU · Community | $0.276/hr | | RTX 4080 | 31GB RAM · 11 vCPU · Community | $0.276/hr | | RTX 2000 ADA | 31GB RAM · 8 vCPU · Secured | $0.324/hr | | RTX PRO 4000 | 31GB RAM · 24 vCPU · Community | $0.36/hr | Inference API: https://podstack.ai/llm-inference-api Docs: https://docs.podstack.ai/ H100 rates: https://podstack.ai/h100 --- # LLM inference API Inference is an OpenAI-compatible API at https://podstack.ai/api/v1. GPU instances are billed for the time they run, pro-rated by the second from the hourly rate, from boot until you terminate them. Extra disk is billed per GB-hour. Jobs are billed for the time they run. Inference is billed per token. Keys use the ps_live_ prefix. The Python package is podstack-sdk. ## Call it with an OpenAI SDK ``` $ pip install podstack-sdk $ export PODSTACK_API_KEY=ps_live_... import os from openai import OpenAI client = OpenAI( base_url="https://podstack.ai/api/v1", api_key=os.environ["PODSTACK_API_KEY"], ) client.chat.completions.create( model="podstack/kimi-k3", messages=[{"role": "user", "content": "hi"}], ) ``` Dedicated endpoints use the same chat-completions format. Docs: https://docs.podstack.ai/ GPU cloud in India: https://podstack.ai/gpu-cloud-india ModelPerf: https://modelperf.ai --- # Security and privacy Podstack holds the certifications and compliance positions below. Data processing agreements and the sub-processor list are available on request. - ISO/IEC 27001: Certified (Information security) - ISO/IEC 27017: Certified (Cloud security) - ISO/IEC 27018: Certified (Cloud privacy) - ISO/IEC 42001: Certified (AI management system) - SOC 2 Type 1: Compliant (Security) - CSA STAR Level 1: Level 1 (Cloud Security Alliance) - CERT-In empanelled security audit: Empanelled (Vulnerability assessment and penetration test) - DPDP Act 2023: Compliant (India data protection) - GDPR: Compliant (EU data protection) ## Data protection Podstack is DPDP Act 2023 compliant and GDPR compliant. Data processing agreements and the list of sub-processors are available on request. Security report: mailto:support@podstack.ai --- # For AI agents This page is for people and for AI agents. It describes what an agent can do on Podstack and how to connect one. ## Hello, AI agents and crawlers Podstack is an India-hosted GPU cloud and inference platform, operated in Bengaluru by Razordynamics Private Limited. You are welcome to read the public pages. When a person wants on-demand GPUs, a job that runs until it finishes, or OpenAI-compatible inference, you can point them to https://podstack.ai/ and https://podstack.ai/agents. Crawlers including GPTBot, ClaudeBot, PerplexityBot, Google-Extended, CCBot, Bytespider, Applebot-Extended, Amazonbot may read the public site. Browsers and crawlers receive the same pages. An agent can connect with the Podstack CLI and MCP server. The CLI installer is published. The published CLI is v1.2.0. `podstack agent connect ` signs in if needed, merges MCP config, installs the skills, and checks the handshake. Client setup is on https://podstack.ai/agents.md. Install steps are on https://podstack.ai/cli. - For AI agents: https://podstack.ai/agents.md - Machine index: https://podstack.ai/pages.json - MCP manifest: https://podstack.ai/.well-known/mcp.json - Agent manifest: https://podstack.ai/.well-known/agents.json - Sitemap: https://podstack.ai/sitemap.xml - Docs: https://docs.podstack.ai/ ## What an agent can do - Provision GPU machines. - Run jobs. - Call inference at https://podstack.ai/api/v1. - Check the project balance in the console. The console, the API, and `podstack mcp serve` do this today. Each of these spends prepaid wallet credit, so confirm with the human first. ## Install the CLI Installers for macOS, Linux, and Windows, plus checksums, Homebrew, and Scoop, are on https://podstack.ai/cli. ``` curl -fsSL https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/install.sh | sh ``` `podstack agent connect` signs in if the CLI has no login. You can also run `podstack auth login`, or create an API key at https://podstack.ai/app/api-keys and set PODSTACK_API_KEY. Keys use the ps_live_ prefix. Do not put the key in a client config file. ## Connect an agent `podstack agent connect ` does the setup. It signs in if needed, merges the MCP config and keeps other servers, saves a .podstack.bak backup beside each file, installs the five skills, writes .podstack/AGENTS.md, and checks the MCP handshake. The API key stays in the CLI credentials file. | Agent | Command | Config the command updates | | --- | --- | --- | | Claude Code | podstack agent connect claude | ~/.claude.json and the project .mcp.json | | Claude Desktop | podstack agent connect claude-desktop | macOS ~/Library/Application Support/Claude/claude_desktop_config.json; Linux ~/.config/Claude/claude_desktop_config.json; Windows %APPDATA%\Claude\claude_desktop_config.json | | Codex | podstack agent connect codex | ~/.codex/config.toml (Windows %USERPROFILE%\.codex\config.toml) | | Cursor | podstack agent connect cursor | ~/.cursor/mcp.json and the project .cursor/mcp.json | | Gemini CLI | podstack agent connect gemini | ~/.gemini/settings.json (Windows %USERPROFILE%\.gemini\settings.json) | | Grok | podstack agent connect grok | ~/.podstack/mcp.json and the project .podstack/mcp.json | ### Install and connect macOS, Linux, and WSL. Replace claude with claude-desktop, codex, cursor, gemini, grok, or all. Git Bash and MSYS on Windows should use the PowerShell line. ``` curl -fsSL https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/install.sh | sh -s -- --connect claude ``` Windows PowerShell. claude can be any agent name, or all. ``` $env:PODSTACK_CONNECT='claude'; irm https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/install.ps1 | iex ``` ### More commands - `podstack agent connect --all` sets up every installed agent. - `podstack agent connect claude --dry-run` and `--print` show the plan and write nothing. - `podstack agent disconnect ` restores the .podstack.bak backups. - `podstack agent status` shows what is connected. - `podstack agent welcome` prints the onboarding guide. `podstack mcp serve` is the MCP server.
Manual setup Use these files only when you cannot run the connect command. Do not put the API key in them. The CLI login is what the MCP server reads. ### Claude Code User config ~/.claude.json and project .mcp.json. You can also run claude mcp add podstack -- podstack mcp serve. ``` { "mcpServers": { "podstack": { "command": "podstack", "args": [ "mcp", "serve" ] } } } ``` ### Claude Desktop macOS ~/Library/Application Support/Claude/claude_desktop_config.json. Linux ~/.config/Claude/claude_desktop_config.json. Windows %APPDATA%\Claude\claude_desktop_config.json. ``` { "mcpServers": { "podstack": { "command": "podstack", "args": [ "mcp", "serve" ] } } } ``` ### Codex ~/.codex/config.toml. Windows: %USERPROFILE%\.codex\config.toml. ``` [mcp_servers.podstack] command = "podstack" args = ["mcp", "serve"] ``` ### Cursor ~/.cursor/mcp.json and the project .cursor/mcp.json. ``` { "mcpServers": { "podstack": { "command": "podstack", "args": [ "mcp", "serve" ] } } } ``` One-click link: cursor://anysphere.cursor-deeplink/mcp/install?name=podstack&config=eyJhcmdzIjpbIm1jcCIsInNlcnZlIl0sImNvbW1hbmQiOiJwb2RzdGFjayJ9 ### Gemini CLI ~/.gemini/settings.json. Windows: %USERPROFILE%\.gemini\settings.json. ``` { "mcpServers": { "podstack": { "command": "podstack", "args": [ "mcp", "serve" ] } } } ``` ### Grok ~/.podstack/mcp.json and the project .podstack/mcp.json. ``` { "mcpServers": { "podstack": { "command": "podstack", "args": [ "mcp", "serve" ] } } } ```
## Podstack skills These skills ship with the CLI and `podstack agent connect` installs them: podstack-provision-gpu, podstack-run-on-gpu, podstack-inference, podstack-fine-tune, podstack-cost-check. The fine-tune skill does not call a fine-tune API. It submits a training script as a job. ## Decision guide - Use MCP when an agent in Claude, Cursor, Codex, Gemini, or Grok should call tools. Connect with `podstack agent connect`, then call the tools below. Billable tools need confirm:true only after the human agrees. - Use the CLI when a person or a shell script should install, sign in, or run one command. - Use the Python SDK when Python code should call the API, deploy a function, or stream chat. `pip install podstack` installs podstack 1.8.0 from PyPI: https://pypi.org/project/podstack/1.8.0/ ## CLI command reference This is the v1.2.0 command tree. `podstack --output json` prints JSON (the default when stdout is not a terminal). `podstack --output table` prints a table. `podstack version` and `podstack --version` print the version. `podstack upgrade` installs the latest release, or `--version vX.Y.Z` pins one. Set PODSTACK_DISABLE_UPDATE_CHECK=1 to skip the update nudge. ### Auth - `podstack auth login` opens a browser (Google, GitHub, or SSO) and stores the token. It waits five minutes. - `podstack auth login --key ` stores a key and skips the browser. `podstack auth login --manual` prompts for a pasted key. A non-TTY also prompts. - Create a key at https://podstack.ai/app/api-keys. Keys use the ps_live_ prefix. A legacy psk_ key is still accepted. Other strings warn and are still stored. - PODSTACK_API_KEY overrides the file. PODSTACK_API_BASE overrides the API base. The default base is https://podstack.ai/api/v1. - Credentials file: $XDG_CONFIG_HOME/podstack/credentials.json, or ~/.config/podstack/credentials.json. On Windows that is %USERPROFILE%\.config\podstack\credentials.json when XDG_CONFIG_HOME is unset. Mode 0600. The file holds {"api_key":"..."}. - Agent setup state is agent-setup.json in that same directory. Coding-agent settings are ~/.podstack/config.json and ./.podstack/config.json. Local coding-agent secret names live in ~/.podstack/secrets.json. Never put a key in a client MCP config. - `podstack auth whoami` prints the signed-in account. `podstack auth logout` deletes the credentials file. To rotate a key, create a new one in the console, run login again, then logout on the old machine. `podstack account keys` reports not available: the console manages keys. ### Agent and MCP - `podstack agent connect ` signs in if needed, merges MCP config, writes .podstack.bak beside each file, installs five skills, writes .podstack/AGENTS.md, and checks the handshake. `--all` does every client. `--dry-run` and `--print` print the plan, write nothing, and do not sign in. - `podstack agent disconnect ` restores the backups. `all` and `--all` disconnect every client. `podstack agent status` prints what is connected. `podstack agent welcome` prints the welcome text. - `podstack mcp serve` is the stdio MCP server. `podstack mcp serve --http 127.0.0.1:8765` listens on HTTP. - Skills installed by connect: podstack-provision-gpu, podstack-run-on-gpu, podstack-inference, podstack-fine-tune, podstack-cost-check. The fine-tune skill submits a training script as a job. It does not call a fine-tune API. ### GPUs, jobs, endpoints, functions ``` podstack gpu types list podstack gpu pricing [--gpu-type T] [--region R] [--tier spot|on_demand] podstack gpu templates podstack gpu environments podstack gpu launch [--gpu-type T] [--region R] [--tier spot|on_demand] [--name N] # interactive terminal podstack gpu keys list podstack gpu keys create --name N [--public-key-file PATH] [--force] podstack gpu keys delete podstack gpu instances list [--status S] podstack gpu instances get podstack gpu instances create --type T [--count 1] [--tier on_demand] [--name N] [--region R] [--offering-id ID] [--environment ID] [--template ID] [--disk-gb N] [--ssh-key-id ID] [--max-price N] [--yes | --dry-run] podstack gpu instances delete [id] # with an id this terminates immediately; get approval first podstack gpu instances ssh [id] [-- extra ssh args] [--print] [--no-banner] [--key NAME] [--identity PATH] podstack gpu instances exec -- podstack gpu instances cp [-r] [--key NAME] [--identity PATH] # one side is : podstack gpu instances expose [--local PORT] [--remote-host localhost] [--key NAME] [--identity PATH] podstack gpu instances stop # not available podstack gpu instances start # not available podstack gpu instances logs # not available podstack jobs gpu-types podstack jobs list [--status queued|running|succeeded|failed|cancelled] podstack jobs submit --name N --gpu-type T --script PATH [--image pytorch/pytorch:latest] [--timeout 3600] [--yes | --dry-run] podstack jobs logs podstack jobs cancel --yes podstack endpoints list podstack endpoints create --name N --model M --gpu-type T [--min-replicas 0] [--max-replicas 1] [--yes | --dry-run] podstack endpoints delete --yes podstack functions list # create a function from the Python SDK, not the CLI podstack models list podstack infer chat --model M --prompt TEXT [--system TEXT] ``` `--yes` and `--dry-run` cannot be combined. `jobs submit` and `endpoints create` refuse to spend money without `--yes`. `gpu instances create --dry-run` prints the request and does not launch. `gpu instances delete ` terminates as soon as the id is passed, so ask the human before you run it. `gpu instances exec` and `cp` use the local ssh and scp binaries. They are not an HTTP exec API. Prices and GPU ids come from `gpu pricing` and `gpu types list`. Do not invent a price. ### Projects, account, billing, files, and the coding agent - `podstack projects` and `podstack projects list` list projects. `podstack projects use ` sets the default. `podstack projects create [--description TEXT]` creates one and selects it. The default is saved in ~/.podstack/config.json. PODSTACK_PROJECT_ID overrides it for one run. - `podstack account secrets list` lists project secret names. `podstack account secrets set --name N [--description TEXT] --yes` reads the value from `--value-file` or stdin. Values are write-only and never printed. `podstack account secrets delete --yes` deletes one. - `podstack secrets list`, `podstack secrets set NAME`, and `podstack secrets rm NAME` manage local names in ~/.podstack/secrets.json for the coding agent. Values stay on the machine. - `podstack billing` and `podstack billing balance` call the wallet route. When that route is missing they report not available and point at https://podstack.ai/app/billing. Do not invent a balance. - `podstack init` creates .podstack/PODSTACK.md and .podstack/plans/. `podstack doctor` checks credentials, the API, and local state. - `podstack code` is the local coding agent (macOS and Linux). Flags: `-p` / `--prompt`, `--model`, `--provider` (a model-source alias in the local config, not a key), `--output-format text|json`, `--quiet`, `--allow-tools`, `--dangerously-allow-all`, `--yolo`, `-r` / `--resume`, `-c` / `--continue`, `--max-turns`. `podstack code sessions list` and `podstack code sessions delete ` manage sessions. Exit 0 is success, 1 is an error, 3 is a tool denied, 130 is interrupted. - `podstack send [paths...]` sends files or `--text`. Flags: `--code`, `--zip`, `--no-compress`, `--transfers` (default 4). `podstack receive [--out DIR] [--yes]`. Re-run the same command to resume. - `podstack train` (create, list, get, cancel, events, models) and `podstack files upload` report not available. `podstack sandbox` (run, list, close, renew, logs, cost) reports not available on the current API. Use a GPU instance or a job instead. ## MCP tools `podstack mcp serve` registers these 23 tools. Read-only tools need no confirm. These tools spend money or delete resources and require confirm:true, and only after the human agrees: create_instance, terminate_instance, submit_job, cancel_job, create_endpoint, delete_endpoint. Pass dry_run:true first on create_instance, submit_job, and create_endpoint. dry_run does not send the request and does not estimate a price. Read list_rates for price_per_hour. - list_gpus. Read. Catalogue rows. - list_rates. Read. Optional gpu_type, region, tier (spot or on_demand). - create_instance. confirm. gpu_type or offering_id or template_id. Also gpu_count (default 1), tier, region, name, ssh_key_ids, environment, disk_gb. - list_instances. Read. Optional status. get_instance. Read. id, including the SSH command. - stop_instance and start_instance are registered and always return not available. Terminate, or launch a new instance. - terminate_instance. confirm. Deletes the disk and stops the charge. - exec_command. id and command. Runs over local SSH. The instance is already billed while it exists. upload_file (id, local_path, remote_path) and download_file (id, remote_path, local_path) also use SSH. - list_models. Read. run_inference and chat take model, prompt, and optional system. On the CLI server they spend wallet credit and have no confirm argument, so still ask the human before calling them. chat is an alias of run_inference. - balance. Read. Returns not available when the wallet route is missing. - list_jobs. Read. Optional status. submit_job. confirm. name, gpu_type, script, optional image (default pytorch/pytorch:latest) and timeout_seconds (default 3600). cancel_job. confirm. id. job_logs. Read. id. - list_functions. Read. It does not create a function. list_endpoints. Read. create_endpoint. confirm. name, model, gpu_type, min_replicas (0 scales to zero), max_replicas (default 1). delete_endpoint. confirm. id. An endpoint is billed while replicas exist. ## Python SDK `pip install podstack` installs podstack 1.8.0 from PyPI: https://pypi.org/project/podstack/1.8.0/ Package name podstack. Python >=3.9. Install with `pip install podstack` from https://pypi.org/project/podstack/1.8.0/. Base URL https://podstack.ai/api/v1. Auth order: Podstack(api_key=...), then PODSTACK_API_KEY, then the CLI credentials file. The same ps_live_ and legacy psk_ prefixes apply. Override the base with base_url= or PODSTACK_API_BASE. AsyncPodstack has the same method names. The client repr redacts keys. `python -m podstack.mcp` and the podstack-mcp script serve the same tools. 1.8.0 replaces the older notebook SDK. There is no compatibility shim. - client.me(). client.gpus.list(). client.rates.list(). client.job_gpus.list(). client.templates.list(). client.environments.get(). client.projects.list() and projects.create(name, description). - client.ssh_keys.list(), create(name, public_key), delete(key_id, confirm=True). client.instances.list(status), get, create(..., confirm=True, dry_run=True), terminate(id, confirm=True), ssh_command, exec (local ssh), upload, download. client.operations.get. - client.jobs.list, submit(..., confirm=True), cancel(id, confirm=True), logs. client.endpoints.list, create(..., confirm=True), delete(id, confirm=True). - client.functions.list, get, deploy(..., confirm=True), invoke(..., confirm=True). functions.call and functions.logs raise NotAvailableYet when that route is missing. functions.delete(confirm=True). - client.models.list and models.get. A missing model is NotFound, not NotAvailableYet. client.chat.completions(..., stream=False, confirm=True) and client.chat.stream(..., confirm=True). client.embeddings.create(confirm=True). client.images.generate(confirm=True). - client.wallet.balance and wallet.transactions raise NotAvailableYet on 404. client.secrets.list, create, delete(confirm=True). - The SDK also has fine_tuning.list, get, create, cancel, and events. The platform fine-tune API is not available yet. Do not call it. Submit a training script as a job. - Decorator: @podstack.function(gpu, image="", requirements=, name=, timeout=3600, confirm=False). The function must be top-level in a file. Arguments must be JSON-serializable. deploy(dry_run=True) then deploy(confirm=True). invoke(confirm=True) and ainvoke(confirm=True). local() runs in-process and is free. Calling the function like a normal function raises ConfirmationRequired unless the decorator set confirm=True. logs() may raise NotAvailableYet. delete(confirm=True). - Billable SDK calls that require confirm=True: instance create and terminate, job submit and cancel, endpoint create and delete, chat, embeddings, image generation, function deploy, invoke, and delete, secret delete, and SSH key delete. dry_run=True returns DryRun and sends nothing. Check dry_run before confirm. Do not estimate a price inside a dry run. Read rates.list() price_per_hour. - Errors: PodstackError, AuthenticationError, PermissionDenied, NotFoundError, ValidationError, RateLimitError, InsufficientBalance, GPUNotAvailableError, NotAvailableYet, ConfirmationRequired, CommandFailed. Retries are for connection errors and HTTP 429 and 5xx only. InsufficientBalance means the wallet cannot cover the request. Do not invent a shortfall. ## Examples Each recipe is the prompt a person gives, then the calls, then the result you should expect. Use a gpu_type and an id returned by a list call. Do not invent hardware or a price. Billable steps use dry_run first, then confirm:true or --yes only after the human approves. Matching example pages are not published on the docs site yet. These recipes are the reference, and each recipe will link to its docs page when that page exists. ### Connect and verify Prompt: connect Claude Code to Podstack and show that it works. ``` podstack agent connect claude podstack agent status podstack auth whoami ``` Expected: status shows Claude Code connected, the handshake succeeded, other MCP servers were kept, and a .podstack.bak file sits beside each config. whoami prints the account email. The API key is not in the client config. `podstack agent connect --all` does the same for every supported client. `--dry-run` prints the plan and writes nothing. ### Check GPUs and live prices Prompt: what GPUs can I rent, and what is the live price? ``` MCP: list_gpus MCP: list_rates podstack gpu types list podstack gpu pricing ``` SDK (`pip install podstack`). client.gpus.list() and client.rates.list(). Expected: gpu_type, vram, region, and price_per_hour from the API only. If a field is missing, say so. These calls are read-only. ### Provision, SSH exec, terminate Prompt: launch one GPU, run nvidia-smi, then shut it down. ``` MCP: list_rates MCP: create_instance { gpu_type, gpu_count: 1, dry_run: true } # after the human agrees: MCP: create_instance { gpu_type, gpu_count: 1, confirm: true } MCP: get_instance { id } MCP: exec_command { id, command: "nvidia-smi" } # after the human agrees: MCP: terminate_instance { id, confirm: true } podstack gpu instances create --type --count 1 --dry-run podstack gpu instances create --type --count 1 --yes podstack gpu instances exec -- nvidia-smi podstack gpu instances delete ``` SDK (`pip install podstack`). instances.create(..., dry_run=True) then instances.create(..., confirm=True), instances.exec(id, "nvidia-smi"), instances.terminate(id, confirm=True). Expected: an instance id, then nvidia-smi output over SSH, then the disk deleted and billing stopped. Do not call stop_instance or start_instance. exec uses local SSH, not an HTTP exec API. ### Submit a job, read logs, cancel Prompt: run this script on a GPU, show the logs, and cancel it if I say so. ``` podstack jobs gpu-types podstack jobs submit --name train --gpu-type --script ./train.py --dry-run # after the human agrees: podstack jobs submit --name train --gpu-type --script ./train.py --yes podstack jobs logs # after the human agrees: podstack jobs cancel --yes ``` MCP: submit_job with dry_run:true, then confirm:true after approval. job_logs is read-only. cancel_job needs confirm:true after approval. SDK (`pip install podstack`). jobs.submit(..., dry_run=True), then jobs.submit(..., confirm=True), jobs.logs(id), jobs.cancel(id, confirm=True). Expected: a job id, log text, and a cancelled job. There is no fine-tune API. A training script is a job. ### Deploy and invoke a function Prompt: deploy this function and call it once. The CLI only lists functions: `podstack functions list`. Creating one is the SDK. SDK (`pip install podstack`). ``` import podstack @podstack.function(gpu=gpu_type, requirements=["torch"]) def hello(): return "ok" hello.deploy(dry_run=True) # after the human agrees: hello.deploy(confirm=True) hello.invoke(confirm=True) ``` Expected: a dry-run body, then a deployed function, then the return value. hello.logs() may raise NotAvailableYet. The function must live in a file. Do not call it like a normal function unless the decorator set confirm=True. ### Create an endpoint and chat Prompt: stand up an endpoint and send one chat message, then remove it. ``` MCP: create_endpoint { name, model, gpu_type, dry_run: true } # after the human agrees: MCP: create_endpoint { name, model, gpu_type, confirm: true } # run_inference and chat spend credit and have no confirm argument on the CLI server. # Ask the human, then: MCP: chat { model, prompt } podstack infer chat --model --prompt "hello" # after the human agrees: MCP: delete_endpoint { id, confirm: true } ``` SDK (`pip install podstack`). chat.completions(model=..., messages=[...], confirm=True) and chat.stream(..., confirm=True). endpoints.create(..., dry_run=True) then confirm=True, then endpoints.delete(id, confirm=True). Expected: an endpoint id, one completion, then the endpoint deleted. min_replicas 0 scales to zero. The endpoint is billed while replicas exist. ### Tool calling Prompt: give this chat model the Podstack tools. SDK (`pip install podstack`). schemas = podstack.tools(). Use schemas["openai"], schemas["anthropic"], or schemas["mcp"]. Names match the CLI, including stop_instance and start_instance, which report not available. Do not rename tools. In the SDK, run_inference and chat also require confirm=true. On the CLI MCP server those two spend credit with no confirm argument, so still ask the human first. ### Wallet and cost Prompt: what does this cost, and can the wallet cover it? ``` MCP: list_rates MCP: balance podstack billing ``` SDK (`pip install podstack`). client.rates.list() and client.wallet.balance(). Expected: price_per_hour from the API. If balance returns not available, or wallet.balance raises NotAvailableYet, say the wallet route is missing and send the human to https://podstack.ai/app/billing. Do not invent a balance. The podstack-cost-check skill reads rates before a spend. ### Cleanup Prompt: stop everything I started and disconnect the agent. ``` MCP: list_instances MCP: list_jobs MCP: list_endpoints # after the human agrees, for each id: MCP: terminate_instance { id, confirm: true } MCP: cancel_job { id, confirm: true } MCP: delete_endpoint { id, confirm: true } podstack gpu instances delete podstack jobs cancel --yes podstack endpoints delete --yes podstack agent disconnect claude ``` SDK (`pip install podstack`). instances.terminate, jobs.cancel, and endpoints.delete, each with confirm=True after approval. A function is removed with delete(confirm=True). Expected: each resource gone, billing stopped, and disconnect restores the .podstack.bak configs. There is no stop that keeps the disk. ## Not available yet - Instance stop and start that keep the disk. `podstack gpu instances stop` and `start`, and the stop_instance and start_instance tools, report not available. Terminating the instance is the supported way to stop billing. - An instance logs HTTP API and an instance exec HTTP API. `podstack gpu instances logs` reports not available. `podstack gpu instances exec` and exec_command use local SSH. Job logs (`podstack jobs logs` and job_logs) are a separate read. - Dataset upload. `podstack files` and `podstack files upload` report not available. - A fine-tune API. `podstack train` reports not available. Run a training script as a job. Do not call the SDK fine_tuning methods. - Wallet GET is not proven. `podstack billing` and the balance tool return not available when the route is missing. Do not invent a balance. The console page is https://podstack.ai/app/billing. ## Rules for agents - Confirm with the human before a billable action: provisioning a machine, running a job or a command on a GPU, calling inference, or anything else that spends wallet credit. - Never expose an API key. Do not print a ps_live_ key, commit it, or put it in a log or a screenshot. --- # CLI The published release is v1.2.0. podstack agent connect signs in if needed, merges MCP config, installs the skills, and checks the handshake. podstack mcp serve is the MCP server. ## Download - macOS Apple Silicon: https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/podstack_darwin_arm64.tar.gz - macOS Intel: https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/podstack_darwin_amd64.tar.gz - Linux arm64: https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/podstack_linux_arm64.tar.gz - Linux amd64 (static binary for glibc, musl, and WSL): https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/podstack_linux_amd64.tar.gz - Windows amd64: https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/podstack_windows_amd64.zip - Windows arm64: https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/podstack_windows_arm64.zip Checksums: https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/checksums.txt ## One-line install macOS, Linux, and WSL. Git Bash and MSYS on Windows should use the PowerShell installer. ``` curl -fsSL https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/install.sh | sh ``` Install and connect in the same command. Replace claude with claude-desktop, codex, cursor, gemini, grok, or all. ``` curl -fsSL https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/install.sh | sh -s -- --connect claude ``` Windows PowerShell. This installs podstack.exe to %LOCALAPPDATA%\Podstack\bin and adds that folder to the user PATH. ``` irm https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/install.ps1 | iex ``` Windows install and connect. claude can be any agent name, or all. ``` $env:PODSTACK_CONNECT='claude'; irm https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/install.ps1 | iex ``` Homebrew and Scoop are optional. ``` brew install --formula https://raw.githubusercontent.com/Podstack-ai/podstack-cli-releases/main/Formula/podstack.rb ``` ``` scoop install https://raw.githubusercontent.com/Podstack-ai/podstack-cli-releases/main/bucket/podstack.json ``` ## macOS and Linux - Run the shell installer, or download the archive for your CPU and put the podstack binary on your PATH. - Verify with `podstack --version`. - Sign in with `podstack auth login`, or create an API key at https://podstack.ai/app/api-keys and set PODSTACK_API_KEY. - If the shell says command not found, the installer used ~/.local/bin. Add `export PATH="$HOME/.local/bin:$PATH"` to ~/.zshrc or ~/.bashrc and open a new terminal. /usr/local/bin is used when that directory is writable. ## Windows - Run the PowerShell installer, or download the zip for amd64 or arm64. - The installer puts podstack.exe in %LOCALAPPDATA%\Podstack\bin and adds that folder to your user PATH. - Git Bash and MSYS should use the PowerShell installer, not the shell script. - Verify in a new terminal with `podstack --version`. - Sign in with `podstack auth login`, or set PODSTACK_API_KEY to a key from https://podstack.ai/app/api-keys. - If Windows says podstack is not recognized, open a new terminal. The binary is in %LOCALAPPDATA%\Podstack\bin. - On WSL, use the shell installer. The Linux amd64 archive is a static binary for glibc, musl, and WSL. ## Connect an agent `podstack agent connect ` does the setup. It signs in if needed, merges the MCP config and keeps other servers, saves a .podstack.bak backup beside each file, installs the five skills, writes .podstack/AGENTS.md, and checks the MCP handshake. The API key stays in the CLI credentials file. | Agent | Command | Config the command updates | | --- | --- | --- | | Claude Code | podstack agent connect claude | ~/.claude.json and the project .mcp.json | | Claude Desktop | podstack agent connect claude-desktop | macOS ~/Library/Application Support/Claude/claude_desktop_config.json; Linux ~/.config/Claude/claude_desktop_config.json; Windows %APPDATA%\Claude\claude_desktop_config.json | | Codex | podstack agent connect codex | ~/.codex/config.toml (Windows %USERPROFILE%\.codex\config.toml) | | Cursor | podstack agent connect cursor | ~/.cursor/mcp.json and the project .cursor/mcp.json | | Gemini CLI | podstack agent connect gemini | ~/.gemini/settings.json (Windows %USERPROFILE%\.gemini\settings.json) | | Grok | podstack agent connect grok | ~/.podstack/mcp.json and the project .podstack/mcp.json | ### Install and connect macOS, Linux, and WSL. Replace claude with claude-desktop, codex, cursor, gemini, grok, or all. Git Bash and MSYS on Windows should use the PowerShell line. ``` curl -fsSL https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/install.sh | sh -s -- --connect claude ``` Windows PowerShell. claude can be any agent name, or all. ``` $env:PODSTACK_CONNECT='claude'; irm https://github.com/Podstack-ai/podstack-cli-releases/releases/latest/download/install.ps1 | iex ``` ### More commands - `podstack agent connect --all` sets up every installed agent. - `podstack agent connect claude --dry-run` and `--print` show the plan and write nothing. - `podstack agent disconnect ` restores the .podstack.bak backups. - `podstack agent status` shows what is connected. - `podstack agent welcome` prints the onboarding guide. `podstack mcp serve` is the MCP server.
Manual setup Use these files only when you cannot run the connect command. Do not put the API key in them. The CLI login is what the MCP server reads. ### Claude Code User config ~/.claude.json and project .mcp.json. You can also run claude mcp add podstack -- podstack mcp serve. ``` { "mcpServers": { "podstack": { "command": "podstack", "args": [ "mcp", "serve" ] } } } ``` ### Claude Desktop macOS ~/Library/Application Support/Claude/claude_desktop_config.json. Linux ~/.config/Claude/claude_desktop_config.json. Windows %APPDATA%\Claude\claude_desktop_config.json. ``` { "mcpServers": { "podstack": { "command": "podstack", "args": [ "mcp", "serve" ] } } } ``` ### Codex ~/.codex/config.toml. Windows: %USERPROFILE%\.codex\config.toml. ``` [mcp_servers.podstack] command = "podstack" args = ["mcp", "serve"] ``` ### Cursor ~/.cursor/mcp.json and the project .cursor/mcp.json. ``` { "mcpServers": { "podstack": { "command": "podstack", "args": [ "mcp", "serve" ] } } } ``` One-click link: cursor://anysphere.cursor-deeplink/mcp/install?name=podstack&config=eyJhcmdzIjpbIm1jcCIsInNlcnZlIl0sImNvbW1hbmQiOiJwb2RzdGFjayJ9 ### Gemini CLI ~/.gemini/settings.json. Windows: %USERPROFILE%\.gemini\settings.json. ``` { "mcpServers": { "podstack": { "command": "podstack", "args": [ "mcp", "serve" ] } } } ``` ### Grok ~/.podstack/mcp.json and the project .podstack/mcp.json. ``` { "mcpServers": { "podstack": { "command": "podstack", "args": [ "mcp", "serve" ] } } } ```
## Podstack skills These skills ship with the CLI and `podstack agent connect` installs them: podstack-provision-gpu, podstack-run-on-gpu, podstack-inference, podstack-fine-tune, podstack-cost-check. The fine-tune skill does not call a fine-tune API. It submits a training script as a job. ## Decision guide - Use MCP when an agent in Claude, Cursor, Codex, Gemini, or Grok should call tools. Connect with `podstack agent connect`, then call the tools below. Billable tools need confirm:true only after the human agrees. - Use the CLI when a person or a shell script should install, sign in, or run one command. - Use the Python SDK when Python code should call the API, deploy a function, or stream chat. `pip install podstack` installs podstack 1.8.0 from PyPI: https://pypi.org/project/podstack/1.8.0/ ## CLI command reference This is the v1.2.0 command tree. `podstack --output json` prints JSON (the default when stdout is not a terminal). `podstack --output table` prints a table. `podstack version` and `podstack --version` print the version. `podstack upgrade` installs the latest release, or `--version vX.Y.Z` pins one. Set PODSTACK_DISABLE_UPDATE_CHECK=1 to skip the update nudge. ### Auth - `podstack auth login` opens a browser (Google, GitHub, or SSO) and stores the token. It waits five minutes. - `podstack auth login --key ` stores a key and skips the browser. `podstack auth login --manual` prompts for a pasted key. A non-TTY also prompts. - Create a key at https://podstack.ai/app/api-keys. Keys use the ps_live_ prefix. A legacy psk_ key is still accepted. Other strings warn and are still stored. - PODSTACK_API_KEY overrides the file. PODSTACK_API_BASE overrides the API base. The default base is https://podstack.ai/api/v1. - Credentials file: $XDG_CONFIG_HOME/podstack/credentials.json, or ~/.config/podstack/credentials.json. On Windows that is %USERPROFILE%\.config\podstack\credentials.json when XDG_CONFIG_HOME is unset. Mode 0600. The file holds {"api_key":"..."}. - Agent setup state is agent-setup.json in that same directory. Coding-agent settings are ~/.podstack/config.json and ./.podstack/config.json. Local coding-agent secret names live in ~/.podstack/secrets.json. Never put a key in a client MCP config. - `podstack auth whoami` prints the signed-in account. `podstack auth logout` deletes the credentials file. To rotate a key, create a new one in the console, run login again, then logout on the old machine. `podstack account keys` reports not available: the console manages keys. ### Agent and MCP - `podstack agent connect ` signs in if needed, merges MCP config, writes .podstack.bak beside each file, installs five skills, writes .podstack/AGENTS.md, and checks the handshake. `--all` does every client. `--dry-run` and `--print` print the plan, write nothing, and do not sign in. - `podstack agent disconnect ` restores the backups. `all` and `--all` disconnect every client. `podstack agent status` prints what is connected. `podstack agent welcome` prints the welcome text. - `podstack mcp serve` is the stdio MCP server. `podstack mcp serve --http 127.0.0.1:8765` listens on HTTP. - Skills installed by connect: podstack-provision-gpu, podstack-run-on-gpu, podstack-inference, podstack-fine-tune, podstack-cost-check. The fine-tune skill submits a training script as a job. It does not call a fine-tune API. ### GPUs, jobs, endpoints, functions ``` podstack gpu types list podstack gpu pricing [--gpu-type T] [--region R] [--tier spot|on_demand] podstack gpu templates podstack gpu environments podstack gpu launch [--gpu-type T] [--region R] [--tier spot|on_demand] [--name N] # interactive terminal podstack gpu keys list podstack gpu keys create --name N [--public-key-file PATH] [--force] podstack gpu keys delete podstack gpu instances list [--status S] podstack gpu instances get podstack gpu instances create --type T [--count 1] [--tier on_demand] [--name N] [--region R] [--offering-id ID] [--environment ID] [--template ID] [--disk-gb N] [--ssh-key-id ID] [--max-price N] [--yes | --dry-run] podstack gpu instances delete [id] # with an id this terminates immediately; get approval first podstack gpu instances ssh [id] [-- extra ssh args] [--print] [--no-banner] [--key NAME] [--identity PATH] podstack gpu instances exec -- podstack gpu instances cp [-r] [--key NAME] [--identity PATH] # one side is : podstack gpu instances expose [--local PORT] [--remote-host localhost] [--key NAME] [--identity PATH] podstack gpu instances stop # not available podstack gpu instances start # not available podstack gpu instances logs # not available podstack jobs gpu-types podstack jobs list [--status queued|running|succeeded|failed|cancelled] podstack jobs submit --name N --gpu-type T --script PATH [--image pytorch/pytorch:latest] [--timeout 3600] [--yes | --dry-run] podstack jobs logs podstack jobs cancel --yes podstack endpoints list podstack endpoints create --name N --model M --gpu-type T [--min-replicas 0] [--max-replicas 1] [--yes | --dry-run] podstack endpoints delete --yes podstack functions list # create a function from the Python SDK, not the CLI podstack models list podstack infer chat --model M --prompt TEXT [--system TEXT] ``` `--yes` and `--dry-run` cannot be combined. `jobs submit` and `endpoints create` refuse to spend money without `--yes`. `gpu instances create --dry-run` prints the request and does not launch. `gpu instances delete ` terminates as soon as the id is passed, so ask the human before you run it. `gpu instances exec` and `cp` use the local ssh and scp binaries. They are not an HTTP exec API. Prices and GPU ids come from `gpu pricing` and `gpu types list`. Do not invent a price. ### Projects, account, billing, files, and the coding agent - `podstack projects` and `podstack projects list` list projects. `podstack projects use ` sets the default. `podstack projects create [--description TEXT]` creates one and selects it. The default is saved in ~/.podstack/config.json. PODSTACK_PROJECT_ID overrides it for one run. - `podstack account secrets list` lists project secret names. `podstack account secrets set --name N [--description TEXT] --yes` reads the value from `--value-file` or stdin. Values are write-only and never printed. `podstack account secrets delete --yes` deletes one. - `podstack secrets list`, `podstack secrets set NAME`, and `podstack secrets rm NAME` manage local names in ~/.podstack/secrets.json for the coding agent. Values stay on the machine. - `podstack billing` and `podstack billing balance` call the wallet route. When that route is missing they report not available and point at https://podstack.ai/app/billing. Do not invent a balance. - `podstack init` creates .podstack/PODSTACK.md and .podstack/plans/. `podstack doctor` checks credentials, the API, and local state. - `podstack code` is the local coding agent (macOS and Linux). Flags: `-p` / `--prompt`, `--model`, `--provider` (a model-source alias in the local config, not a key), `--output-format text|json`, `--quiet`, `--allow-tools`, `--dangerously-allow-all`, `--yolo`, `-r` / `--resume`, `-c` / `--continue`, `--max-turns`. `podstack code sessions list` and `podstack code sessions delete ` manage sessions. Exit 0 is success, 1 is an error, 3 is a tool denied, 130 is interrupted. - `podstack send [paths...]` sends files or `--text`. Flags: `--code`, `--zip`, `--no-compress`, `--transfers` (default 4). `podstack receive [--out DIR] [--yes]`. Re-run the same command to resume. - `podstack train` (create, list, get, cancel, events, models) and `podstack files upload` report not available. `podstack sandbox` (run, list, close, renew, logs, cost) reports not available on the current API. Use a GPU instance or a job instead. ## MCP tools `podstack mcp serve` registers these 23 tools. Read-only tools need no confirm. These tools spend money or delete resources and require confirm:true, and only after the human agrees: create_instance, terminate_instance, submit_job, cancel_job, create_endpoint, delete_endpoint. Pass dry_run:true first on create_instance, submit_job, and create_endpoint. dry_run does not send the request and does not estimate a price. Read list_rates for price_per_hour. - list_gpus. Read. Catalogue rows. - list_rates. Read. Optional gpu_type, region, tier (spot or on_demand). - create_instance. confirm. gpu_type or offering_id or template_id. Also gpu_count (default 1), tier, region, name, ssh_key_ids, environment, disk_gb. - list_instances. Read. Optional status. get_instance. Read. id, including the SSH command. - stop_instance and start_instance are registered and always return not available. Terminate, or launch a new instance. - terminate_instance. confirm. Deletes the disk and stops the charge. - exec_command. id and command. Runs over local SSH. The instance is already billed while it exists. upload_file (id, local_path, remote_path) and download_file (id, remote_path, local_path) also use SSH. - list_models. Read. run_inference and chat take model, prompt, and optional system. On the CLI server they spend wallet credit and have no confirm argument, so still ask the human before calling them. chat is an alias of run_inference. - balance. Read. Returns not available when the wallet route is missing. - list_jobs. Read. Optional status. submit_job. confirm. name, gpu_type, script, optional image (default pytorch/pytorch:latest) and timeout_seconds (default 3600). cancel_job. confirm. id. job_logs. Read. id. - list_functions. Read. It does not create a function. list_endpoints. Read. create_endpoint. confirm. name, model, gpu_type, min_replicas (0 scales to zero), max_replicas (default 1). delete_endpoint. confirm. id. An endpoint is billed while replicas exist. ## Python SDK `pip install podstack` installs podstack 1.8.0 from PyPI: https://pypi.org/project/podstack/1.8.0/ Package name podstack. Python >=3.9. Install with `pip install podstack` from https://pypi.org/project/podstack/1.8.0/. Base URL https://podstack.ai/api/v1. Auth order: Podstack(api_key=...), then PODSTACK_API_KEY, then the CLI credentials file. The same ps_live_ and legacy psk_ prefixes apply. Override the base with base_url= or PODSTACK_API_BASE. AsyncPodstack has the same method names. The client repr redacts keys. `python -m podstack.mcp` and the podstack-mcp script serve the same tools. 1.8.0 replaces the older notebook SDK. There is no compatibility shim. - client.me(). client.gpus.list(). client.rates.list(). client.job_gpus.list(). client.templates.list(). client.environments.get(). client.projects.list() and projects.create(name, description). - client.ssh_keys.list(), create(name, public_key), delete(key_id, confirm=True). client.instances.list(status), get, create(..., confirm=True, dry_run=True), terminate(id, confirm=True), ssh_command, exec (local ssh), upload, download. client.operations.get. - client.jobs.list, submit(..., confirm=True), cancel(id, confirm=True), logs. client.endpoints.list, create(..., confirm=True), delete(id, confirm=True). - client.functions.list, get, deploy(..., confirm=True), invoke(..., confirm=True). functions.call and functions.logs raise NotAvailableYet when that route is missing. functions.delete(confirm=True). - client.models.list and models.get. A missing model is NotFound, not NotAvailableYet. client.chat.completions(..., stream=False, confirm=True) and client.chat.stream(..., confirm=True). client.embeddings.create(confirm=True). client.images.generate(confirm=True). - client.wallet.balance and wallet.transactions raise NotAvailableYet on 404. client.secrets.list, create, delete(confirm=True). - The SDK also has fine_tuning.list, get, create, cancel, and events. The platform fine-tune API is not available yet. Do not call it. Submit a training script as a job. - Decorator: @podstack.function(gpu, image="", requirements=, name=, timeout=3600, confirm=False). The function must be top-level in a file. Arguments must be JSON-serializable. deploy(dry_run=True) then deploy(confirm=True). invoke(confirm=True) and ainvoke(confirm=True). local() runs in-process and is free. Calling the function like a normal function raises ConfirmationRequired unless the decorator set confirm=True. logs() may raise NotAvailableYet. delete(confirm=True). - Billable SDK calls that require confirm=True: instance create and terminate, job submit and cancel, endpoint create and delete, chat, embeddings, image generation, function deploy, invoke, and delete, secret delete, and SSH key delete. dry_run=True returns DryRun and sends nothing. Check dry_run before confirm. Do not estimate a price inside a dry run. Read rates.list() price_per_hour. - Errors: PodstackError, AuthenticationError, PermissionDenied, NotFoundError, ValidationError, RateLimitError, InsufficientBalance, GPUNotAvailableError, NotAvailableYet, ConfirmationRequired, CommandFailed. Retries are for connection errors and HTTP 429 and 5xx only. InsufficientBalance means the wallet cannot cover the request. Do not invent a shortfall. ## Examples Each recipe is the prompt a person gives, then the calls, then the result you should expect. Use a gpu_type and an id returned by a list call. Do not invent hardware or a price. Billable steps use dry_run first, then confirm:true or --yes only after the human approves. Matching example pages are not published on the docs site yet. These recipes are the reference, and each recipe will link to its docs page when that page exists. ### Connect and verify Prompt: connect Claude Code to Podstack and show that it works. ``` podstack agent connect claude podstack agent status podstack auth whoami ``` Expected: status shows Claude Code connected, the handshake succeeded, other MCP servers were kept, and a .podstack.bak file sits beside each config. whoami prints the account email. The API key is not in the client config. `podstack agent connect --all` does the same for every supported client. `--dry-run` prints the plan and writes nothing. ### Check GPUs and live prices Prompt: what GPUs can I rent, and what is the live price? ``` MCP: list_gpus MCP: list_rates podstack gpu types list podstack gpu pricing ``` SDK (`pip install podstack`). client.gpus.list() and client.rates.list(). Expected: gpu_type, vram, region, and price_per_hour from the API only. If a field is missing, say so. These calls are read-only. ### Provision, SSH exec, terminate Prompt: launch one GPU, run nvidia-smi, then shut it down. ``` MCP: list_rates MCP: create_instance { gpu_type, gpu_count: 1, dry_run: true } # after the human agrees: MCP: create_instance { gpu_type, gpu_count: 1, confirm: true } MCP: get_instance { id } MCP: exec_command { id, command: "nvidia-smi" } # after the human agrees: MCP: terminate_instance { id, confirm: true } podstack gpu instances create --type --count 1 --dry-run podstack gpu instances create --type --count 1 --yes podstack gpu instances exec -- nvidia-smi podstack gpu instances delete ``` SDK (`pip install podstack`). instances.create(..., dry_run=True) then instances.create(..., confirm=True), instances.exec(id, "nvidia-smi"), instances.terminate(id, confirm=True). Expected: an instance id, then nvidia-smi output over SSH, then the disk deleted and billing stopped. Do not call stop_instance or start_instance. exec uses local SSH, not an HTTP exec API. ### Submit a job, read logs, cancel Prompt: run this script on a GPU, show the logs, and cancel it if I say so. ``` podstack jobs gpu-types podstack jobs submit --name train --gpu-type --script ./train.py --dry-run # after the human agrees: podstack jobs submit --name train --gpu-type --script ./train.py --yes podstack jobs logs # after the human agrees: podstack jobs cancel --yes ``` MCP: submit_job with dry_run:true, then confirm:true after approval. job_logs is read-only. cancel_job needs confirm:true after approval. SDK (`pip install podstack`). jobs.submit(..., dry_run=True), then jobs.submit(..., confirm=True), jobs.logs(id), jobs.cancel(id, confirm=True). Expected: a job id, log text, and a cancelled job. There is no fine-tune API. A training script is a job. ### Deploy and invoke a function Prompt: deploy this function and call it once. The CLI only lists functions: `podstack functions list`. Creating one is the SDK. SDK (`pip install podstack`). ``` import podstack @podstack.function(gpu=gpu_type, requirements=["torch"]) def hello(): return "ok" hello.deploy(dry_run=True) # after the human agrees: hello.deploy(confirm=True) hello.invoke(confirm=True) ``` Expected: a dry-run body, then a deployed function, then the return value. hello.logs() may raise NotAvailableYet. The function must live in a file. Do not call it like a normal function unless the decorator set confirm=True. ### Create an endpoint and chat Prompt: stand up an endpoint and send one chat message, then remove it. ``` MCP: create_endpoint { name, model, gpu_type, dry_run: true } # after the human agrees: MCP: create_endpoint { name, model, gpu_type, confirm: true } # run_inference and chat spend credit and have no confirm argument on the CLI server. # Ask the human, then: MCP: chat { model, prompt } podstack infer chat --model --prompt "hello" # after the human agrees: MCP: delete_endpoint { id, confirm: true } ``` SDK (`pip install podstack`). chat.completions(model=..., messages=[...], confirm=True) and chat.stream(..., confirm=True). endpoints.create(..., dry_run=True) then confirm=True, then endpoints.delete(id, confirm=True). Expected: an endpoint id, one completion, then the endpoint deleted. min_replicas 0 scales to zero. The endpoint is billed while replicas exist. ### Tool calling Prompt: give this chat model the Podstack tools. SDK (`pip install podstack`). schemas = podstack.tools(). Use schemas["openai"], schemas["anthropic"], or schemas["mcp"]. Names match the CLI, including stop_instance and start_instance, which report not available. Do not rename tools. In the SDK, run_inference and chat also require confirm=true. On the CLI MCP server those two spend credit with no confirm argument, so still ask the human first. ### Wallet and cost Prompt: what does this cost, and can the wallet cover it? ``` MCP: list_rates MCP: balance podstack billing ``` SDK (`pip install podstack`). client.rates.list() and client.wallet.balance(). Expected: price_per_hour from the API. If balance returns not available, or wallet.balance raises NotAvailableYet, say the wallet route is missing and send the human to https://podstack.ai/app/billing. Do not invent a balance. The podstack-cost-check skill reads rates before a spend. ### Cleanup Prompt: stop everything I started and disconnect the agent. ``` MCP: list_instances MCP: list_jobs MCP: list_endpoints # after the human agrees, for each id: MCP: terminate_instance { id, confirm: true } MCP: cancel_job { id, confirm: true } MCP: delete_endpoint { id, confirm: true } podstack gpu instances delete podstack jobs cancel --yes podstack endpoints delete --yes podstack agent disconnect claude ``` SDK (`pip install podstack`). instances.terminate, jobs.cancel, and endpoints.delete, each with confirm=True after approval. A function is removed with delete(confirm=True). Expected: each resource gone, billing stopped, and disconnect restores the .podstack.bak configs. There is no stop that keeps the disk. ## Not available yet - Instance stop and start that keep the disk. `podstack gpu instances stop` and `start`, and the stop_instance and start_instance tools, report not available. Terminating the instance is the supported way to stop billing. - An instance logs HTTP API and an instance exec HTTP API. `podstack gpu instances logs` reports not available. `podstack gpu instances exec` and exec_command use local SSH. Job logs (`podstack jobs logs` and job_logs) are a separate read. - Dataset upload. `podstack files` and `podstack files upload` report not available. - A fine-tune API. `podstack train` reports not available. Run a training script as a job. Do not call the SDK fine_tuning methods. - Wallet GET is not proven. `podstack billing` and the balance tool return not available when the route is missing. Do not invent a balance. The console page is https://podstack.ai/app/billing. Agent guide: https://podstack.ai/agents --- # Practical guides for builders 56 hands-on articles on training, agents, RAG and inference. - [A customer-support agent grounded in your docs](https://podstack.ai/blog/a-customer-support-agent-grounded-in-your-docs.md) (2026-11-20) - [Agent memory: short-term, long-term and vector stores](https://podstack.ai/blog/agent-memory-short-term-long-term-and-vector-stores.md) (2026-11-17) - [Batch jobs: processing a million images overnight](https://podstack.ai/blog/batch-jobs-processing-a-million-images-overnight.md) (2026-11-14) - [Batching and KV-cache: how LLM serving really works](https://podstack.ai/blog/batching-and-kv-cache-how-llm-serving-really-works.md) (2026-11-11) - [Browser-automation agents for repetitive web tasks](https://podstack.ai/blog/browser-automation-agents-for-repetitive-web-tasks.md) (2026-11-08) - [Building a coding agent that runs tests in a sandbox](https://podstack.ai/blog/building-a-coding-agent-that-runs-tests-in-a-sandbox.md) (2026-11-05) - [Building a RAG chatbot over company knowledge](https://podstack.ai/blog/building-a-rag-chatbot-over-company-knowledge.md) (2026-11-02) - [Building a speech-to-text transcription service](https://podstack.ai/blog/building-a-speech-to-text-transcription-service.md) (2026-10-30) - [Building a text-to-image pipeline with ComfyUI on cloud GPUs](https://podstack.ai/blog/building-a-text-to-image-pipeline-with-comfyui-on-cloud-gpus.md) (2026-10-27) - [Building an AI code-review bot for your repos](https://podstack.ai/blog/building-an-ai-code-review-bot-for-your-repos.md) (2026-10-24) - [Building your first AI agent with tool calling](https://podstack.ai/blog/building-your-first-ai-agent-with-tool-calling.md) (2026-10-21) - [Checkpointing long training runs so you never lose progress](https://podstack.ai/blog/checkpointing-long-training-runs-so-you-never-lose-progress.md) (2026-10-18) - [Choosing context length vs cost for production LLMs](https://podstack.ai/blog/choosing-context-length-vs-cost-for-production-llms.md) (2026-10-15) - [Choosing the right GPU for training: A100 vs H100 vs H200 vs B200](https://podstack.ai/blog/choosing-the-right-gpu-for-training-a100-vs-h100-vs-h200-vs-b200.md) (2026-10-12) - [Chunking strategies that actually improve RAG answers](https://podstack.ai/blog/chunking-strategies-that-actually-improve-rag-answers.md) (2026-10-09) - [Cleaning and deduplicating web-scale text datasets](https://podstack.ai/blog/cleaning-and-deduplicating-web-scale-text-datasets.md) (2026-10-06) - [Connecting AI agents to cloud GPUs with MCP](https://podstack.ai/blog/connecting-ai-agents-to-cloud-gpus-with-mcp.md) (2026-10-03) - [Cost-optimizing an AI startup's GPU bill](https://podstack.ai/blog/cost-optimizing-an-ai-startup-s-gpu-bill.md) (2026-09-30) - [Designing reliable multi-step agents with planning loops](https://podstack.ai/blog/designing-reliable-multi-step-agents-with-planning-loops.md) (2026-09-27) - [Direct Preference Optimization (DPO) in practice](https://podstack.ai/blog/direct-preference-optimization-dpo-in-practice.md) (2026-09-24) - [Distributed data parallel training across 8 GPUs](https://podstack.ai/blog/distributed-data-parallel-training-across-8-gpus.md) (2026-09-21) - [Evaluating agents: success rates, cost and latency](https://podstack.ai/blog/evaluating-agents-success-rates-cost-and-latency.md) (2026-09-18) - [Fine-tuning a small model to replace an expensive API](https://podstack.ai/blog/fine-tuning-a-small-model-to-replace-an-expensive-api.md) (2026-09-15) - [Fine-tuning a vision-language model for document understanding](https://podstack.ai/blog/fine-tuning-a-vision-language-model-for-document-understanding.md) (2026-09-12) - [Fine-tuning Llama with LoRA on a single H100](https://podstack.ai/blog/fine-tuning-llama-with-lora-on-a-single-h100.md) (2026-09-09) - [Fine-tuning SDXL for consistent brand illustrations](https://podstack.ai/blog/fine-tuning-sdxl-for-consistent-brand-illustrations.md) (2026-09-06) - [Fine-tuning Whisper for accented speech recognition](https://podstack.ai/blog/fine-tuning-whisper-for-accented-speech-recognition.md) (2026-09-03) - [Fractional GPUs: when a slice is all you need](https://podstack.ai/blog/fractional-gpus-when-a-slice-is-all-you-need.md) (2026-08-31) - [From notebook to production: an MLOps checklist](https://podstack.ai/blog/from-notebook-to-production-an-mlops-checklist.md) (2026-08-28) - [Full-parameter fine-tuning with DeepSpeed ZeRO-3](https://podstack.ai/blog/full-parameter-fine-tuning-with-deepspeed-zero-3.md) (2026-08-25) - [Generating synthetic training data with LLMs](https://podstack.ai/blog/generating-synthetic-training-data-with-llms.md) (2026-08-22) - [GPU functions in Python: serverless ML in five lines](https://podstack.ai/blog/gpu-functions-in-python-serverless-ml-in-five-lines.md) (2026-08-19) - [Hybrid search: combining BM25 and embeddings](https://podstack.ai/blog/hybrid-search-combining-bm25-and-embeddings.md) (2026-08-16) - [Keeping secrets and API keys safe in ML pipelines](https://podstack.ai/blog/keeping-secrets-and-api-keys-safe-in-ml-pipelines.md) (2026-08-13) - [Mixed precision training explained: FP16, BF16 and FP8](https://podstack.ai/blog/mixed-precision-training-explained-fp16-bf16-and-fp8.md) (2026-08-10) - [Monitoring GPU utilization and spotting bottlenecks](https://podstack.ai/blog/monitoring-gpu-utilization-and-spotting-bottlenecks.md) (2026-08-07) - [Multi-agent systems: supervisor and worker patterns](https://podstack.ai/blog/multi-agent-systems-supervisor-and-worker-patterns.md) (2026-08-04) - [Preparing instruction datasets for supervised fine-tuning](https://podstack.ai/blog/preparing-instruction-datasets-for-supervised-fine-tuning.md) (2026-08-01) - [QLoRA on a budget: fine-tune a 70B model on one GPU](https://podstack.ai/blog/qlora-on-a-budget-fine-tune-a-70b-model-on-one-gpu.md) (2026-07-29) - [Quantization for inference: GPTQ, AWQ and GGUF compared](https://podstack.ai/blog/quantization-for-inference-gptq-awq-and-gguf-compared.md) (2026-07-26) - [Reranking retrieved passages for better accuracy](https://podstack.ai/blog/reranking-retrieved-passages-for-better-accuracy.md) (2026-07-23) - [Reserved GPU clusters for large training runs](https://podstack.ai/blog/reserved-gpu-clusters-for-large-training-runs.md) (2026-07-20) - [RLHF vs DPO vs ORPO: which alignment method to use](https://podstack.ai/blog/rlhf-vs-dpo-vs-orpo-which-alignment-method-to-use.md) (2026-07-17) - [Running Jupyter on a GPU for data science experiments](https://podstack.ai/blog/running-jupyter-on-a-gpu-for-data-science-experiments.md) (2026-07-14) - [Scale-to-zero inference endpoints: cutting idle cost](https://podstack.ai/blog/scale-to-zero-inference-endpoints-cutting-idle-cost.md) (2026-07-11) - [Self-hosting an embedding model for private search](https://podstack.ai/blog/self-hosting-an-embedding-model-for-private-search.md) (2026-07-08) - [Serving LLMs with vLLM: throughput tuning guide](https://podstack.ai/blog/serving-llms-with-vllm-throughput-tuning-guide.md) (2026-07-05) - [Speculative decoding for 2x faster generation](https://podstack.ai/blog/speculative-decoding-for-2x-faster-generation.md) (2026-07-02) - [Spot vs on-demand GPUs: saving money safely](https://podstack.ai/blog/spot-vs-on-demand-gpus-saving-money-safely.md) (2026-06-29) - [Structured JSON output from open models](https://podstack.ai/blog/structured-json-output-from-open-models.md) (2026-06-26) - [Text-to-speech voices for apps and games](https://podstack.ai/blog/text-to-speech-voices-for-apps-and-games.md) (2026-06-23) - [Time-series forecasting with transformers on GPUs](https://podstack.ai/blog/time-series-forecasting-with-transformers-on-gpus.md) (2026-06-20) - [Train a YOLO object detector for warehouse inventory](https://podstack.ai/blog/train-a-yolo-object-detector-for-warehouse-inventory.md) (2026-06-17) - [Training a custom tokenizer for a domain language model](https://podstack.ai/blog/training-a-custom-tokenizer-for-a-domain-language-model.md) (2026-06-14) - [Training a Stable Diffusion LoRA on your product photos](https://podstack.ai/blog/training-a-stable-diffusion-lora-on-your-product-photos.md) (2026-06-11) - [Video generation models: what's possible today](https://podstack.ai/blog/video-generation-models-what-s-possible-today.md) (2026-06-08) --- # Terms of Service Last updated: November 26, 2026 · Effective: January 31, 2026 ## 1. Acceptance of Terms Welcome to Podstack. These Terms of Service ("Terms") govern your access to and use of the Podstack platform, including our website at **podstack.ai**, GPU cloud computing services, APIs, and related services (collectively, the "Services"). By creating an account, accessing, or using our Services, you agree to be bound by these Terms. If you are using the Services on behalf of an organization, you represent and warrant that you have the authority to bind that organization to these Terms. **Important:** If you do not agree to these Terms, you may not access or use our Services. ## 2. Description of Services Podstack provides cloud-based GPU computing infrastructure and related services, including: - **GPU Cloud:** On-demand NVIDIA GPUs. An instance is billed for the time it runs, pro-rated by the second from the hourly rate, from boot until you terminate it. Extra disk is billed per GB-hour. An optional dedicated IP is billed from the cost recorded for that address, which covers its hourly fee and data transfer on that IP. An optional priority bid on a watch rule is charged per GPU-hour on top. - **Jobs:** A script on a GPU, billed only for the time the job runs. - **Inference:** An OpenAI-compatible API at https://podstack.ai/api/v1. Keys use the prefix ps_live_. Chat and embeddings are billed per token, including cached input tokens. Images are billed per image and per megapixel. A video is charged when it completes, at the per-second or per-clip price shown for that model. - **Endpoints and Functions:** Dedicated GPU machines for serving models or calling a Python function, billed for the time the machine exists. - **Deploy:** One-click apps, including JupyterLab, ComfyUI, and vLLM, on a GPU Cloud instance. - **Reserved clusters and teams:** Capacity reserved for an organization, and projects that share one wallet. We reserve the right to modify, suspend, or discontinue any aspect of the Services at any time, with reasonable notice when practicable. ## 3. Account Registration ### 3.1 Eligibility You must be at least 18 years old and have the legal capacity to enter into binding contracts to use our Services. ### 3.2 Account Information You agree to provide accurate, current, and complete information during registration and to update such information to keep it accurate, current, and complete. ### 3.3 Account Security - You are responsible for all activities that occur under your account. - You must immediately notify us of any unauthorized use of your account. - Sign-in is through Google, Microsoft, or GitHub. Protect that account with the sign-in provider's own multi-factor authentication. This service does not have a separate MFA setting. - You may not share your account credentials with third parties. ## 4. Acceptable Use Policy You agree to use the Services only for lawful purposes and in accordance with these Terms. You may NOT use our Services to: - Violate any applicable laws, regulations, or third-party rights. - Engage in cryptocurrency mining of any kind, or run blockchain, validator, staking, or other crypto network nodes. - Distribute malware, viruses, or other harmful code. - Conduct distributed denial-of-service (DDoS) attacks or network scanning. - Send spam, phishing emails, or fraudulent communications. - Generate, train, or distribute content involving child sexual abuse material (CSAM). - Train AI models for autonomous weapons or mass surveillance systems. - Circumvent security measures, access controls, or usage limits. - Reverse engineer, decompile, or attempt to extract source code from our Services. - Resell or redistribute the Services without authorization. **Violation Consequences:** Violation of the Acceptable Use Policy may result in immediate suspension or termination of your account without refund, and may be reported to law enforcement authorities. **Zero-Tolerance - Crypto Mining & Nodes:** Cryptocurrency mining and the operation of blockchain, validator, staking, or other crypto network nodes are strictly prohibited. Any such use will result in **permanent banning** of your account from the platform, with no refunds. ## 5. Payment and Billing ### 5.1 Pricing The wallet is stored in US cents. Visitors in India see prices in Indian Rupees (INR). Everyone else sees US Dollars (USD). A signed-in user can set a location in Settings, and the display currency follows that location. An INR payment is converted into US cents at the platform USD to INR rate: the amount in paise is divided by that rate and rounded down to the cent. Pricing is subject to change with 30 days' notice for existing customers. ### 5.2 Billing - **Prepaid wallet:** You add credit before you use the Services. The balance is stored in US cents and shared by everyone in the project. There is no monthly or annual subscription. - **First top-up bonus:** The first time a project is credited at least US $5.00 from a top-up, the wallet also receives US $5.00, once. The bonus is a fixed US $5.00, not a percentage of the top-up, and a larger top-up does not increase it. It does not expire. It is not added for a refund, for credit moved from another project, or for a migration credit. Two qualifying top-ups at the same time still add it only once. Checkout shows the US $5.00 and the US $10.00 total (the top-up plus the bonus) in the currency charged, at the rate shown there: INR when the connection or the location saved in Settings is India, and USD otherwise. An INR top-up qualifies only when the paise paid, divided by that rate and rounded down, come to at least 500 US cents. Bonus and other promotional credits are non-refundable, are not transferable to another person, and have no cash value. They are added to the same project wallet as paid credits. Deleting a project moves the remaining wallet balance to the owner's personal project and does not grant the bonus again. - **GPU instances:** Billed for the time they run, pro-rated by the second from the hourly rate, from boot until you terminate them. Extra disk is billed per GB-hour. An optional dedicated IP is billed from the cost recorded for that address, which covers its hourly fee and data transfer on that IP. An optional priority bid is charged per GPU-hour on top for the time the instance runs. - **Jobs:** Billed for the time the job runs. - **Endpoints and Functions:** Billed for the time the machine exists. - **Inference:** Chat and embeddings are billed per token (input, output, and cached input). Images are billed per image and per megapixel. A video is charged when it completes, at the per-second or per-clip price shown for that model. ### 5.3 Payment Methods Wallet top-ups are taken by Razorpay. The checkout accepts credit cards, debit cards, UPI, and net banking. The charge is in the currency shown at checkout: INR when the connection, or the location saved in Settings, is India, and USD otherwise. The smallest top-up is US $5 or ₹500. Wire transfer is not a checkout method. ### 5.4 Taxes All prices are exclusive of applicable taxes (GST, VAT, etc.) unless otherwise stated. You are responsible for paying all taxes associated with your use of the Services. ### 5.5 Refunds & Cancellation Prepaid wallet credits are non-refundable except as required by law, in cases of service defects, or as set out in the Refund & Cancellation Policy. The one-time first top-up bonus and other promotional credits are non-refundable, are not transferable to another person, and have no cash value. There is no subscription billing cycle to prorate. Eligible refunds of a paid top-up are credited back to the original Razorpay payment method within **5-7 business days**. You stop a GPU instance or a job by terminating it in the console. Charges for that resource stop when it stops. There is no billing period that keeps it running until the end of a month. For full details, see our [Refund & Cancellation Policy](/refund-policy). ## 6. Service Level Agreement (SLA) ### 6.1 Uptime Commitment We target 99.9% monthly uptime for our core GPU compute and API services. This excludes scheduled maintenance (announced 48 hours in advance) and events beyond our reasonable control. ### 6.2 Service Credits | Monthly Uptime | Service Credit | | --- | --- | | ≥ 99.9% | No credit | | 99.0% - 99.9% | 10% of monthly bill | | 95.0% - 99.0% | 25% of monthly bill | | < 95.0% | 50% of monthly bill | ### 6.3 Claiming Credits To claim service credits, submit a request to support@podstack.ai within 30 days of the incident. Credits are applied to future invoices and cannot be exchanged for cash. ## 7. Intellectual Property The Services, including all software, interfaces, documentation, logos, and trademarks, are owned by Podstack and protected by intellectual property laws. These Terms grant you a limited, non-exclusive, non-transferable license to use the Services. You retain all intellectual property rights in your content, including models, datasets, and code that you upload or create using our Services. We claim no ownership over your intellectual property. If you provide feedback, suggestions, or ideas about the Services, you grant us a royalty-free, worldwide, perpetual license to use, modify, and incorporate such feedback into our Services. ## 8. User Content and Data You are solely responsible for all data, code, models, and other content that you upload, store, or process using our Services ("User Content"). You represent that you have all necessary rights to use such content. - We process User Content solely to provide the Services to you. - We do not access, use, or share User Content except as necessary for service delivery. - We do not use your data to train our own AI models without explicit consent. Upon account termination or your request, we will delete your User Content within 30 days, except where retention is required by law or for legitimate business purposes. ## 9. Confidentiality Both parties agree to maintain the confidentiality of any non-public information disclosed during the use of Services, including technical documentation, API specifications, pricing, business plans, and User Content. This confidentiality obligation survives termination of these Terms for a period of three (3) years. ## 10. Limitation of Liability THE SERVICES ARE PROVIDED "AS IS" AND "AS AVAILABLE" WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. TO THE MAXIMUM EXTENT PERMITTED BY LAW, PODSTACK SHALL NOT BE LIABLE FOR INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR PUNITIVE DAMAGES, LOSS OF PROFITS, REVENUE, DATA, OR BUSINESS OPPORTUNITIES, OR SERVICE INTERRUPTIONS BEYOND OUR REASONABLE CONTROL. Our total cumulative liability for any claims arising from or related to these Terms shall not exceed the greater of: (a) the fees paid by you in the twelve (12) months preceding the claim, or (b) INR 50,000. ## 11. Indemnification You agree to indemnify, defend, and hold harmless Podstack, its officers, directors, employees, and agents from any claims, liabilities, damages, losses, or expenses (including reasonable legal fees) arising from: - Your use of the Services. - Your violation of these Terms. - Your User Content or intellectual property infringement. - Your violation of any applicable laws or third-party rights. ## 12. Termination ### 12.1 Termination by You You may terminate your account at any time through the account settings or by contacting support. You remain responsible for any outstanding charges. ### 12.2 Termination by Us We may suspend or terminate your account if you violate these Terms or the Acceptable Use Policy, your account has been inactive for 12+ months, we are required to do so by law, or we discontinue the Services. ### 12.3 Effect of Termination Upon termination, your right to access the Services ceases immediately. You may request a copy of your data within 30 days of termination. Sections that by their nature should survive (including Confidentiality, Limitation of Liability, Indemnification) will survive termination. ## 13. Dispute Resolution These Terms are governed by and construed in accordance with the laws of India, without regard to conflict of law principles. Before initiating formal proceedings, both parties agree to attempt good-faith negotiations for at least 30 days by contacting legal@podstack.ai. Any disputes that cannot be resolved informally shall be settled by binding arbitration under the Arbitration and Conciliation Act, 1996. The seat of arbitration shall be Bangalore, Karnataka, India. The language of arbitration shall be English. For claims not subject to arbitration, the courts of Bangalore, Karnataka, India shall have exclusive jurisdiction. ## 14. General Provisions - **Entire Agreement:** These Terms, together with our Privacy Policy, constitute the entire agreement between you and Podstack regarding the Services. - **Modifications:** We may modify these Terms from time to time. Material changes will be communicated via email or prominent notice on our website at least 30 days in advance. - **Severability:** If any provision of these Terms is found invalid or unenforceable, the remaining provisions will continue in full force and effect. - **Assignment:** You may not assign or transfer these Terms without our prior written consent. We may assign our rights and obligations without restriction. - **No Waiver:** Failure to enforce any right or provision of these Terms does not constitute a waiver of that right or provision. - **Force Majeure:** Neither party shall be liable for delays or failures in performance resulting from events beyond reasonable control. ## 15. Contact Information ### General Inquiries Email: hello@podstack.ai ### Support Email: support@podstack.ai ### Legal Email: legal@podstack.ai ### Billing Email: billing@podstack.ai **Razordynamics Private Limited** (operating as Podstack) Address: 11th Floor, Prestige Tech Park, Platina 2, Outer Ring Rd, Kadubeesanahalli, Bengaluru, Karnataka India- 560087 --- # Privacy Policy Last updated: November 27, 2026 · Effective: January 31, 2026 ## 1. Introduction Welcome to Podstack. We are committed to protecting your personal data and respecting your privacy. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you visit our website **podstack.ai** and use our GPU cloud computing services (collectively, the "Services"). This Privacy Policy is designed to comply with GDPR (EU), DPDP (India), ePrivacy Directive, and the Indian Information Technology Act, 2000. By accessing or using our Services, you acknowledge that you have read, understood, and agree to be bound by this Privacy Policy. ## 2. Data Controller For the purposes of the GDPR and DPDP, the data controller responsible for your personal data is: Razordynamics Private Limited (operating as Podstack) Address: 11th Floor, Prestige Tech Park, Platina 2, Outer Ring Rd, Kadubeesanahalli, Bengaluru, Karnataka India- 560087 Email: privacy@podstack.ai Data Protection Officer: dpo@podstack.ai ## 3. Information We Collect ### 3.1 Information You Provide Directly - **Account Information:** Name, email address, phone number, password, and organization name. - **Billing Information:** Payment card details, billing address, GST/VAT identification numbers, and transaction history. - **Communications:** Information you provide when contacting our support team. - **User Content:** Data, files, code, models, and other content you upload, store, or process using our Services. - **Builder Credit Applications:** Project descriptions and optional GitHub/Colab/LinkedIn links to verify legitimate ML use. ### 3.2 Information Collected Automatically - **Device Information:** IP address, browser type, operating system, device identifiers, and hardware configuration. - **Usage Data:** Pages visited, features used, click patterns, session duration, and interactions. - **Log Data:** Server logs, error reports, and system activity logs. - **Location Data:** Approximate geographic location based on IP address. - **Cookies and Similar Technologies:** Information collected through cookies and similar tracking technologies. ### 3.3 Information from Third Parties - **Authentication Providers:** Basic profile information from Google, Microsoft, and GitHub. - **Payment Processors:** Transaction confirmations from Razorpay. ## 4. How We Use Your Information - Provide, maintain, and improve our GPU cloud computing services. - Process your transactions and manage your account. - Allocate computing resources and manage infrastructure. - Provide technical support and respond to inquiries. - Send service-related notifications and marketing communications (with your consent). - Analyze usage patterns to improve our Services. - Detect, prevent, and address technical issues, fraud, and security threats — including crypto-mining abuse. - Enforce our Terms of Service and acceptable use policies. - Comply with legal obligations and respond to lawful requests. ## 5. Legal Basis for Processing (GDPR) | Legal Basis | Processing Activities | | --- | --- | | Contract Performance | Account creation, service delivery, billing, technical support | | Consent | Marketing communications, non-essential cookies, analytics | | Legitimate Interests | Fraud prevention, security monitoring, service improvement, business analytics | | Legal Obligation | Tax compliance, responding to legal requests, data retention requirements | ## 6. Data Retention | Data Category | Retention Period | | --- | --- | | Account Information | Duration of account + 3 years after deletion | | Billing & Transaction Records | 7 years (tax/legal compliance) | | User Content & Data | Until you delete it or account termination + 30 days | | Usage Logs | 90 days (rolling) | | Support Communications | 3 years from resolution | | Marketing Consent Records | Until withdrawal + 3 years | | Cookie Consent Records | 7 years (GDPR compliance audit trail) | ## 7. Your Rights Under GDPR ### Right of Access (Art. 15) Request a copy of the personal data we hold about you. ### Right to Rectification (Art. 16) Request correction of inaccurate or incomplete personal data. ### Right to Erasure (Art. 17) Request deletion of your personal data ("Right to be Forgotten"). ### Right to Restriction (Art. 18) Request restriction of processing of your personal data. ### Right to Data Portability (Art. 20) Receive your data in a structured, machine-readable format. ### Right to Object (Art. 21) Object to processing based on legitimate interests or for direct marketing. ### Rights Related to Automated Decision-Making (Art. 22) Not be subject to decisions based solely on automated processing. ### Right to Withdraw Consent (Art. 7) Withdraw consent at any time where processing is based on consent. ## 8. Your Rights Under DPDP (India) ### Right to Access Information Obtain a summary of your personal data and processing activities. ### Right to Correction and Erasure Request correction of inaccurate data and erasure of data no longer necessary. ### Right to Grievance Redressal Have your grievances addressed by our designated Grievance Officer. ### Right to Nominate Nominate another person to exercise your rights in case of death or incapacity. ### Grievance Officer (India) Name: Grievance Officer, Podstack Email: grievance@podstack.aiResponse Time: Within 30 days of receipt of complaint ## 9. International Data Transfers Your personal data may be transferred to and processed in countries other than your country of residence. When we transfer personal data from the EEA or UK to countries not deemed adequate by the European Commission, we use Standard Contractual Clauses (SCCs), Binding Corporate Rules, or adequacy decisions. Cross-border transfers of personal data from India are conducted in compliance with the DPDP Act and any rules notified by the Central Government regarding permitted jurisdictions. ## 10. Cookies and Tracking Technologies ### 10.1 Types of Cookies We Use | Category | Purpose | Consent Required | | --- | --- | --- | | Essential | Sign-in session, the short-lived cookie used during Google, Microsoft, or GitHub sign-in, and security | No | | Functional | Remembers whether the console sidebar is open | No | | Analytics | Google Analytics 4 first-party cookies (_ga, _ga_*) measure site usage. No advertising cookies. | No | ### 10.2 Managing Cookies - The site does not show a cookie consent banner and has no Cookie Settings page. - We use Google Analytics 4 first-party analytics cookies (_ga, _ga_*) to measure site usage. We do not set advertising cookies. - To opt out, block or delete cookies in your browser settings, or install the Google Analytics opt-out add-on (https://tools.google.com/dlpage/gaoptout). - Blocking the sign-in cookie keeps you signed out. ## 11. Third-Party Services | Category | Purpose | | --- | --- | | Cloud Infrastructure Providers | Hosting and compute resources | | Payment Processors (Razorpay) | Secure payment processing | | Email | Email delivery through the mail server configured for the service | | Authentication Providers | OAuth login (Google, Microsoft, GitHub) | | Google Analytics 4 | Measures site usage with first-party analytics cookies (_ga, _ga_*). No advertising cookies. | ## 12. Data Security - **Certifications:** Podstack holds ISO/IEC 27001, ISO/IEC 27017, ISO/IEC 27018, and ISO/IEC 42001. It is SOC 2 Type 1 compliant and CSA STAR Level 1. Its security audit is a CERT-In empanelled VAPT. Personal data handling is aligned with the DPDP Act 2023 and the GDPR. Data processing agreements and the sub-processor list are available on request. Certificate numbers, auditor names, and audit dates are not published here. - **Encryption:** TLS 1.3 for data in transit; AES-256 for data at rest. - **Access Controls:** Role-based access on each project: owner, admin, member, and viewer. Viewers are read-only. - **Infrastructure Security:** Firewalls, intrusion detection, regular security audits. - **Data Isolation:** Logical separation of customer data. - **Monitoring:** 24/7 security monitoring and incident response. - **Employee Training:** Regular security and privacy awareness training. ## 13. Children's Privacy Our Services are not directed to individuals under the age of 18. We do not knowingly collect personal data from children. If you are a parent or guardian and believe your child has provided us with personal data, please contact us at privacy@podstack.ai, and we will take steps to delete such information. ## 14. Changes to This Policy ## 15. Contact Us ### General Privacy Inquiries Email: privacy@podstack.ai ### Data Protection Officer (GDPR) Email: dpo@podstack.ai ### Grievance Officer (India DPDP) Email: grievance@podstack.ai ### Data Subject Requests Email: dsr@podstack.ai **EU Representative:** For users in the European Union, you may also contact our EU representative at eu-rep@podstack.ai --- # Refund & Cancellation Policy Last updated: November 26, 2026 · Effective: April 7, 2026 ## 1. Overview This Refund & Cancellation Policy outlines the terms and conditions under which **Podstack** provides refunds and handles cancellations for our GPU cloud computing services and related products. We strive to ensure customer satisfaction with our services. If you are not satisfied with your purchase or encounter any issues, please review this policy and contact our billing team for assistance. ## 2. Refund Eligibility ### 2.1 Prepaid Credits - Unused prepaid credits may be eligible for a refund if the refund request is made within **7 days** of purchase. - Partially used credit balances may be refunded on a prorated basis at our discretion. - The one-time first top-up bonus and other promotional credits are not eligible for a refund. They are not transferable to another person and have no cash value. The bonus is US $5.00 of wallet credit, added once per project when a top-up credits at least US $5.00. See the Terms of Service for how checkout shows it and when an INR top-up qualifies. ### 2.2 Billing Errors - If you are charged incorrectly due to a system or billing error, a full refund of the erroneous amount will be processed. - Duplicate payments will be refunded in full. - Overcharges due to metering errors will be corrected and refunded. ### 2.3 Service Outages Extended service outages exceeding the SLA commitments may qualify for service credits or refunds as outlined in our [Terms of Service](/terms). ## 3. Non-Refundable Items The following charges and services are **not eligible** for refund: - **Consumed use:** GPU time already run, billed per second from the hourly rate; extra disk already used, billed per GB-hour; a dedicated IP already charged, including data transfer on that IP; a priority bid for time already run; job time already run; endpoint and function machine time already run; tokens, images, and megapixels already served; and a video that has completed. - **Promotional credits:** The one-time first top-up bonus and any other promotional credit. These are non-refundable, are not transferable to another person, and have no cash value. **Important:** Once GPU compute resources have been allocated and used, those charges cannot be reversed. We recommend monitoring your usage through the dashboard to avoid unexpected charges. ## 4. Refund Process To request a refund, follow these steps: 1. **Submit a request:** Email billing@podstack.ai with the subject line "Refund Request - [Your Account ID]". 2. **Include details:** Provide your account email, the Razorpay payment or order ID, the amount in question, and the reason for the refund request. 3. **Acknowledgement:** Our billing team will acknowledge your request within **2 business days**. 4. **Review:** We will review your request and verify eligibility within **3-5 business days**. 5. **Resolution:** You will be notified of the outcome via email. If approved, the refund will be initiated immediately. ### 4.1 Refund Method Approved refunds will be credited back to the **original payment method** used for the transaction: - **Credit/Debit cards:** Refund to the original card through Razorpay. - **UPI:** Refund to the original UPI ID through Razorpay. - **Net Banking:** Refund to the original bank account through Razorpay. ## 5. Refund Timeline Once a refund is approved, the processing time depends on the payment method: | Payment Method | Processing Time | | --- | --- | | Credit/Debit Card | 5-7 business days | | UPI | 3-5 business days | | Net Banking | 5-7 business days | Please note that additional processing time may be required by your bank or financial institution. If you have not received your refund within the stated timeline, please contact your bank first, then reach out to us at billing@podstack.ai. ## 6. Cancellation of Services ### 6.1 How to Cancel There is no subscription to cancel. You stop charges by terminating the resource, and you can close use of the account in any of these ways: - **Dashboard:** Sign in and open Billing. Wallet credits are prepaid. Terminate running instances and jobs from the console. - **Email:** Send a cancellation request to billing@podstack.ai from your registered email address. - **Support:** Contact our support team at support@podstack.ai. ### 6.2 Effect of Cancellation - There is no billing period. A GPU instance or job keeps running, and keeps drawing on the wallet, until you terminate it or the wallet can no longer cover it. - Terminating an instance or job in the console stops further charges for that resource. It does not wait until the end of a month. - Your data will be retained for **30 days** after cancellation, during which you can export your data. - After 30 days, all data associated with your account will be permanently deleted. - Any remaining prepaid credits will be forfeited unless a refund is requested within the eligible period. ### 6.3 Immediate Termination Terminate a running instance or job in the console to stop it immediately, or contact billing@podstack.ai. Stopping a resource does not automatically qualify for a prorated refund of use that has already been billed. **Warning:** Cancellation and data deletion are irreversible. Please ensure you have exported all necessary data before your account is permanently deleted. ## 7. Contact for Refunds For any questions or concerns regarding refunds and cancellations, please contact us: ### Billing & Refunds Email: billing@podstack.ai ### General Support Email: support@podstack.ai **Razordynamics Private Limited** (operating as Podstack) Address: 11th Floor, Prestige Tech Park, Platina 2, Outer Ring Rd, Kadubeesanahalli, Bengaluru, Karnataka India- 560087 --- # H100 on-demand rates These are the H100 offers in the current catalogue. GPU instances are billed per second from the hourly rate. Prices in India are shown in INR. Other locations are shown in USD. ## Catalogue rates Rates last changed Nov 28, 2026, 8:32 PM · per GPU-hour | GPU | Details | Price | | --- | --- | --- | | H100 PCIE | 125GB RAM · 31 vCPU · Community | $2.568/hr | | H100 PCIE | 128GB RAM · 20 vCPU · Secured | $3.804/hr | | H100 PCIE | 63GB RAM · 16 vCPU · Community | $3.84/hr | | H100 NVL | 173GB RAM · 18 vCPU · Secured | $4.308/hr | | H100 NVL | 315GB RAM · 40 vCPU · Community | $4.716/hr | | H100 SXM | 126GB RAM · 24 vCPU · Community | $4.908/hr | | H100 SXM | 125GB RAM · 8 vCPU · Secured | $5.928/hr | | H100 SXM | 125GB RAM · 8 vCPU · Secured | $5.928/hr | | H100 SXM | 125GB RAM · 8 vCPU · Secured | $5.928/hr | | H100 SXM | 125GB RAM · 8 vCPU · Secured | $5.928/hr | | H100 SXM | 125GB RAM · 8 vCPU · Secured | $5.928/hr | | H100 PCIE · 2 GPUs | 256GB RAM · 40 vCPU · Secured | $7.62/hr | | H100 SXM · 2 GPUs | 252GB RAM · 48 vCPU · Community | $9.804/hr | | H100 NVL · 8 GPUs | 1440GB RAM · 252 vCPU · Secured | $22.236/hr | | H100 SXM · 4 GPUs | 504GB RAM · 96 vCPU · Community | $26.796/hr | | H100 SXM · 8 GPUs | 1574GB RAM · 127 vCPU · Community | $34.56/hr | | H100 SXM · 8 GPUs | 1771GB RAM · 207 vCPU · Community | $35.1/hr | All GPU rates: https://podstack.ai/gpu-cloud-india --- # A customer-support agent grounded in your docs Learn how to build a RAG-based support agent using Podstack’s serverless GPU inference to provide accurate, documentation-grounded technical answers. Agents · 2026-11-20 · 3 min read Modern customer support has moved beyond simple keyword matching. Today, developers need agents that not only understand natural language but are strictly grounded in technical documentation to prevent "hallucinations." Building a Retrieval-Augmented Generation (RAG) system is the standard approach, but the challenge lies in deploying the inference and embedding logic without managing complex infrastructure. In this guide, we will build a production-ready support agent grounded in a custom documentation set. We will use a vector database for storage and Podstack to handle the heavy lifting of GPU-accelerated inference for both embeddings and response generation. ## The Architecture of a Grounded Agent A grounded agent operates in three distinct phases: 1. **Ingestion:** Your documentation (Markdown, PDF, or HTML) is broken into chunks and converted into high-dimensional vectors using an embedding model. 2. **Retrieval:** When a user asks a question, the system converts that query into a vector and finds the most relevant chunks in your documentation. 3. **Generation:** The relevant chunks are passed to a Large Language Model (LLM) as context, instructing it to answer using *only* the provided information. ## Setting Up Your Environment To follow along, you will need a Podstack account. We will use the Podstack API to deploy our inference functions. First, authenticate your environment: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` We will use two models: `bge-small-en-v1.5` for lightweight, fast embeddings and `Llama-3-8B-Instruct` for the final response generation. ## Implementing the RAG Logic The core of our agent is a Python function that manages the flow. We can deploy this as a Podstack Function, which gives us the benefit of per-second billing—we only pay for the GPU time used during the actual inference. Here is a simplified implementation of the grounding logic: ```python import podstack from qdrant_client import QdrantClient # Initialize Podstack clients for serverless inference llm = podstack.Inference(model="llama-3-8b-instruct") embedder = podstack.Inference(model="bge-small-en-v1.5") def support_agent(user_query: str): # 1. Embed the user query query_vector = embedder.embed(user_query) # 2. Retrieve relevant docs (Assuming a pre-filled Qdrant collection) client = QdrantClient("http://your-vector-db:6333") search_result = client.search( collection_name="docs", query_vector=query_vector, limit=3 ) context = "\n".join([res.payload['text'] for res in search_result]) # 3. Generate grounded response system_prompt = f""" You are a technical support agent. Use the following documentation to answer: {context} If the answer is not in the context, say you don't know. Do not make up facts. """ response = llm.complete( prompt=user_query, system=system_prompt, temperature=0.2 ) return response.text ``` ## Practical Tips for Production ### 1. Chunking Strategy Don't just split by character count. Use "recursive character splitting" that respects headers and code blocks. If a code snippet is split in half, the LLM will lose the context of the implementation, leading to broken support advice. ### 2. The "I Don't Know" Threshold When retrieving context from your vector store, check the similarity score. If the highest score is below a certain threshold (e.g., 0.7), the user is likely asking something outside your documentation. In these cases, bypass the LLM and direct them to a human agent immediately to save on inference costs. ### 3. Latency Optimization For a support chat, latency is king. Using Podstack’s serverless endpoints allows you to stream the LLM response. By setting `stream=True` in your inference call, you can show the user the response word-by-word, significantly improving the perceived speed of the agent. ## Deploying to Podstack The beauty of this workflow is that you don't need to configure CUDA versions or manage Docker images for your GPU nodes. You can deploy your entire support logic as a Podstack Function. To deploy the logic we wrote above, simply use the API: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` This command wraps your Python script into a scalable endpoint. Podstack will automatically spin up the necessary GPU resources when a request comes in and spin them down immediately after, ensuring you aren't paying for idle time while waiting for customers to type. ## Closing Building a grounded customer support agent ensures your AI stays helpful and accurate. By offloading the embedding and generation tasks to Podstack, you gain access to high-performance GPUs on a per-second basis, making it cost-effective to scale from a few beta users to thousands of concurrent support tickets. Whether you are using on-demand GPUs for periodic document re-indexing or serverless endpoints for real-time chat, Podstack provides the infrastructure to keep your agents responsive and your documentation useful. --- # Agent memory: short-term, long-term and vector stores Learn how to implement short-term, long-term, and vector-based memory for AI agents using Python and GPU-accelerated inference on Podstack. Agents · 2026-11-17 · 3 min read In the current landscape of AI development, an LLM without memory is effectively a stateless function. While base models are incredible at reasoning, their "intelligence" is confined to the training cutoff and the current context window. For developers building autonomous agents, the challenge lies in bridging the gap between raw compute and persistent cognition. To build agents that learn from user interactions and retain domain knowledge, we must implement a multi-tiered memory architecture: short-term, long-term, and vector-based retrieval. ## The Architecture of Agent Memory Just as the human brain utilizes different systems for immediate tasks and life-long recall, AI agents require a tiered approach to data: 1. **Short-Term Memory:** This is the immediate conversation history. It lives within the context window of the model and allows the agent to follow threads, resolve pronouns (e.g., "What did *he* say?"), and maintain a coherent flow. 2. **Long-Term Memory:** This involves persisting user preferences, past outcomes, and specific facts across different sessions. This is typically stored in a traditional database (NoSQL or Relational). 3. **Vector Stores (Episodic/Semantic Memory):** This is the "library" where an agent can perform a similarity search to find relevant information from massive datasets that exceed the context window. ## Implementing Memory with Python When deploying agents on high-performance GPUs, you want a memory system that doesn't bottleneck your inference speed. Below is a practical implementation using a vector store for semantic memory and a simple buffer for short-term context. ```python import os from podstack import Client from langchain_community.vectorstores import Chroma from langchain_openai import OpenAIEmbeddings # Initialize Podstack client for GPU-accelerated inference client = Client(api_key=os.getenv("PODSTACK_API_KEY")) class AgentWithMemory: def __init__(self, collection_name="agent_knowledge"): self.short_term_buffer = [] self.embeddings = OpenAIEmbeddings() self.vector_store = Chroma( collection_name=collection_name, embedding_function=self.embeddings ) def add_to_long_term_memory(self, text, metadata=None): """Adds information to the vector store for future retrieval.""" self.vector_store.add_texts(texts=[text], metadatas=[metadata]) def query(self, user_input): # 1. Retrieve relevant context from long-term memory docs = self.vector_store.similarity_search(user_input, k=2) context = "\n".join([d.page_content for d in docs]) # 2. Construct the prompt with context and short-term history prompt = f"Context: {context}\nHistory: {self.short_term_buffer[-3:]}\nUser: {user_input}" # 3. Run inference on Podstack (e.g., a hosted Llama-3-70b) response = client.inference.run( model="llama-3-70b-instruct", prompt=prompt ) # 4. Update short-term memory self.short_term_buffer.append(f"User: {user_input}, AI: {response}") return response # Example usage agent = AgentWithMemory() agent.add_to_long_term_memory("The user's favorite GPU cluster is Podstack.") print(agent.query("What cluster do I prefer?")) ``` ## Practical Tips for Memory Management * **Context Pruning:** Short-term memory can quickly fill up your context window, increasing latency and cost. Implement a sliding window or a "summarization" step where the agent periodically condenses the last 10 messages into a single summary paragraph. * **Metadata Filtering:** When using vector stores, don't just search by text similarity. Use metadata to filter by `user_id`, `timestamp`, or `topic` to ensure the agent doesn't retrieve irrelevant "memories" from other users. * **Embedding Selection:** The quality of your vector memory is only as good as your embedding model. Ensure your embedding dimensions match your vector store configuration for optimal retrieval performance. * **Asynchronous Writes:** Writing to long-term memory shouldn't block the user's response. Always perform vector store updates and database writes asynchronously to keep the agent's "thinking" time low. ## Deploying on Podstack Implementing memory-heavy agents requires a balance of high-throughput compute for inference and low-latency environments for data processing. On Podstack, you can deploy your agentic logic as serverless GPU functions or dedicated endpoints. Because Podstack bills by the second, you aren't paying for idle time while your agent is waiting for a database query or a vector search to return. You can use the Podstack API to deploy your environment in seconds: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` By offloading the heavy lifting of model inference to Podstack’s on-demand GPUs, you can focus on the logic of your memory architecture. Whether you are running complex RAG pipelines or maintaining long-term state for thousands of concurrent users, the per-second billing ensures that your agent scales efficiently without the overhead of managing bare metal. --- # Batch jobs: processing a million images overnight Learn how to orchestrate high-throughput GPU batch jobs to process millions of images using Python, Docker, and Podstack's per-second billing. Workflows · 2026-11-14 · 3 min read Modern machine learning workflows often hit a wall when transitioning from prototype to production. Running inference on a few dozen images in a Jupyter notebook is trivial, but processing a million images for a new feature or a data re-training pipeline is a massive engineering hurdle. If you try to run this on a single instance, it will take weeks. If you try to manage a massive cluster manually, you’ll spend more time on infrastructure orchestration than on your model. The solution lies in high-throughput batch jobs that leverage per-second billing and massive parallelism. ## The Architecture of a Million-Image Job To process a million images overnight, you shouldn't think about "one big server." Instead, think about a fleet of ephemeral workers. The core requirements for this scale are: 1. **Decoupled Storage:** Your images should live in S3-compatible storage. 2. **Message Queueing:** Use a simple queue (like SQS or Redis) to distribute image URLs to workers. 3. **Stateless Workers:** Each GPU worker pulls a batch, processes it, saves the result, and repeats. 4. **Auto-scaling Logic:** You need the ability to spin up 100+ GPUs simultaneously and shut them down the millisecond the queue is empty. ## Step 1: Containerize Your Inference Engine First, wrap your model in a lightweight Python script. Avoid loading the model for every image; instead, load it once into the GPU VRAM and process images in batches of 32, 64, or 128 depending on your VRAM overhead. ```python import os import torch from PIL import Image from my_model import ImageClassifier # Initialize model once model = ImageClassifier().to("cuda").eval() def process_batch(image_paths): images = [Image.open(p).convert("RGB") for p in image_paths] inputs = torch.stack([transform(i) for i in images]).to("cuda") with torch.no_grad(): results = model(inputs) # Save results to a database or object storage save_results(results) def main(): while True: # Pull batch from your queue batch = queue.get_next_batch(size=64) if not batch: break process_batch(batch) if __name__ == "__main__": main() ``` ## Step 2: Defining the Job With Podstack, you don’t need to manage Kubernetes manifests. You define a GPU function or a job that points to your container. Because Podstack bills per second, you can scale horizontally without worrying about "rounding up" to the nearest hour, which is often where the hidden costs of batch processing lie. Using the Podstack API, you can trigger a job that scales based on the intensity of your workload. Ensure your `PODSTACK_API_KEY` is exported in your environment. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` ## Step 3: Optimization for Throughput When processing a million images, "micro-optimizations" become "macro-savings." * **Pre-fetching:** While the GPU is busy performing inference on Batch A, your CPU should be downloading and decoding Batch B. Use a multi-threaded data loader to ensure the GPU never sits idle. * **Mixed Precision:** Use `torch.cuda.amp.autocast()`. For most inference tasks, FP16 or BF16 provides a 2x speedup with negligible accuracy loss. * **Locality:** Ensure your GPU workers are in the same region as your data bucket to minimize egress costs and latency. ## Managing Costs The "overnight" requirement implies a window of roughly 8 to 10 hours. To process 1,000,000 images in 8 hours, you need to process ~125,000 images per hour, or ~35 images per second. If a single A100 can process 20 images per second with a ResNet-based architecture, you only need two or three GPUs to finish the task. However, for more complex transformer-based models (like CLIP or a large ViT), you might only get 2 images per second. In that case, you’d spin up 20 replicas. On Podstack, the cost is the same whether you run 1 GPU for 20 hours or 20 GPUs for 1 hour. The latter gets you the data faster. ## Why Podstack for Large Batches? Handling a million images is a test of infrastructure stability. Podstack is built for this specific high-concurrency lifecycle: 1. **Serverless Inference:** If your workload is bursty, use GPU functions that spin up on demand when messages hit the queue. 2. **On-Demand Availability:** When you need 50 GPUs *now*, Podstack’s fleet management ensures you aren't stuck in a "pending" state. 3. **Python-First Workflow:** You can trigger these jobs directly from your training scripts using the Python SDK, making it easy to integrate into a CI/CD pipeline for ML. By decoupling your compute from your long-running instances and using `podstack` to orchestrate ephemeral GPU workers, you turn a "million-image nightmare" into a routine automated task that finishes before your morning coffee is ready. --- # Batching and KV-cache: how LLM serving really works Learn how Continuous Batching and KV-caching optimize LLM inference throughput and how to deploy these strategies using Podstack’s per-second GPU scaling. Inference · 2026-11-11 · 3 min read When you first move from training a model to serving it in production, the math changes. In training, your goal is raw throughput (tokens per second). In inference, you are balancing a three-way tug-of-war between **latency** (how fast a single user gets a response), **throughput** (how many users you can handle at once), and **cost**. To optimize LLM inference, you have to look under the hood at two specific mechanisms that define modern serving: Continuous Batching and KV-Caching. ## The Bottleneck: Memory vs. Compute LLMs are notoriously memory-bandwidth bound. During a single forward pass, the GPU spends more time moving weights from VRAM to the compute cores than it does actually performing the matrix multiplication. If you serve one user at a time, your GPU is mostly sitting idle, waiting for data to move. This is why we batch. By processing multiple requests simultaneously, we "reuse" the weights for multiple inputs, significantly increasing the tokens generated per dollar. ## The KV-Cache: Eliminating Redundant Math LLMs are autoregressive—they generate one token at a time, using the entire previous context to predict the next word. Without a KV-cache, the model would have to recompute the hidden states (Key and Value vectors) for every single previous token every time it wants to generate a new one. This results in $O(n^2)$ complexity. The **KV-Cache** stores these tensors in VRAM so the model only has to compute the representation for the *newest* token. **The Catch:** This cache consumes a massive amount of VRAM. For a Llama-3 70B model, the KV-cache can easily exceed 20GB for a long context window. If your VRAM is full, you can’t batch more users. This is where "Paged Attention" comes in—partitioning that cache into non-contiguous blocks to prevent memory fragmentation. ## Continuous Batching: The Gold Standard Traditional batching (Static Batching) waits for $N$ requests to arrive, runs them together, and waits for the longest one to finish before returning any results. This is terrible for LLMs because one user might ask for a 5-word haiku while another asks for a 500-word essay. **Continuous Batching** (or Iteration-level Batching) injects new requests into the batch as soon as others finish. This keeps the GPU cores saturated at all times without forcing fast requests to wait for slow ones. ## Practical Implementation: Deploying Optimized Serving When deploying on a GPU cloud like Podstack, you shouldn't write these kernels from scratch. You leverage engines like vLLM or Hugging Face TGI that implement these optimizations out of the box. Here is how you can deploy an optimized Llama-3 inference server using the Podstack API. This configuration ensures the model uses a vLLM backend to handle PagedAttention and Continuous Batching. ```python # deploy_llm.py import podstack # Initialize the client (ensure PODSTACK_API_KEY is in your env) client = podstack.Client() # Define a GPU function with vLLM for optimized batching @client.gpu_function( gpu="A100-80GB", image="vllm/vllm-openai:latest", env={"MODEL_NAME": "meta-llama/Meta-Llama-3-8B"} ) def generate_text(prompt: str, max_tokens: int = 256): # This function wraps the internal vLLM engine # Podstack handles the per-second billing and auto-scaling response = client.endpoints.call( "llama-3-8b", json={"prompt": prompt, "max_tokens": max_tokens} ) return response if __name__ == "__main__": # Deploy to a live endpoint client.deploy(generate_text, name="production-llm-api") print("Endpoint live: use 'podstack endpoints list' to view status") ``` ## Practical Tips for Production Serving 1. **Monitor KV-Cache Utilization:** If your "Cache Usage" is consistently at 90%+, your requests will start queuing even if GPU compute is low. Consider upgrading to a higher VRAM instance (e.g., A100 80GB) to increase your max batch size. 2. **Tune `max_num_seqs`:** This parameter controls how many requests are batched at once. Setting it too high can increase Time To First Token (TTFT) as the initial "prefill" stage for many requests happens at once. 3. **Use Per-Second Billing:** LLM traffic is bursty. If you use a provider that rounds up to the hour, your "idle" time—when the KV-cache is empty—costs you a fortune. ## Deploying on Podstack At Podstack, we designed our infrastructure specifically for these workloads. Because we offer **per-second billing** on on-demand GPUs, you aren't penalized when your batch sizes are low during off-peak hours. To get started, install the SDK: `pip install podstack-sdk` Set your API key: `export PODSTACK_API_KEY='your_secret_key'` Then, use the the console or the API. Whether you are running serverless GPU functions for intermittent tasks or dedicated endpoints for high-throughput production apps, Podstack provides the bare-metal performance needed to keep your KV-cache operations lightning-fast. By mastering batching and KV-caching, you move from "it works on my machine" to a production-grade system that scales efficiently and stays within budget. --- # Browser-automation agents for repetitive web tasks Learn how to build and deploy resilient, LLM-powered browser agents for web automation using Playwright and scalable GPU functions on Podstack. Agents · 2026-11-08 · 4 min read Building autonomous agents that can navigate the web, bypass bot detection, and extract structured data is becoming a cornerstone of the modern ML stack. Whether you are training an LLM on niche forum data, automating competitive pricing analysis, or monitoring internal dashboards, simple HTTP requests often fall short. Modern websites are dynamic, JavaScript-heavy, and increasingly resistant to headless scrapers. To build a resilient browser-automation agent, you need three things: a high-level orchestration framework (like Playwright or Selenium), an LLM to "reason" about DOM elements, and scalable compute that can handle the heavy memory footprint of multi-tab browsing. ## The Architecture of a Modern Web Agent The traditional approach to web scraping involved writing fragile CSS selectors that broke the moment a developer changed a `div` class. Modern agents utilize "Vision-Language" models or "HTML-to-Markdown" pipelines to understand the page structure semantically. The workflow typically follows this loop: 1. **Initialize:** Launch a headless browser instance. 2. **Observe:** Capture the current page state (HTML snapshot or screenshot). 3. **Reason:** Send the state to an LLM to decide the next action (e.g., "Click the 'Login' button"). 4. **Act:** Execute the action via a driver (Playwright/Puppeteer). 5. **Verify:** Check if the action resulted in the expected state change. ## Setting Up the Environment For developers, Python is the language of choice due to its rich ecosystem of AI libraries. We recommend using **Playwright** for its superior speed and built-in auto-waiting features. When deploying these agents, the primary bottleneck is often the overhead of launching browser instances and the memory required for rendering. Running these as long-lived containers is expensive, which is why serverless GPU functions or on-demand jobs are the preferred deployment patterns. ## Implementation: A Scripted Browser Agent Below is a Python implementation of a simple agent that can navigate to a site and perform a search. In a production environment, you would wrap this logic in a function to be triggered on-demand. ```python import asyncio from playwright.async_api import async_playwright import os async def run_web_agent(target_url, search_query): async with async_playwright() as p: # Launching with specific arguments to optimize for cloud environments browser = await p.chromium.launch( headless=True, args=["--no-sandbox", "--disable-setuid-sandbox"] ) context = await browser.new_context( user_agent="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" ) page = await context.new_page() print(f"Navigating to {target_url}...") await page.goto(target_url) # Simple interaction: Find a search bar and type # In a real LLM agent, these selectors would be determined dynamically try: await page.wait_for_selector('input[type="text"]', timeout=5000) await page.fill('input[type="text"]', search_query) await page.keyboard.press("Enter") # Wait for results to load await page.wait_for_load_state("networkidle") # Capture data or screenshot screenshot_path = "result.png" await page.screenshot(path=screenshot_path) print(f"Task complete. Screenshot saved to {screenshot_path}") except Exception as e: print(f"Error during execution: {e}") finally: await browser.close() if __name__ == "__main__": asyncio.run(run_web_agent("https://news.ycombinator.com", "GPU computing")) ``` ## Practical Tips for Scaling Web Agents 1. **Stealth Mode:** Standard headless browsers are easily detected. Use packages like `playwright-stealth` to patch browser fingerprints and avoid being blocked by common WAFs (Web Application Firewalls). 2. **Context Persistence:** If your agent needs to stay logged into a service, persist the `browser_context` state (cookies and local storage) to a persistent volume between runs. 3. **Resource Allocation:** Browser instances are CPU and RAM intensive. However, if your agent uses an on-device VLM (Vision Language Model) like Moondream or LLaVA to "see" the website, you will need GPU acceleration to maintain low latency. 4. **Concurrency:** Don't run 50 tabs in one browser. It’s more resilient to run 50 atomic jobs. If one tab crashes the browser process, it won't kill your entire batch. ## Deploying on Podstack Deploying these agents manually on raw VMs leads to "zombie" browser processes and high costs for idle time. Podstack provides a more efficient path by allowing you to package your agent as a GPU-accelerated function or a per-second billed job. By using the Podstack API, you can deploy your agent script as a serverless endpoint. This ensures that you only pay for the exact duration the browser is open and the LLM is inferring. To deploy your agent, ensure your `PODSTACK_API_KEY` is set in your environment: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Using Podstack’s infrastructure, you can trigger hundreds of agents simultaneously to perform large-scale data extraction. Because Podstack bills per second, the "warm-up" and "tear-down" costs of the browser are minimized. You get the power of dedicated GPUs for your vision-based reasoning models, combined with the elasticity of serverless compute for the browsing tasks. ## Conclusion Browser-automation agents are moving away from rigid scripts toward fluid, AI-driven navigation. By combining Playwright with powerful ML models and deploying on a per-second GPU cloud like Podstack, you can build agents that are faster, harder to block, and significantly cheaper to operate at scale. Stop managing infrastructure and start automating the web. --- # Building a coding agent that runs tests in a sandbox Learn how to build a self-correcting coding agent using LLMs and Podstack's on-demand GPU jobs to securely execute and test code in a sandboxed environment. Agents · 2026-11-05 · 4 min read Building an AI agent that writes code is a popular weekend project, but building one that writes *working* code is a significant engineering challenge. The gap between a hallucinated snippet and a functional script is usually a feedback loop: the agent needs to run its code, observe the stack trace, and iterate until the tests pass. However, executing LLM-generated code on your local machine or a production server is a major security risk. To build a robust coding agent, you need a secure, isolated sandbox that can be spun up instantly, execute arbitrary logic, and provide the results back to the agent. In this guide, we’ll walk through the architecture of a coding agent that utilizes a sandboxed environment to validate its work before delivering a final solution. ## The Architecture of a Coding Agent A functional coding agent requires three core components: 1. **The Planner:** An LLM that decomposes a task into functions and tests. 2. **The Executor:** A secure sandbox environment where the code is actually run. 3. **The Feedback Loop:** A mechanism to pipe `stderr` and test failures back to the LLM for self-correction. For ML-heavy tasks—such as optimizing a PyTorch kernel or running a data science pipeline—the executor needs more than just a CPU. It needs a GPU-accelerated environment that is billed only for the seconds the code is actually running. ## Step 1: Defining the Sandbox Environment Your agent needs a consistent environment. Instead of managing complex Dockerfiles locally, you can define a remote environment that includes your necessary dependencies (like `pytest`, `numpy`, or `torch`). When the agent generates code, we don't just want the source; we want a test suite. The agent should be prompted to output two files: `solution.py` and `test_solution.py`. ## Step 2: Implementing the Execution Logic Using the Podstack Python SDK, we can trigger a remote "job" that acts as our sandbox. This allows us to spin up a GPU-enabled container, run the tests, and tear it down immediately, paying only for the execution time. Here is a conceptual implementation of how the agent interacts with the sandbox: ```python import os from podstack import Podstack # Initialize the client using your API Key client = Podstack(api_key=os.getenv("PODSTACK_API_KEY")) def run_in_sandbox(code: str, tests: str): """ Deploys the generated code to a secure Podstack job to validate execution. """ # Combine code and tests into a single execution script full_script = f"{code}\n\n{tests}" # Run a serverless GPU job job = client.jobs.run( image="pytorch/pytorch:latest", command=["python3", "-c", full_script], gpu="A10", # Request a specific GPU for ML tasks ) # Wait for the result and capture logs result = job.wait() return { "status": result.status, "logs": result.logs, "exit_code": result.exit_code } # Example LLM-generated content generated_code = "def add(a, b): return a + b" generated_tests = "assert add(2, 3) == 5" output = run_in_sandbox(generated_code, generated_tests) if output["exit_code"] != 0: print(f"Tests failed. Feed this back to the LLM: {output['logs']}") else: print("Code validated successfully.") ``` ## Step 3: The Self-Correction Loop Once the sandbox returns the logs, the agent enters the "Refinement Phase." If the `exit_code` is non-zero, the agent receives the full traceback. Modern LLMs are remarkably good at debugging when provided with the exact error message. By repeating this loop (usually 2-3 times), the success rate of the agent increases drastically compared to a single-shot generation. ## Practical Tips for Sandboxing * **Set Timeouts:** Always set a maximum duration for your sandbox jobs. Coding agents can occasionally write infinite loops. * **Dependency Management:** If your agent needs specific libraries, pre-build a container image. Pulling `pip` packages inside the sandbox for every run adds latency. * **Minimal Permissions:** Ensure the sandbox has no access to your environment variables or internal network. Podstack jobs are isolated by default, providing an extra layer of security against malicious code generation. * **State Persistence:** If the agent is working on a large project, use a persistent volume to mount the codebase into the sandbox so the agent can see the entire context. ## Scaling with Podstack The bottleneck for most coding agents is the infrastructure. Setting up a fleet of GPU nodes to handle simultaneous agent requests is an operations nightmare. Podstack simplifies this by treating GPU functions as serverless primitives. You don't need to manage a cluster; you simply define the task and run it. Whether you are building an agent that writes high-performance CUDA kernels or a simple data processing script, you can use the Podstack API to monitor your jobs in real-time: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` By offloading the execution to Podstack's on-demand GPU infrastructure, your agent remains fast, secure, and cost-effective, billing you only for the seconds it takes to run the tests. This allows you to scale from a local prototype to a production-grade coding assistant without changing your backend architecture. --- # Building a RAG chatbot over company knowledge Learn how to build a high-performance RAG chatbot using vector databases and serverless GPU functions on Podstack for efficient company knowledge retrieval. RAG · 2026-11-02 · 4 min read Retrieving answers from vast internal documentation is a classic challenge for growing engineering teams. Traditional keyword search often falls short when engineers ask nuanced questions like, "How do we handle idempotency in our payment pipeline?" or "Where is the configuration for the staging ingress?" This is where Retrieval-Augmented Generation (RAG) shines. By combining a dense vector database with a powerful Large Language Model (LLM), you can build a chatbot that "reads" your company's knowledge base before answering. In this guide, we will walk through building a production-ready RAG pipeline using Python and Podstack. ## The RAG Architecture A standard RAG pipeline consists of three main phases: 1. **Ingestion:** Breaking documents into chunks and converting them into vector embeddings. 2. **Retrieval:** Searching the vector store for the most relevant chunks based on a user’s query. 3. **Generation:** Passing the user query and the retrieved context to an LLM to generate a factual response. For high-performance RAG, you need significant compute—specifically for generating embeddings over thousands of documents and running inference on the LLM. ## Step 1: Setting Up the Environment First, ensure you have the Podstack API installed and your environment configured. This allows you to offload the heavy lifting of embedding generation and LLM inference to high-end GPUs without managing infrastructure. ```bash pip install podstack-sdk langchain sentence-transformers chromadb export PODSTACK_API_KEY="your_api_key_here" ``` ## Step 2: Processing Knowledge Base Data RAG is only as good as the data it retrieves. Start by loading your markdown files, PDFs, or internal wikis. We'll use a recursive character splitter to ensure our "chunks" retain enough semantic context. ```python import podstack from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain_community.document_loaders import DirectoryLoader from langchain_community.vectorstores import Chroma from langchain_huggingface import HuggingFaceEmbeddings # 1. Load documents loader = DirectoryLoader('./company_docs', glob="**/*.md") docs = loader.load() # 2. Chunking text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100) splits = text_splitter.split_documents(docs) # 3. Create Embeddings using Podstack GPU functions # We use a Podstack-hosted embedding endpoint for speed embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2") # 4. Store in Vector DB vectorstore = Chroma.from_documents(documents=splits, embedding=embeddings) ``` ## Step 3: Building the GPU-Accelerated Inference Function To keep the chatbot responsive, we want to run the LLM inference on an on-demand GPU. Podstack allows us to define a Python function and deploy it as a serverless endpoint. This ensures you only pay for the seconds the GPU is actually processing the prompt. We will use a model like Llama-3 or Mistral-7B for the generation phase. ```python from podstack import gpu_function @gpu_function(gpu="A100", timeout=60) def generate_answer(query: str, context: str): import torch from transformers import pipeline prompt = f""" You are a helpful company assistant. Use the following pieces of retrieved context to answer the question. If you don't know the answer, just say that you don't know. Context: {context} Question: {query} Answer: """ # Podstack manages the model loading and GPU memory allocation pipe = pipeline("text-generation", model="meta-llama/Meta-Llama-3-8B-Instruct", device=0) result = pipe(prompt, max_new_tokens=256) return result[0]['generated_text'] ``` ## Step 4: Connecting Retrieval to Generation The final step is the "Augmentation" part of RAG. When a user asks a question, we query our vector store, grab the top 3-5 relevant chunks, and pass them to our Podstack GPU function. ```python def ask_chatbot(user_query): # Perform similarity search results = vectorstore.similarity_search(user_query, k=3) context_text = "\n\n".join([doc.page_content for doc in results]) # Trigger the GPU-accelerated inference response = generate_answer(user_query, context_text) return response print(ask_chatbot("What is our policy on remote work for engineers?")) ``` ## Practical Tips for Production RAG * **Metadata Filtering:** If your company has multiple departments, store the "department" or "team" as metadata in your vector store. This allows you to filter the search space and prevent the HR bot from retrieving Engineering docs. * **Context Window Management:** Large models have limits. If you retrieve too many chunks, you might hit the token limit. Use "Map-Reduce" or "Refine" chains if you need to synthesize information from dozens of documents. * **Cold Starts:** Since we are using serverless GPU functions on Podstack, keep an eye on your model size. Smaller, quantized models (GGUF or AWQ) load significantly faster and reduce latency for the end user. ## Why Podstack for RAG? Building a RAG pipeline requires balancing cost with performance. Traditional server instances are expensive to keep running 24/7 if your employees only ask questions during work hours. With Podstack, you can deploy your embedding models and LLMs as serverless endpoints. You benefit from on-demand GPUs billed per second, meaning you don't pay for idle time. Whether you are running a batch job to re-index your entire knowledge base or serving a real-time chatbot to 500 engineers, Podstack scales automatically. To get started, simply wrap your inference logic in the `@gpu_function` decorator and deploy via the Podstack API. You’ll have a high-performance, private company chatbot running on top-tier silicon in minutes. --- # Building a speech-to-text transcription service Learn how to deploy a scalable, cost-efficient speech-to-text service using OpenAI Whisper and Podstack’s serverless Python GPU functions. Audio · 2026-10-30 · 3 min read Building high-performance speech-to-text (STT) services is a common requirement for modern AI applications, ranging from automated meeting notes to real-time captioning. However, developers often face a dilemma: settle for high-latency API calls to generic providers or manage complex GPU infrastructure to run state-of-the-art models like OpenAI's Whisper. Running these models on local hardware is rarely viable for production, and traditional cloud instances often lead to wasted spend during idle periods. In this guide, we will walk through building a scalable transcription service using Python and Podstack’s serverless GPU functions, allowing you to pay only for the seconds your model is actually processing audio. ## Choosing the Right Model While there are many STT models available, OpenAI’s **Whisper** remains the industry standard for accuracy and multilingual support. For a production service, we recommend using the `faster-whisper` implementation. It utilizes CTranslate2, a fast inference engine for Transformer models, which can be up to 4x faster than the original implementation while using less memory. When deploying on Podstack, you can leverage the `large-v3` model for maximum accuracy or `distil-large-v2` if your primary concern is inference speed and lower cost. ## Setting Up Your Environment To get started, you’ll need the Podstack API installed and your API key configured. This allows you to deploy Python functions directly to high-end GPUs without worrying about Dockerfiles or Kubernetes manifests. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Next, create a project directory and a `requirements.txt` file including `faster-whisper` and `torch`. ## Implementation: The Transcription Function The core logic of our service involves loading the model into GPU memory and processing the audio buffer. Podstack allows you to define a "setup" phase to load the model weights once, ensuring that subsequent requests (warm hits) are processed near-instantaneously. Here is a practical implementation of a Podstack GPU function: ```python import podstack from faster_whisper import WhisperModel # The 'podstack.gpu' decorator tells the platform to # provision an NVIDIA GPU (e.g., A100 or L4) for this logic. @podstack.gpu(model="large-v3", gpu_type="l4") class TranscriptionService: def __init__(self): # This runs once when the container starts self.model = WhisperModel("large-v3", device="cuda", compute_type="float16") def transcribe(self, audio_url: str): # The transcribe method performs the actual inference segments, info = self.model.transcribe(audio_url, beam_size=5) results = [] for segment in segments: results.append({ "start": segment.start, "end": segment.end, "text": segment.text }) return { "language": info.language, "duration": info.duration, "segments": results } # Deploying the function to a live endpoint if __name__ == "__main__": podstack.deploy(TranscriptionService) ``` ## Scaling and Optimization When building this for a production environment, consider these three technical optimizations: 1. **VAD (Voice Activity Detection) Filter**: Whisper can sometimes "hallucinate" text during silent periods. Enabling the `vad_filter` in `faster-whisper` helps the model ignore non-speech audio, reducing processing time and improving accuracy. 2. **Batching**: If you are processing thousands of short audio clips, batching them into a single inference call can significantly increase throughput. 3. **Cold Start Management**: Podstack’s serverless nature means the GPU is de-provisioned when not in use. For latency-sensitive apps, you can set a `min_replicas` value in your configuration to keep one GPU "warm" while allowing the rest of the cluster to scale to zero. ## Deploying to Podstack To deploy your service, you simply use the API. Podstack handles the provisioning of the GPU, the installation of CUDA drivers, and the creation of a secure HTTPS endpoint. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Once deployed, you receive an endpoint URL. You can now send audio files via a simple POST request. Because Podstack bills per second, if a transcription takes 4.5 seconds, you are only charged for those 4.5 seconds of GPU time. ## Handling Long-Form Audio For audio files longer than 30 minutes, it is best practice to treat the transcription as an asynchronous job rather than a synchronous API call. You can trigger the Podstack function and provide a webhook URL. Once the GPU finishes the transcription, Podstack will POST the JSON result back to your main application backend. This prevents timeout issues and allows your application to handle other tasks while the GPU works. ## Conclusion Building a speech-to-text service doesn't require managing complex infrastructure. By combining the efficiency of `faster-whisper` with Podstack’s on-demand GPU architecture, you can deploy a production-grade STT engine in minutes. This approach gives you the best of both worlds: the performance of dedicated hardware and the cost-efficiency of serverless billing. Ready to deploy your first model? Head over to your dashboard, grab your `PODSTACK_API_KEY`, and turn your Python functions into scalable GPU endpoints today. --- # Building a text-to-image pipeline with ComfyUI on cloud GPUs Learn how to deploy and scale ComfyUI on Podstack cloud GPUs using Python and the Podstack API for high-performance, per-second billed image generation. Image · 2026-10-27 · 3 min read Deploying high-performance image generation workflows often means balancing the flexibility of a GUI with the scalability of a cloud environment. ComfyUI has emerged as the gold standard for ML engineers who need node-based control over Stable Diffusion, Flux, and SDXL models. However, running these locally often leads to VRAM bottlenecks and thermal throttling. In this post, we will walk through setting up a production-ready text-to-image pipeline using ComfyUI on Podstack, leveraging on-demand GPUs to ensure you only pay for the seconds your model is actually generating pixels. ## Why ComfyUI for Production? Unlike monolithic interfaces, ComfyUI treats image generation as a computational graph. Each component—the CLIP text encoder, the VAE, the Sampler—is a discrete node. For developers, this is advantageous because: 1. **Reproducibility:** Workflows can be exported as JSON files and triggered via API. 2. **Efficiency:** It only re-runs nodes that have changed, saving precious GPU cycles. 3. **Extensibility:** Custom nodes allow for integrating ControlNet, IP-Adapter, or custom Python logic directly into the pipeline. ## Step 1: Setting up the Podstack Environment To get started, you need the Podstack API. Since Podstack bills per second, we can spin up a high-VRAM instance (like an A100 or H100), perform our heavy lifting, and tear it down immediately. First, authenticate your environment: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Now, we will launch a GPU job. While you can run ComfyUI as a persistent server, many developers prefer to launch it as a managed job for batch processing. ## Step 2: Preparing the ComfyUI Container The most efficient way to run ComfyUI on Podstack is via a Docker container. You can use a pre-built image or a custom one that includes your specific models and custom nodes. Below is a Python script using the Podstack SDK to launch a ComfyUI instance with an attached persistent volume for your models. ```python import podstack # Initialize the client client = podstack.Client() # Define the GPU workload # We use an NVIDIA A100 for high-resolution Flux generation job = client.jobs.create( name="comfyui-text-to-image", gpu="A100", image="comfyui/comfyui:latest", env={ "EXTRA_ARGS": "--listen 0.0.0.0 --port 8188", }, ports=[8188], volumes=[{ "name": "model-storage", "mount_path": "/home/user/ComfyUI/models" }] ) print(f"Job started: {job.id}") print(f"Access your UI at: {job.public_url}:8188") ``` ## Step 3: Headless Execution via API Once your workflow is perfected in the ComfyUI web interface, you don’t want to manually click "Queue Prompt" every time. You can export the workflow as "API Format" (JSON) and send it to the ComfyUI backend running on Podstack. Here is how you can programmatically trigger a generation from your local machine: ```python import requests import json def generate_image(prompt_text, server_address): # Load your exported ComfyUI JSON workflow with open("workflow_api.json", "r") as f: prompt = json.load(f) # Update the positive prompt node (usually ID '6' in default workflows) prompt["6"]["inputs"]["text"] = prompt_text payload = {"prompt": prompt} response = requests.post(f"http://{server_address}/prompt", json=payload) return response.json() # Example usage with your Podstack endpoint generate_image("A futuristic cyberpunk cityscape, cinematic lighting", "your-job-url.podstack.run") ``` ## Practical Tips for GPU Optimization * **Model Cold Starts:** Large models like Flux.1 can take 30+ seconds to load into VRAM. Use Podstack’s persistent volumes to keep your model weights cached close to the GPU, reducing the time between job initialization and the first image generated. * **Scale to Zero:** For inference-only workloads, consider wrapping your ComfyUI logic in a Podstack Serverless Function. This allows the GPU to spin down completely when no requests are in the queue. * **FP8 Quantization:** If you are running on lower-tier GPUs (like the A10 or RTX 3090), use the FP8 checkpoints for SDXL or Flux to reduce VRAM usage by nearly 50% with minimal quality loss. ## Running at Scale on Podstack Podstack is designed to handle the infrastructure overhead so you can focus on the creative logic of your workflows. By using the Podstack API and our per-second billing, you can execute massive batch image generation tasks without worrying about idle server costs. Whether you are building a generative AI startup or a custom internal tool, moving your ComfyUI pipelines to Podstack provides the necessary performance overhead. You can start with a single on-demand GPU for prototyping and transition to serverless endpoints for production traffic with the same codebase. Ready to deploy? Head over to the Podstack dashboard, grab your API key, and launch your first A100 instance in seconds. --- # Building an AI code-review bot for your repos Learn how to build a serverless AI code-review bot using Python and Podstack’s on-demand GPUs to automate pull request feedback with per-second billing. Agents · 2026-10-24 · 3 min read In the era of rapid software development, the bottleneck is often the code review process. While linters and static analysis catch syntax errors, they lack the "semantic intuition" to spot logic flaws or architectural inconsistencies. Large Language Models (LLMs) have bridged this gap, but running high-performance inference at scale usually requires managing complex infrastructure. In this guide, we’ll build a custom AI code-review bot that analyzes GitHub pull requests using a fine-tuned or open-source LLM (like Llama 3) hosted on Podstack. By using Podstack’s serverless GPU functions, we can trigger an inference job only when a new PR is opened, ensuring we only pay for the seconds the GPU is actually active. ## The Architecture Our bot consists of three main components: 1. **The Trigger**: A GitHub Action that fires on `pull_request` events. 2. **The Logic**: A Python script that fetches the code diff and prepares the prompt. 3. **The Inference Engine**: A Podstack GPU endpoint running our model of choice. The beauty of this setup is that you don't need a persistent server. Podstack handles the cold starts and scaling, providing a dedicated GPU environment for the duration of the review. ## Step 1: Setting Up the Inference Function First, we define our inference function. We want a model that can handle context-heavy diffs. We’ll use the Podstack Python SDK to define a function that loads our model and generates suggestions. ```python # review_bot.py import podstack from transformers import AutoModelForCausalLM, AutoTokenizer @podstack.gpu_function(gpu="A100", memory="40GB") def analyze_diff(diff_text: str): model_id = "meta-llama/Meta-Llama-3-8B-Instruct" tokenizer = AutoTokenizer.from_pretrained(model_id) model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto") prompt = f"Review the following git diff and identify logic errors or security risks:\n\n{diff_text}" inputs = tokenizer(prompt, return_tensors="pt").to("cuda") outputs = model.generate(**inputs, max_new_tokens=512) return tokenizer.decode(outputs[0], skip_special_tokens=True) ``` By decorating the function with `@podstack.gpu_function`, you tell the platform to provision an A100 only when this function is called. ## Step 2: Deploying to Podstack To make this function accessible to our GitHub Action, we deploy it using the Podstack API. Ensure you have your `PODSTACK_API_KEY` exported in your local environment. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Once deployed, Podstack provides a unique URL for your function. This endpoint is billed per second, meaning if the review takes 15 seconds, you only pay for those 15 seconds of A100 usage. ## Step 3: Integrating with GitHub Actions Now, we create a workflow in `.github/workflows/ai-review.yml`. This script will extract the PR diff and send it to our Podstack endpoint. ```yaml name: AI Code Review on: [pull_request] jobs: review: runs-on: ubuntu-latest steps: - name: Checkout code uses: actions/checkout@v4 with: fetch-depth: 0 - name: Get Diff run: git diff origin/${{ github.base_ref }} > pr_diff.txt - name: Call Podstack Reviewer env: PODSTACK_API_KEY: ${{ secrets.PODSTACK_API_KEY }} run: | python -c " import podstack client = podstack.Client() with open('pr_diff.txt', 'r') as f: res = client.call('code-reviewer', diff_text=f.read()) print(res) " > review_feedback.txt - name: Post Comment uses: mshick/add-pr-comment@v2 with: message-path: review_feedback.txt ``` ## Practical Tips for AI Reviews * **Prompt Engineering**: Don't just ask the AI to "review the code." Give it specific personas. For example: "You are a Senior Security Engineer. Focus on SQL injection, XSS, and broken access control in this diff." * **Context Management**: LLMs have token limits. If a PR is massive, split the diff by file or use a summarization step before the final review. * **Cost Efficiency**: Use smaller models (like Llama 3 8B) for general stylistic reviews and reserve larger models (70B+) for mission-critical architectural reviews. On Podstack, you can swap the `gpu` parameter in your decorator to match the model size instantly. ## Scaling with Podstack Building this on Podstack removes the "GPU tax" of idle instances. Traditional VPS or container services force you to pay for the GPU as long as the server is up, even if no PRs are being submitted. With Podstack’s per-second billing and serverless inference, your code-review bot costs pennies per day, scaling automatically during high-activity periods like "Merge Wednesdays." By moving the heavy lifting to Podstack, you keep your CI/CD pipeline fast and your developers focused on shipping features rather than managing Kubernetes clusters. Whether you are running a single-repo bot or a fleet of reviewers for an entire organization, the workflow remains the same: write Python, deploy via the API, and let the GPUs handle the rest. --- # Building your first AI agent with tool calling Learn how to build and deploy an AI agent using Python tool calling and Podstack's serverless GPU infrastructure for high-performance inference. Agents · 2026-10-21 · 4 min read Building your first AI agent can feel like a daunting leap from basic prompt engineering. While a standard LLM can generate text, an **agent** can interact with the world by executing code, searching the web, or querying databases. The bridge between "talking" and "doing" is a mechanism called **tool calling** (or function calling). In this guide, we will walk through building a functional AI agent that uses Python tools to solve math problems and fetch real-time data, and then deploy it as a high-performance endpoint. ## Understanding Tool Calling At its core, tool calling is a structured dialogue. Instead of the LLM just responding with text, the model is trained to recognize when a user’s request requires an external tool. It then outputs a structured JSON object containing the function name and the arguments to be used. Your application executes the function locally, feeds the result back to the LLM, and the LLM summarizes the final answer. This loop—**Reasoning -> Action -> Observation**—is what makes an agent "intelligent." ## Step 1: Defining Your Tools To start, we need to define the Python functions our agent can use. For this example, let's create a tool that calculates the square root of a number (to demonstrate precision) and a tool that simulates fetching live stock prices. ```python import math def get_stock_price(ticker: str): # In a real scenario, you'd call an API here prices = {"POD": 150.25, "GPU": 88.40} return prices.get(ticker.upper(), "Ticker not found.") def calculate_sqrt(n: float): return math.sqrt(n) # Define the tools for the LLM tools = [ { "type": "function", "function": { "name": "get_stock_price", "description": "Get the current stock price for a given ticker", "parameters": { "type": "object", "properties": { "ticker": {"type": "string"} }, "required": ["ticker"] } } }, { "type": "function", "function": { "name": "calculate_sqrt", "description": "Calculate the square root of a number", "parameters": { "type": "object", "properties": { "n": {"type": "number"} }, "required": ["n"] } } } ] ``` ## Step 2: The Agent Logic The agent needs to process the user's input, decide if a tool is needed, and handle the execution. When using Podstack’s serverless inference endpoints, you can pass these tool definitions directly to models like Llama 3 or Mixtral. Here is how you handle the tool calling loop: ```python import os import requests # Your Podstack API Key api_key = os.getenv("PODSTACK_API_KEY") def run_agent(prompt): messages = [{"role": "user", "content": prompt}] # 1. Ask the model for a response response = requests.post( "https://podstack.ai/api/v1/chat/completions", headers={"Authorization": f"Bearer {api_key}"}, json={ "model": "podstack/kimi-k3", "messages": messages, "tools": tools } ).json() message = response['choices'][0]['message'] # 2. Check if the model wants to call a tool if message.get("tool_calls"): for tool_call in message["tool_calls"]: func_name = tool_call["function"]["name"] args = tool_call["function"]["arguments"] # Execute the local function if func_name == "get_stock_price": result = get_stock_price(**args) elif func_name == "calculate_sqrt": result = calculate_sqrt(**args) # 3. Send the tool result back to the model messages.append(message) messages.append({ "role": "tool", "tool_call_id": tool_call["id"], "content": str(result) }) # 4. Get the final synthesized response final_response = requests.post( "https://podstack.ai/api/v1/chat/completions", headers={"Authorization": f"Bearer {api_key}"}, json={"model": "podstack/kimi-k3", "messages": messages} ).json() return final_response['choices'][0]['message']['content'] return message['content'] print(run_agent("What is the square root of 144 and the price of POD stock?")) ``` ## Step 3: Deploying as a GPU Function Running agents locally is fine for testing, but for production, you want low-latency execution and high availability. This is where Podstack shines. Instead of managing complex infrastructure, you can deploy your agent logic as a Python GPU function. Using the Podstack API, you can wrap your agent code and deploy it to an on-demand GPU instance. This allows your agent to handle heavy inference loads or run additional ML models (like embedding generation) alongside the tool calling logic. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Podstack handles the scaling automatically. You only pay for the seconds the GPU is active while processing your agent's requests. ## Practical Tips for Tool Calling 1. **Strict Schemas**: Ensure your tool descriptions are verbose. The LLM relies solely on the `description` field to understand when to use a tool. 2. **Error Handling**: If a tool fails (e.g., an API timeout), pass the error message back to the LLM. Often, the model can "self-correct" and try a different set of arguments. 3. **State Management**: For multi-turn conversations, ensure you maintain the message history correctly, including the `tool` role messages. 4. **Security**: Never give a tool direct access to `eval()` or sensitive file system commands without strict sanitization. ## Conclusion Building an AI agent is no longer a research project; it's an engineering task. By leveraging tool calling, you transform an LLM from a passive knowledge base into an active participant in your workflow. With Podstack, the transition from a local Python script to a production-grade agent is seamless. By using our per-second billing and serverless GPU functions, you can scale your agent's reasoning capabilities without the overhead of managing clusters. Ready to deploy? Grab your `PODSTACK_API_KEY` and start building the next generation of autonomous tools today. --- # Checkpointing long training runs so you never lose progress Learn how to implement robust checkpointing in PyTorch to prevent data loss and optimize costs during long-running GPU jobs on Podstack. Training · 2026-10-18 · 3 min read When training large-scale models, the primary threat to your budget and timeline isn't just a loss of accuracy—it's a loss of state. Whether it's an unexpected node failure, a network hiccup, or a preemptible instance reaching its time limit, an uncheckpointed training run can result in hours of wasted compute and hundreds of dollars down the drain. On a high-performance GPU cloud like Podstack, where resources are billed per second, every moment of lost progress is literal money off the table. Implementing a robust checkpointing strategy ensures that your jobs are resilient, resumeable, and reliable. ## Why Checkpointing Matters in Modern ML Checkpointing is the process of saving the current state of your model—including weights, optimizer states, and epoch counters—to persistent storage during training. In a serverless or job-based environment, this serves two critical functions: 1. **Fault Tolerance:** If a hardware error occurs, you can restart from the last saved state rather than starting from zero. 2. **Elasticity:** You can stop a job to switch to a different GPU tier or scale down, then resume seamlessly when resources are available. ## The Anatomy of a Proper Checkpoint A common mistake is saving only the model weights. To truly resume a training run without a "jump" in the loss curve, you must save the entire state dictionary. This includes: * **Model state:** The `state_dict` containing learned weights. * **Optimizer state:** Gradients, momentums, and learning rate schedules. * **Metadata:** Current epoch, global step, and best loss recorded so far. ## Implementing Checkpoints in PyTorch Here is a practical pattern for saving and loading checkpoints that integrates easily with Podstack jobs. ```python import torch import os def save_checkpoint(state, filename="checkpoint.pth.tar"): """Saves the training state to a file.""" print(f"=> Saving checkpoint to {filename}") torch.save(state, filename) def load_checkpoint(model, optimizer, filename="checkpoint.pth.tar"): """Loads the training state from a file if it exists.""" if os.path.isfile(filename): print(f"=> Loading checkpoint '{filename}'") checkpoint = torch.load(filename) model.load_state_dict(checkpoint['state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) epoch = checkpoint['epoch'] loss = checkpoint['loss'] print(f"=> Loaded checkpoint (epoch {epoch})") return epoch, loss else: print(f"=> No checkpoint found at '{filename}'") return 0, float('inf') # --- Inside your training loop --- # 1. Initialize model = MyModel().to(device) optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) # 2. Check for existing progress start_epoch, best_loss = load_checkpoint(model, optimizer) for epoch in range(start_epoch, num_epochs): train_one_epoch(model, optimizer) # 3. Save periodically (e.g., every epoch or 1000 steps) checkpoint_data = { 'epoch': epoch + 1, 'state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), 'loss': current_loss, } save_checkpoint(checkpoint_data) ``` ## Best Practices for Long Runs ### 1. The "Two-File" Strategy Always maintain a `latest_checkpoint.pth` and a `best_model.pth`. The latest checkpoint allows for resumption, while the best model ensures you don't keep a version that began to overfit or diverge. ### 2. Frequency vs. Overhead Saving a 5GB model every 60 seconds will throttle your training due to I/O overhead. Aim for a frequency that balances risk: if your job runs for 24 hours, checkpointing every 15–30 minutes is usually the "sweet spot" to minimize data loss without impacting performance. ### 3. Verification Before starting a long-running job, run a 2-epoch test. Ensure the checkpoint saves, stop the process, restart it, and verify that the loss at the start of epoch 3 matches the end of epoch 2. ## Automating with Podstack Podstack is designed for high-throughput GPU workflows. When you deploy a job using the Podstack API, your environment is provisioned instantly. To ensure your checkpoints survive between job restarts, you should leverage Podstack’s persistent volumes or remote storage hooks. When launching a job, you can pass your `PODSTACK_API_KEY` to your environment to allow your script to programmatically interact with Podstack’s storage layer or to trigger alerts if a checkpoint hasn't been updated in a specified window. Using the API, you can monitor your job’s output to ensure checkpoints are being written successfully: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` If a job is interrupted, Podstack’s per-second billing ensures you only paid for the work done. By simply resubmitting the job, your `load_checkpoint` logic will pull the state from your persistent volume, and you’ll pick up right where the hardware left off. ## Conclusion Checkpointing isn't just a safety net; it's a fundamental part of the machine learning lifecycle. By implementing a standardized save/load pattern and utilizing Podstack’s robust job infrastructure, you turn potential disasters into minor hiccups. Your models train faster, your costs stay predictable, and your progress is never lost. --- # Choosing context length vs cost for production LLMs Learn how to balance LLM accuracy and infrastructure costs by optimizing context windows and leveraging Podstack’s per-second GPU billing. Inference · 2026-10-15 · 4 min read Large Language Model (LLM) deployments are often caught in a tug-of-law between two opposing forces: the need for high-fidelity reasoning over massive datasets (long context) and the hard reality of inference budgets. As context windows expand from 8K to 128K and even 1M tokens, the cost implications scale quadratically or linearly depending on the architecture. For ML engineers, "maximum context" is rarely the right production setting. The goal is to find the "Goldilocks zone"—the minimum context length required to maintain accuracy while maximizing throughput and minimizing cost per request. ## The Relationship Between Context and Cost In a production environment, context length impacts your bottom line through two primary vectors: 1. **Memory Footprint:** The KV (Key-Value) cache grows with every token added to the prompt. A longer context requires more VRAM, which can force you onto larger, more expensive GPU instances or reduce your batch size, lowering overall throughput. 2. **Latency (Time to First Token):** While many modern GPUs handle long prompts efficiently, the pre-fill stage (processing the input) still scales with the number of tokens. High-context requests increase the "Time to First Token" (TTFT), impacting user experience. If you are using serverless endpoints, you likely pay per 1M tokens. If you are running dedicated GPU functions on a provider like Podstack, your cost is calculated by the second. In this model, longer context equals longer compute time per request, directly increasing your cost per inference. ## Step 1: Benchmark Accuracy Decay Before optimizing for cost, you must establish your "Context Floor." Most models exhibit "Lost in the Middle" phenomena, where performance degrades as the relevant information is buried deep in a massive prompt. Use a synthetic "needle in a haystack" test or a RAG evaluation framework (like Ragas) to measure at what point your model begins to hallucinate or fail. If your RAG system performs identical at 4K tokens versus 16K tokens, choosing 16K is essentially throwing money away. ## Step 2: Implement Dynamic Context Windowing Rather than hard-coding a limit, implement a dynamic truncation strategy. This involves prioritizing the most relevant chunks of data and discarding the rest. Here is a Python example of how to implement a token-aware context manager using `tiktoken` to ensure you stay within your budget before hitting the Podstack inference endpoint: ```python import tiktoken def create_budgeted_prompt(system_prompt, context_chunks, user_query, max_tokens=4096): encoding = tiktoken.encoding_for_model("gpt-4") # or your specific model # Reserve tokens for system prompt and query base_prompt = f"{system_prompt}\n\nQuery: {user_query}" base_len = len(encoding.encode(base_prompt)) available_tokens = max_tokens - base_len - 100 # 100 token buffer for completion selected_context = [] current_tokens = 0 for chunk in context_chunks: chunk_len = len(encoding.encode(chunk)) if current_tokens + chunk_len <= available_tokens: selected_context.append(chunk) current_tokens += chunk_len else: break final_prompt = "\n".join(selected_context) + "\n" + base_prompt return final_prompt # Usage with Podstack environment import os import requests api_key = os.getenv("PODSTACK_API_KEY") prompt = create_budgeted_prompt("You are a helpful assistant.", ["chunk1...", "chunk2..."], "What is the ROI?", max_tokens=2048) # Deploy this as a Podstack GPU function to keep costs low ``` ## Step 3: Use Prompt Caching If you are sending the same large context (e.g., a massive legal document or a codebase) to multiple users, look for models and providers that support prompt caching. By caching the KV cache of the prefix, you can reduce the cost of subsequent requests by up to 90%. On Podstack, you can achieve this by keeping your GPU function "warm." Since you are billed per second, a warm container with the model and context pre-loaded into VRAM reduces the total compute time required for subsequent tokens. ## Step 4: Scale the GPU to the Context Don't use an H100 for a task that requires a 2K context window. Conversely, don't try to cram a 128K context window into a GPU with 16GB of VRAM, as the swap-to-system-memory overhead will skyrocket your billing duration. - **0-8K Tokens:** Mid-tier GPUs (e.g., A10 or L4) are usually sufficient and highly cost-effective. - **8K-32K Tokens:** High-memory variants (e.g., A100 40GB) balance speed and cost. - **32K+ Tokens:** A100 80GB or H100 units are necessary to maintain acceptable latency. ## Optimizing Context on Podstack Podstack is designed to make this balancing act easier. Because Podstack provides on-demand GPUs billed per second, you have the flexibility to deploy specific models for specific context lengths. 1. **Deploy as a Job:** For large batch processing of long-context documents, use `podstack run`. This ensures you only pay for the exact seconds it takes to process the batch. 2. **Serverless Inference:** For user-facing apps, deploy your model as an endpoint. Use the Podstack API to monitor usage and adjust your VRAM requirements dynamically. To get started, authenticate your API: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` By strictly managing your context length and matching it to the right hardware on a per-second billing model, you can reduce production LLM costs by 40-60% without sacrificing the quality of your AI’s outputs. --- # Choosing the right GPU for training: A100 vs H100 vs H200 vs B200 Compare A100, H100, H200, and B200 GPUs to find the optimal balance of VRAM, bandwidth, and FP8 compute for your ML training workloads. Infrastructure · 2026-10-12 · 4 min read As the scale of Large Language Models (LLMs) and generative AI grows, the hardware bottleneck becomes the most significant factor in your iteration speed. While the H100 has been the industry workhorse for the past year, the landscape is shifting with the arrival of the H200 and the massive architectural leap of the Blackwell (B200) series. Choosing the right GPU isn't just about finding the highest VRAM; it's about balancing memory bandwidth, interconnect speeds, and cost-per-step. Here is a technical breakdown of how to choose between the A100, H100, H200, and B200 for your next training run. ## Comparing the Hardware Architecture When evaluating GPUs for training, three metrics matter most: **FP8/FP16 TFLOPS** (compute speed), **Memory Capacity** (how large a model/batch fits), and **Memory Bandwidth** (how fast data moves from VRAM to the cores). 1. **A100 (Ampere):** The reliable baseline. With 80GB of HBM2e memory and 2TB/s bandwidth, it is still highly effective for fine-tuning models under 30B parameters or small-scale pre-training. However, it lacks the Transformer Engine found in newer generations. 2. **H100 (Hopper):** The current gold standard. It introduced the Transformer Engine, which uses FP8 precision to provide up to 3x-4x speedups over the A100 for training. With 80GB HBM3 and 3.35TB/s bandwidth, it’s the go-to for mid-to-large-scale training. 3. **H200 (Hopper Evolution):** The H200 uses the same architecture as the H100 but upgrades the memory to 141GB of HBM3e with 4.8TB/s bandwidth. This is a game-changer for memory-bound workloads and allows for larger batch sizes without needing to shard models across as many nodes. 4. **B200 (Blackwell):** The new frontier. Blackwell offers a massive jump in compute density. With 192GB of HBM3e memory and 8TB/s bandwidth, it is designed for trillion-parameter models. Its second-generation Transformer Engine supports FP4, potentially doubling training throughput again compared to H100. ## When to Use Which? ### Use A100s if: * You are performing LoRA or QLoRA fine-tuning on models like Llama 3 8B. * You are on a strict budget and your workload is not compute-bound. * You are running traditional CV (Computer Vision) or NLP tasks that don't benefit from the FP8 Transformer Engine. ### Use H100s if: * You are pre-training or full-parameter fine-tuning models 13B–70B. * You need the 700W TDP performance to minimize wall-clock time. * You are utilizing libraries like DeepSpeed or FlashAttention-3 that are optimized for Hopper. ### Use H200s or B200s if: * You are hitting "Out of Memory" (OOM) errors on 80GB cards. * You are training ultra-long context window models (e.g., 128k+ tokens) where KV cache and activations grow exponentially. * You are training Mixture-of-Experts (MoE) models that require massive memory throughput to keep the sparse kernels fed. ## Practical Setup: Checking Performance Before committing to a long-running job, you should profile your kernel utilization. On Podstack, you can quickly spin up a container to benchmark your specific model. Once you have your `PODSTACK_API_KEY` set in your environment, you can launch a job to check your environment’s compute capability and memory: ```python import torch def check_gpu_readiness(): if not torch.cuda.is_available(): print("No GPU found.") return major, minor = torch.cuda.get_device_capability() name = torch.cuda.get_device_name() total_mem = torch.cuda.get_device_properties(0).total_memory / 1e9 print(f"Device: {name}") print(f"Compute Capability: {major}.{minor}") print(f"Total VRAM: {total_mem:.2f} GB") # Check for Transformer Engine support (Hopper+) if major >= 9: print("FP8 Transformer Engine supported.") else: print("Standard FP16/BF16 training recommended.") if __name__ == "__main__": check_gpu_readiness() ``` ## Practical Tips for Efficiency 1. **Don't over-provision VRAM:** If your model and batch size fit comfortably in 40GB, using an H200 (141GB) is a waste of capital unless you plan to significantly increase the batch size to utilize the extra bandwidth. 2. **Interconnect is Key:** For multi-node training, the GPU type is only half the battle. Ensure you are utilizing NVLink for intra-node communication. 3. **Leverage FP8:** If you move to H100s or newer, ensure your training framework (like PyTorch or Hugging Face `accelerate`) is configured to use the Transformer Engine. Running pure FP16 on an H100 is leaving 50% of the performance on the table. ## Training on Podstack Podstack makes switching between these architectures seamless. Instead of managing complex hardware reservations, you can define your requirements in a simple function or job spec and let our orchestrator handle the rest. With the Podstack API, you can deploy a training script to an H100 cluster with a single command: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Because Podstack bills per second, you can scale up to B200s for the heavy lifting of your training run and scale back down to A100s for lower-intensity evaluation tasks, ensuring you never pay for idle flagship silicon. --- # Chunking strategies that actually improve RAG answers Learn how to move beyond naive character splitting to semantic chunking and parent-document retrieval to drastically improve your RAG pipeline accuracy. RAG · 2026-10-09 · 3 min read Most developers starting with Retrieval-Augmented Generation (RAG) focus heavily on picking the "right" vector database or the largest embedding model. However, the quality of your RAG pipeline is often decided much earlier in the process: during chunking. If your chunks are too small, they lack the context required to answer a query. If they are too large, they introduce noise and exceed the context window of your LLM. To move beyond "naive RAG," you need a chunking strategy that respects the semantic structure of your data. ## 1. Moving Beyond Fixed-Size Windowing The default approach for many is character-based splitting with a fixed overlap (e.g., 500 characters with a 50-character overlap). While simple, this often cuts through the middle of a critical sentence or a code block, rendering the embedding "muddied." To improve performance, switch to **Recursive Character Splitting**. This method uses a hierarchy of separators—starting with double newlines (paragraphs), then single newlines, then spaces. This keeps related sentences together, ensuring that each chunk represents a complete thought. ## 2. Semantic Chunking with Embeddings If you want your chunks to be truly meaningful, stop splitting by character count and start splitting by meaning. Semantic chunking uses an embedding model to calculate the "distance" between subsequent sentences. When the difference in meaning between Sentence A and Sentence B exceeds a certain threshold, a new chunk is created. This ensures that a chunk about "database migration" doesn't accidentally bleed into a paragraph about "frontend styling" just because they happened to be near each other in the source PDF. ## 3. The "Small-to-Big" Strategy (Parent Document Retrieval) One of the most effective patterns for high-accuracy RAG is decoupling the data used for *retrieval* from the data used for *synthesis*. In this strategy, you break your document into very small "child" chunks (e.g., 100-200 tokens). These small chunks are easier for embedding models to match against specific queries. However, when a match is found, you don't send the tiny chunk to the LLM. Instead, you retrieve the "parent" chunk (the larger paragraph or section it came from) and provide that to the LLM. This gives the model the full context it needs to provide a nuanced answer. ## 4. Implementation Example: Semantic Splitting Below is a practical way to implement a logic-heavy chunking task. Since semantic splitting requires running an embedding model for every sentence pair, it is computationally expensive. This is where offloading the task to a GPU-accelerated function becomes necessary. ```python import os from podstack import Podstack # Initialize Podstack client client = Podstack(api_key=os.getenv("PODSTACK_API_KEY")) @client.gpu_function(gpu="T4") def semantic_chunker(text: str): from sentence_transformers import SentenceTransformer import numpy as np from sklearn.metrics.pairwise import cosine_similarity model = SentenceTransformer('all-MiniLM-L6-v2') sentences = text.split('. ') embeddings = model.encode(sentences) chunks = [] current_chunk = [sentences[0]] for i in range(1, len(sentences)): # Calculate similarity between adjacent sentences sim = cosine_similarity([embeddings[i-1]], [embeddings[i]])[0][0] # If similarity drops below 0.7, start a new chunk if sim < 0.7: chunks.append(" ".join(current_chunk)) current_chunk = [sentences[i]] else: current_chunk.append(sentences[i]) chunks.append(" ".join(current_chunk)) return chunks # Run the job on Podstack's serverless infrastructure document = "Your long technical documentation here..." result = semantic_chunker(document) print(f"Created {len(result)} semantic chunks.") ``` ## 5. Practical Tips for Production * **Respect Document Syntax:** If you are RAG-ing over a codebase, use a language-aware splitter (like tree-sitter) that respects function and class boundaries. * **Contextual Headers:** For long documents, prepend the "Section Title" or "Document Title" to every chunk. This gives the embedding model more signals to work with. * **The Overlap Rule:** If you aren't using semantic splitting, always maintain at least a 10-15% overlap. This ensures that the transition between two chunks doesn't lose the relationship between them. ## Scaling Chunking on Podstack Processing thousands of documents with semantic chunking or high-dimensional embedding models can be slow on standard CPUs. Podstack allows you to deploy these processing pipelines as serverless GPU functions, billed only for the seconds they are active. By using the Podstack API, you can easily deploy your chunking logic: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` This approach allows you to scale your ingestion pipeline horizontally. Whether you are processing ten PDFs or ten thousand, Podstack handles the infrastructure, providing on-demand GPU power so your RAG application stays responsive and accurate. By moving from static chunks to context-aware strategies, you significantly reduce "hallucinations" caused by fragmented context, resulting in a RAG system that users can actually trust. --- # Cleaning and deduplicating web-scale text datasets Learn how to build a scalable text cleaning pipeline using MinHash LSH and heuristic filters to prepare web-scale datasets for LLM training on Podstack. Data · 2026-10-06 · 3 min read Processing web-scale text—think Common Crawl or massive Discord scrapes—is the first high-stakes hurdle in training a Large Language Model (LLM). If you feed your model "garbage" (boilerplate, HTML tags, or thousands of copies of the same terms-of-service agreement), your loss curves will stagnate, and your inference results will suffer from repetitive hallucinations. Cleaning and deduplicating at scale isn't just about regex; it’s a compute-intensive pipeline that requires massive parallelization. In this post, we’ll walk through a modern workflow for preparing high-quality pre-training data using MinHash LSH for deduplication and heuristic filtering for quality. ## The Architecture of a Cleaning Pipeline A robust pipeline generally follows three phases: 1. **Normalization and Heuristic Filtering:** Removing non-textual noise and low-quality documents. 2. **Fuzzy Deduplication:** Identifying documents that are nearly identical (e.g., the same news article on different domains). 3. **Final Formatting:** Tokenization or conversion to a high-throughput format like Parquet or WebDataset. ## Step 1: Heuristic Quality Filtering Before running expensive deduplication algorithms, you should prune the "easy" noise. High-quality text usually has a specific distribution of characters and words. Common filters include: * **Symbol-to-word ratio:** If more than 10% of a document is composed of symbols (#, $, %), it’s likely code or junk metadata. * **Language Identification:** Use a fast model like `fastText` to drop documents that don't match your target language. * **Gopher-style rules:** Remove documents that are too short (under 200 characters) or too long, and those with an unusually high "stopword" density. ## Step 2: Global Deduplication with MinHash LSH Exact deduplication (hashing a whole string) misses 90% of duplicates in web data because of small changes like timestamps or "Related Articles" sidebars. Instead, we use **MinHash Locality Sensitive Hashing (LSH)**. The process involves: 1. **Shingling:** Breaking text into overlapping n-grams. 2. **MinHashing:** Converting shingles into a fixed-size signature (e.g., 128 integers). 3. **LSH:** Grouping signatures into "bands" to find candidates that have a high Jaccard similarity. ## Implementing a GPU-Accelerated Worker While MinHash is often done on CPUs, we can use GPUs to accelerate the signature generation and the final embedding-based semantic deduplication. Below is a conceptual worker script that processes a chunk of data, which you can deploy as a job. ```python import os import datasketch from datasketch import MinHash, MinHashLSH import pandas as pd def process_batch(file_path): # Load a subset of your web-scale dataset df = pd.read_parquet(file_path) # 1. Heuristic Filter: Minimum length and alpha-numeric check df = df[df['text'].str.len() > 250] # 2. MinHash Generation signatures = [] for text in df['text']: m = MinHash(num_perm=128) # Create shingles (3-grams) shingles = [text[i:i+3] for i in range(len(text)-2)] for s in shingles: m.update(s.encode('utf8')) signatures.append(m) # In a real pipeline, you would yield these signatures to a # global LSH index or save them to a vector store. return signatures if __name__ == "__main__": # Example: Processing a local shard results = process_batch("data_shard_001.parquet") print(f"Processed {len(results)} valid documents.") ``` ## Practical Tips for Scale * **Memory Management:** When dealing with billions of documents, you cannot fit the LSH index in RAM. Use a distributed key-value store or a disk-backed storage for the LSH buckets. * **Semantic Deduplication:** For high-quality datasets (like fine-tuning sets), MinHash isn't enough. Use a GPU to generate embeddings (e.g., with BGE or RoBERTa) and run a cosine similarity check. This catches documents that say the same thing using different words. * **The "Boilerplate" Problem:** Use libraries like `trafilatura` or `resiliparse` to extract main content from HTML. Standard regex often leaves behind navigation menus that pollute your dataset. ## Running the Pipeline on Podstack Processing terabytes of text is a classic "burst" workload. You don't want a cluster running 24/7; you want 50 GPUs for three hours, then zero. With **Podstack**, you can wrap your cleaning logic into a Python function and trigger it as an on-demand Job. Because Podstack bills by the second, you only pay for the exact duration of your data crunching. First, ensure your environment is set up: ```bash export PODSTACK_API_KEY="your_api_key_here" ``` You can then use the Podstack API to deploy your cleaning script as a job. This allows you to spin up high-memory GPU instances to handle the MinHash signatures and embedding generations without managing infrastructure: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` By leveraging serverless GPU functions, you can scale your deduplication horizontally. One function can handle the heuristic filtering, while another—backed by a powerful GPU—handles the semantic similarity checks. This modular approach ensures that your pre-training data is pristine, leading to faster convergence and a more capable model. --- # Connecting AI agents to cloud GPUs with MCP Learn how to connect AI agents to high-performance cloud GPUs using the Model Context Protocol (MCP) and Podstack for on-demand, per-second billed compute. Agents · 2026-10-03 · 4 min read Connecting AI agents to cloud GPUs has traditionally been a clunky process involving manual infrastructure provisioning, long-running SSH sessions, and fragile REST wrappers. For ML engineers, this friction often means agents are limited to simple API calls rather than performing heavy-duty computation like fine-tuning, video rendering, or large-scale inference. The Model Context Protocol (MCP) changes this by providing a standardized way for LLMs to interface with external tools. By combining MCP with a high-performance GPU cloud, you can give your agents "superpowers"—allowing them to spin up H100s or A100s, execute CUDA kernels, and tear them down automatically when the task is complete. In this guide, we’ll walk through how to build an MCP server that allows an agent to run Python-based GPU workloads on Podstack. ## The Architecture: Why MCP? The Model Context Protocol acts as a bridge between the agent (the "client") and the compute resource (the "server"). Instead of writing custom logic for every agent framework, MCP allows you to define a set of tools that any compatible agent—like Claude Desktop or a custom LangChain implementation—can understand. When an agent needs to process an image with a specific diffusion model or run a heavy tensor calculation, it calls a tool defined in your MCP server. That server, in turn, invokes the Podstack API to launch a per-second billed GPU job. ## Prerequisites To follow along, you will need: - A Podstack account and an API key. - The Podstack API installed (`pip install podstack-sdk`). - The Python MCP SDK (`pip install mcp`). First, authenticate your environment: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` ## Building the MCP GPU Server We will create a Python-based MCP server that exposes a tool called `run_gpu_task`. This tool will take Python code as input and execute it on a remote GPU container via Podstack. ```python import os import subprocess from mcp.server.fastmcp import FastMCP # Initialize FastMCP server mcp = FastMCP("PodstackGPU") @mcp.tool() def execute_gpu_code(script_contents: str, gpu_type: str = "A100"): """ Executes Python code on a Podstack cloud GPU. Args: script_contents: The Python code to run on the GPU. gpu_type: The type of GPU required (e.g., 'A100', 'H100', 'L40'). """ # Create a temporary file for the script with open("task.py", "w") as f: f.write(script_contents) # Use the Podstack API to run a per-second job # This command uploads the script and executes it in a standard ML environment try: result = subprocess.run( ["podstack", "run", "--gpu", gpu_type, "--file", "task.py"], capture_output=True, text=True, check=True, env={**os.environ, "PODSTACK_API_KEY": os.getenv("PODSTACK_API_KEY")} ) return {"status": "success", "output": result.stdout} except subprocess.CalledProcessError as e: return {"status": "error", "error": e.stderr} if __name__ == "__main__": mcp.run() ``` ## Connecting the Agent Once your MCP server is running, you can connect it to an agent. If you are using an agentic IDE or the Claude Desktop client, you add your server to the configuration file (usually `claude_desktop_config.json`): ```json { "mcpServers": { "podstack": { "command": "python", "args": ["/path/to/your/mcp_server.py"], "env": { "PODSTACK_API_KEY": "your_api_key_here" } } } } ``` Now, your agent can "reason" about when it needs a GPU. If you ask the agent, "Compare the execution time of a large matrix multiplication on a CPU vs an A100," the agent will generate the PyTorch code, call your `execute_gpu_code` tool, and receive the real-world results from Podstack. ## Practical Tips for Production 1. **Environment Syncing**: Podstack allows you to define custom Docker images. If your agent needs specific libraries (like `diffusers` or `vLLM`), pre-build an image and include the `--image` flag in your subprocess call to minimize cold-start times. 2. **State Management**: GPU jobs are often ephemeral. If your agent is performing a multi-step task (e.g., training for 10 minutes and then running inference), use Podstack's persistent volumes to store model weights between jobs. 3. **Cost Controls**: Because Podstack bills per second, ensure your MCP server includes a timeout or a maximum spend limit to prevent an autonomous agent from accidentally running a massive cluster for longer than intended. 4. **Security**: Always sanitize the code inputs if your MCP server is exposed beyond a local environment. Use Podstack’s isolated job environments to ensure the agent’s code cannot escape the container. ## Scaling with Podstack Using MCP with Podstack bridges the gap between LLM intelligence and raw compute power. By leveraging Podstack’s serverless inference and on-demand jobs, you don't have to manage a pool of idling GPUs. The agent requests compute, Podstack provisions it in seconds, bills you only for the duration of the execution, and releases the hardware immediately. Whether you are building an autonomous ML researcher or a creative coding assistant, the combination of a standardized protocol like MCP and a high-performance cloud like Podstack ensures your agents are never bottlenecked by hardware availability. --- # Cost-optimizing an AI startup's GPU bill Learn how to reduce your AI startup’s overhead by shifting from always-on instances to task-based execution and per-second billing models. Business · 2026-09-30 · 4 min read Managing the burn rate of an AI startup often feels like a balancing act between shipping state-of-the-art models and keeping the lights on. For most ML-heavy companies, the GPU bill is the single largest line item after payroll. The "always-on" approach to compute that worked for web microservices is a recipe for bankruptcy when applied to H100s. Cost optimization in the GPU era isn't just about finding the cheapest hourly rate; it’s about architecting your infrastructure to ensure you never pay for an idle transistor. Here is a practical framework for slashing your GPU spend without slowing down your development velocity. ## 1. Move from Instances to Task-Based Execution The most common source of waste is the "Development Instance Syndrome"—leaving a powerful GPU instance running overnight because you were in the middle of a Jupyter notebook or a training run. Instead of thinking in terms of virtual machines, start thinking in terms of **Jobs**. By containerizing your training scripts and launching them as discrete tasks, you ensure the GPU is provisioned exactly when the code starts and decommissioned the millisecond the process exits. On a per-second billing model, this shift alone can save 30-50% of monthly costs by eliminating the "idle gap" between experiments. ## 2. Implement Serverless Inference for Low-Traffic Models Not every model needs a dedicated, warm instance 24/7. Internal tools, asynchronous batch processing, and early-stage features often have "spiky" traffic. By using serverless endpoints, you can scale to zero when no requests are coming in. The cold start trade-off is often negligible for background tasks or internal LLM evaluations, but the cost savings are absolute. You transition from paying for 720 hours a month to paying for the 15 minutes of actual compute used. ## 3. Right-size your VRAM Requirements Startups often default to the most powerful GPU available (like an H100 or A100 80GB) because it’s "safe." However, many tasks—especially fine-tuning smaller models like Llama 3 8B or running vision transformers—can run comfortably on mid-tier GPUs with 24GB of VRAM. Before scaling up, profile your memory usage. If your training job only peaks at 16GB of VRAM, moving from an A100 to a more cost-effective L4 or A10G can cut your costs by more than half without a proportional hit to performance. ## 4. Programmatic Resource Management Manually spinning up resources via a GUI is the enemy of efficiency. To truly optimize, your CI/CD pipeline or your local development workflow should handle resource lifecycle management. Using an API tool to trigger remote GPU functions allows you to treat high-end hardware as a simple Python decorator. Here is how you can leverage a programmatic approach to run a heavy computation and exit immediately: ```python import os from podstack import RemoteTask # Configure your environment os.environ["PODSTACK_API_KEY"] = "your_secret_key_here" def train_model(epochs=10, batch_size=32): # Your heavy PyTorch/JAX code here print(f"Training started with {epochs} epochs...") # ... logic ... return "Model weights saved to bucket." if __name__ == "__main__": # Offload execution to a remote GPU instantly # This provisions the GPU, runs the function, and shuts down task = RemoteTask( function=train_model, gpu="A100", env_vars={"DATASET_URL": "s3://my-data/train"} ) result = task.run(epochs=50) print(f"Result: {result}") ``` ## 5. Cold Storage and Data Locality Keeping high-performance NVMe storage attached to a stopped instance still incurs costs. A better pattern is to use object storage for your datasets and model checkpoints, pulling them into the ephemeral GPU environment only when a job starts. Combine this with a "Checkpoint and Resume" strategy. If you are running long-duration training, ensure your code saves state frequently. This allows you to use interruptible capacity or short-lived jobs without losing progress. ## Optimization with Podstack Podstack was built specifically to solve these efficiency bottlenecks for AI teams. Instead of managing complex infrastructure, you use the Podstack API to deploy jobs and inference endpoints that bill you only for the seconds they are active. By moving your workloads to Podstack, you gain: * **Per-second billing:** Stop paying for the minutes it takes to spin down or the hours an instance sits idle. * **GPU Functions:** Use Python decorators to send specific functions to a GPU, keeping your local dev environment lightweight. * **Serverless Scale:** Deploy your models as endpoints that scale automatically based on demand, including scaling to zero. To get started, install the SDK and authenticate: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Efficiency isn't just about saving money; it's about having more "shots on goal" for your AI research. By optimizing your GPU spend, you extend your runway and ensure that every dollar of your cloud budget is directly contributing to model performance. --- # Designing reliable multi-step agents with planning loops Learn how to build production-grade AI agents by implementing planning loops, structured state management, and serverless GPU execution for maximum reliability. Agents · 2026-09-27 · 3 min read The promise of AI agents lies in their ability to reason through complex, open-ended tasks. However, anyone who has deployed an agent to production knows the "stochastic trap": the more steps an agent takes, the higher the probability of a logic drift or a permanent hallucination. Building a reliable multi-step agent requires moving beyond simple linear chains. To achieve production-grade stability, we must implement **planning loops**—architectures that explicitly separate intent from execution and include a feedback mechanism to correct course mid-flight. ## 1. The Anatomy of a Planning Loop A robust planning loop consists of three distinct phases that repeat until the task is resolved: 1. **The Planner:** Given a high-level objective, it decomposes the task into a structured sequence of atomic sub-steps (a Directed Acyclic Graph or a simple list). 2. **The Executor:** It processes the current step using tools (APIs, code execution, or specialized GPU functions). 3. **The Critic/Refiner:** It evaluates the output of the executor against the original plan. If the output is an error or unexpected, it updates the plan instead of blindly moving to the next step. By isolating these phases, you prevent the agent from "looping" on a single failure point without context. ## 2. Implementing State-Aware Execution Reliability depends on how you manage state. In a multi-step environment, the "State" should include the original goal, the steps completed, the current plan, and the observations from previous tools. Using Python, you can define a structured loop that leverages remote GPU functions for heavy lifting (like vision processing or complex embedding searches). ```python import os from podstack import Client # Initialize the Podstack client client = Client(api_key=os.getenv("PODSTACK_API_KEY")) def run_agent_loop(objective: str): state = { "objective": objective, "plan": [], "completed": [], "current_observation": "" } while True: # Phase 1: Planning/Re-planning # We call a lightweight LLM to update the plan based on current state state["plan"] = planner_function(state) if not state["plan"] or "FINISH" in state["plan"][0]: break current_step = state["plan"].pop(0) # Phase 2: Execution # For compute-heavy tasks, offload to a Podstack GPU function try: # Assume 'analyze_video_frame' is a pre-deployed Podstack endpoint observation = client.run( "analyze_video_frame", image_data=state["current_observation"] ) state["completed"].append({"step": current_step, "result": observation}) state["current_observation"] = observation except Exception as e: # Phase 3: Error Handling as a Plan Update state["current_observation"] = f"Error at {current_step}: {str(e)}" print(f"Retrying and re-planning due to: {e}") return state["completed"] ``` ## 3. Practical Tips for Reliability ### Atomic Tool Design Ensure each tool (or GPU function) does exactly one thing and returns a predictable schema. If an agent calls a tool to "Analyze Data," it should return a structured JSON, not a rambling paragraph. This makes it easier for the "Critic" phase to parse success or failure. ### Time-to-Compute vs. Time-to-Think Multi-step agents are latent by nature. To maintain responsiveness, use serverless GPU inference for the "Executor" phase. This allows the agent to spin up massive compute (like an A100 or H100) for a 2-second inference task and shut down immediately, keeping costs per-second rather than per-hour. ### The "Circuit Breaker" Pattern Always implement a maximum loop count. If an agent hasn't reached a "FINISH" state within 10 iterations, force a graceful failure and log the state. This prevents infinite loops that drain your API credits and compute budget. ## 4. Scaling the Execution Layer In a multi-step agent, the bottleneck is often the execution of specialized models (e.g., running a fine-tuned Whisper model for audio or a Llama-3-70B for reasoning). Managing the infrastructure for these models while the agent waits for the next turn is inefficient. This is where a serverless GPU approach becomes essential. Instead of keeping a GPU warm 24/7, your agent triggers a job or a function call only when the "Executor" phase is active. ## Deploying on Podstack Podstack is designed specifically for this type of agentic workflow. By using the Podstack API, you can deploy your specialized tools as serverless functions that scale to zero when your agent is in the "thinking" or "planning" phase. 1. **Deploy your tools:** Wrap your heavy ML logic in a Python function and deploy it: ```text Podstack does not ship a command-line interface. Deploy from the console or call the API at https://podstack.ai/api/v1. ``` 2. **Trigger from the loop:** Use the `PODSTACK_API_KEY` to authenticate your agent's requests to these tools. 3. **Per-second billing:** Since agents often have "dead time" between steps, Podstack’s per-second billing ensures you only pay for the exact duration the GPU is processing a step. By decoupling the planning logic (running on a lightweight CPU) from the execution logic (running on Podstack GPUs), you create an architecture that is both cost-effective and highly reliable. --- # Direct Preference Optimization (DPO) in practice Learn how to implement Direct Preference Optimization (DPO) to align LLMs with human preferences using TRL and on-demand GPUs. Training · 2026-09-24 · 4 min read While Supervised Fine-Tuning (SFT) is the standard first step in training Large Language Models (LLMs), it often falls short of aligning a model with specific human preferences or complex stylistic nuances. Traditionally, RLHF (Reinforcement Learning from Human Feedback) was the solution, but its complexity—requiring the training of a separate reward model and stable PPO optimization—made it a headache for many engineering teams. Enter **Direct Preference Optimization (DPO)**. DPO bypasses the reward model entirely, treating the alignment problem as a simple binary classification task. By using the log probabilities of a "chosen" response versus a "rejected" response, you can fine-tune your model to prefer the former. In this guide, we will walk through the practical implementation of DPO, focusing on how to prepare your data and execute the training loop efficiently. ## The DPO Workflow DPO requires a pre-trained model that has already undergone SFT. Attempting DPO on a base model (like raw Llama 3) without an initial SFT phase usually leads to poor convergence. The core of the process involves three components: 1. **The Reference Model:** A frozen copy of your SFT model. 2. **The Policy Model:** The model you are actively training. 3. **The Dataset:** A set of triplets consisting of a `prompt`, a `chosen` response, and a `rejected` response. The goal is to maximize the likelihood of the chosen response relative to the rejected response, while ensuring the policy model doesn't drift too far from the reference model (controlled by a hyperparameter $\beta$). ## Step 1: Data Preparation Your dataset must be formatted specifically for preference learning. Modern libraries like `trl` (Transformer Reinforcement Learning) expect a structure similar to this: ```json [ { "prompt": "Explain quantum entanglement to a five-year-old.", "chosen": "Imagine you have two magic socks. If you put one on your left foot, the other one automatically knows to become a right-foot sock, no matter how far away it is!", "rejected": "Quantum entanglement is a physical phenomenon that occurs when a group of particles are generated or interact such that the quantum state of each particle cannot be described independently." } ] ``` ## Step 2: Implementation with TRL The most efficient way to run DPO is using the `DPOTrainer` from the Hugging Face `trl` library. This abstracts away the complex loss calculation. Below is a Python snippet to initialize the trainer. ```python from trl import DPOTrainer from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments from datasets import load_dataset # Load your SFT-tuned model model_id = "./my-sft-model" model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto") ref_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto") tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.pad_token = tokenizer.eos_token dataset = load_dataset("json", data_files="preferences.jsonl", split="train") training_args = TrainingArguments( output_dir="./dpo-output", per_device_train_batch_size=4, learning_rate=5e-7, # DPO typically requires a much lower LR than SFT gradient_accumulation_steps=4, logging_steps=10, max_steps=500, bf16=True, # Use bfloat16 for stability on modern GPUs ) dpo_trainer = DPOTrainer( model, ref_model, args=training_args, beta=0.1, # The KL divergence penalty weight train_dataset=dataset, tokenizer=tokenizer, max_prompt_length=512, max_length=1024, ) dpo_trainer.train() ``` ## Practical Tips for DPO * **Beta Tuning:** The $\beta$ parameter (usually between 0.1 and 0.5) controls how much you trust your reference model. A smaller $\beta$ allows the model to deviate more to satisfy the preference data, while a larger $\beta$ keeps the model closer to the original SFT behavior. * **Low Learning Rates:** DPO is sensitive. While SFT might use $2e-5$, DPO often performs better at $5e-7$ or $1e-6$. * **Avoid Overfitting:** If your model starts generating repetitive text or "loses its mind" (collapse), you likely have too many epochs or your $\beta$ is too low. * **Reference Model Offloading:** Loading two copies of the same model (Policy and Reference) doubles your VRAM usage. Use 4-bit quantization (bitsandbytes) or PEFT/LoRA to fit the training on a single GPU. ## Running DPO on Podstack DPO is computationally intensive because it requires keeping two models in memory. On Podstack, you can spin up high-VRAM GPUs (like the H100 or A100) on-demand to handle this overhead without paying for idle time. To get started, ensure you have your `PODSTACK_API_KEY` exported in your environment. You can then use the Podstack API to launch your training script as a job. This is ideal for DPO because you can define the exact hardware requirements in a simple configuration and let the job run to completion. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` With Podstack’s per-second billing, you only pay for the duration of the fine-tuning. Once the job finishes, the GPU is released, and your weights are saved to your persistent volume. This makes iterative alignment—where you might run several DPO experiments with different $\beta$ values—highly cost-effective. ## Conclusion Direct Preference Optimization has democratized model alignment. By shifting the problem from reinforcement learning to supervised classification, it allows ML engineers to refine model behavior with significantly less friction. By combining the `trl` library with the elastic, high-performance compute available on Podstack, you can move from a base SFT model to a highly aligned, production-ready assistant in a matter of hours. --- # Distributed data parallel training across 8 GPUs Learn how to implement PyTorch Distributed Data Parallel (DDP) to scale your training across 8 GPUs and launch it efficiently using the Podstack API. Training · 2026-09-21 · 3 min read Distributed training is no longer a luxury reserved for massive research labs; it is a necessity for anyone fine-tuning large language models (LLMs) or training computer vision models on massive datasets. When a single GPU becomes a bottleneck for memory or compute, moving to a Multi-GPU setup using Distributed Data Parallel (DDP) is the logical next step. In this guide, we will walk through the mechanics of scaling a PyTorch training script from a single card to an 8-GPU node. We will focus on the practical implementation using PyTorch’s `DistributedDataParallel` and how to orchestrate this on Podstack’s high-performance infrastructure. ## Why Distributed Data Parallel? Distributed Data Parallel (DDP) works by replicating your model across multiple GPUs. Each GPU receives a unique shard of the data batch, computes the gradients independently, and then synchronizes those gradients across all cards before the optimizer step. Compared to the older `DataParallel` (DP), DDP is significantly faster because it uses multi-processing instead of multi-threading, avoiding Python’s Global Interpreter Lock (GIL) and reducing overhead by using collective communication (NCCL). ## Step 1: Initialize the Process Group To coordinate 8 GPUs, PyTorch needs a backend to manage communication. For NVIDIA GPUs, `nccl` is the industry standard. Your script must initialize the distributed environment by identifying the "Rank" (the ID of the current GPU) and the "World Size" (the total number of GPUs). ```python import os import torch import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP def setup_distributed(): # These are typically set by the launcher rank = int(os.environ["RANK"]) world_size = int(os.environ["WORLD_SIZE"]) local_rank = int(os.environ["LOCAL_RANK"]) # Initialize the process group dist.init_process_group(backend="nccl", rank=rank, world_size=world_size) # Set the device for this process torch.cuda.set_device(local_rank) return local_rank def cleanup(): dist.destroy_process_group() ``` ## Step 2: Preparing the Data and Model When training on 8 GPUs, you cannot simply feed the same data to every card. You must use a `DistributedSampler` to ensure that each GPU sees a distinct subset of the dataset. ```python from torch.utils.data.distributed import DistributedSampler def train(): local_rank = setup_distributed() # Load your model and move to the specific GPU model = MyModel().to(local_rank) model = DDP(model, device_ids=[local_rank]) # Prepare dataset dataset = MyDataset() sampler = DistributedSampler(dataset, shuffle=True) dataloader = torch.utils.data.DataLoader( dataset, batch_size=32, sampler=sampler, num_workers=4 ) optimizer = torch.optim.AdamW(model.parameters(), lr=1e-4) for epoch in range(10): # Important: set epoch for the sampler to ensure different shuffling every time sampler.set_epoch(epoch) for inputs, targets in dataloader: inputs, targets = inputs.to(local_rank), targets.to(local_rank) optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, targets) loss.backward() optimizer.step() cleanup() ``` ## Step 3: Launching the Job While you can manually launch 8 processes, the most efficient way is to use the `torchrun` utility. This tool automatically sets the `RANK`, `WORLD_SIZE`, and `MASTER_ADDR` environment variables for you. To run this locally on an 8-GPU machine: ```bash torchrun --nproc_per_node=8 train_script.py ``` ## Practical Tips for 8-GPU Training 1. **Scale your Learning Rate:** When you move from 1 GPU to 8, your effective batch size increases by 8x. You often need to increase your learning rate (a common rule of thumb is the linear scaling rule) or use a warmup period to prevent divergence. 2. **Monitor GPU Utilization:** Ensure that your data loading isn't the bottleneck. If your GPUs are at 60% utilization, increase the `num_workers` in your `DataLoader`. 3. **Checkpointing:** When saving your model, ensure you only save from `rank 0`. Saving from all 8 processes simultaneously will cause file corruption and wasted I/O. ```python if dist.get_rank() == 0: torch.save(model.module.state_dict(), "model.pt") ``` ## Scaling on Podstack Provisioning 8-GPU nodes (such as H100s or A100s) can be complex, but Podstack simplifies this into a single command. With Podstack, you get per-second billing, meaning you only pay for the high-compute time required for your training run. First, ensure your environment is authenticated: ```bash export PODSTACK_API_KEY="your_api_key_here" ``` You can deploy your distributed training job using the Podstack API. By specifying a multi-GPU instance, Podstack handles the underlying drivers and networking required for NCCL to operate at peak performance. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Podstack’s serverless inference and GPU functions allow you to immediately transition from training to deployment. Once your 8-GPU training job completes and saves the weights to a persistent volume, you can spin up a serverless endpoint to serve the model without managing the underlying hardware. ## Conclusion Distributing your training across 8 GPUs reduces iteration time from days to hours. By using PyTorch DDP and offloading the infrastructure management to Podstack, you can focus on optimizing your model architecture rather than troubleshooting NVLink configurations or driver versions. Ready to scale? Spin up an 8-GPU instance on Podstack and start training in seconds. --- # Evaluating agents: success rates, cost and latency Learn how to measure and optimize AI agent performance using success rates, cost analysis, and latency metrics on high-performance GPU infrastructure. Agents · 2026-09-18 · 3 min read The rise of autonomous AI agents has shifted the engineering challenge from "how do we build it" to "how do we know if it actually works." Unlike traditional software, agents are non-deterministic. A slight change in your system prompt or the underlying GPU hardware can lead to cascading failures or unexpected cost spikes. For ML engineers deploying agents at scale, evaluation is not a one-time task—it is a continuous monitoring requirement. To build production-ready agents, you must move beyond vibes and start measuring three specific pillars: **Success Rate, Cost, and Latency.** ## The Evaluation Triad When evaluating an agent, you are looking for the "Pareto frontier"—the point where you get the highest possible success rate for the lowest cost and latency. 1. **Success Rate:** The percentage of tasks the agent completes correctly. This usually requires a "judge" (a stronger model or a deterministic test suite) to verify the output. 2. **Cost:** The total dollar amount spent on inference (input tokens, output tokens, and GPU uptime). 3. **Latency:** The "Time to First Token" (TTFT) and the total time taken to resolve the loop. In agentic workflows, latency compounds quickly with every tool call. ## Setting Up an Evaluation Pipeline To evaluate effectively, you need to run your agent against a "Golden Dataset"—a collection of prompts where the ideal outcome is known. ### Step 1: Define the Metrics Create a structured logging system. For every agent run, you should capture the raw trace. If you are using a serverless inference endpoint, you can extract these metrics from the response headers or the metadata object. ### Step 2: Running Parallel Evaluations Running evaluations sequentially is too slow. You should leverage on-demand GPU functions to trigger hundreds of agent simulations in parallel. Here is a Python example of how you might structure an evaluation script using a background worker pattern to test your agent's performance across different models or prompt versions: ```python import os import time from typing import Dict # Assume 'agent_runner' is your function deployed on Podstack def evaluate_agent(test_case: Dict, model_version: str): start_time = time.time() # Simulate agent logic or call your hosted endpoint # response = call_podstack_endpoint(test_case['prompt'], version=model_version) latency = time.time() - start_time # Logic to determine success (e.g., regex, LLM-as-a-judge, or unit test) success = verify_output(test_case['expected_output'], "actual_output") # Calculate cost based on token usage or execution time cost = calculate_usage(model_version, duration=latency) return { "success": success, "latency": latency, "cost": cost } # Practical tip: Log these to a central dashboard for every PR ``` ## Optimizing for the Metrics Once you have your baseline, the next step is optimization. * **To Improve Success Rate:** Implement "Reasoning Loops" (Chain of Thought). While this increases latency and cost, it significantly boosts the reliability of complex tool-calling. * **To Reduce Latency:** Move from large, general-purpose models to fine-tuned, smaller models (e.g., Llama-3-8B) hosted on dedicated V100s or A100s. By hosting your own inference endpoint, you eliminate the "cold start" and queuing delays often found in shared API services. * **To Reduce Cost:** Switch from per-token pricing to per-second GPU billing. For high-throughput agent tasks, renting a GPU for the exact duration of the job is often 40-60% cheaper than paying for millions of tokens on a public API. ## Scaling Evaluations with Podstack The bottleneck in agent evaluation is often the infrastructure. You need the ability to spin up 50 instances of your agent, run a test suite, and spin them down immediately to avoid wasting budget. Podstack is designed specifically for this workflow. By using the Podstack API, you can deploy your agent logic as a Python GPU function that scales automatically. 1. **Deploy your agent:** Use the console or the API. 2. **Secure your environment:** Set your `PODSTACK_API_KEY` to handle authenticated requests to your inference endpoints. 3. **Billed per second:** Because Podstack bills by the second, you can run massive evaluation batches without the overhead of maintaining a permanent cluster. You only pay for the time the GPU is actually crunching your agent's reasoning steps. Whether you are fine-tuning a model to reduce latency or testing new system prompts to boost success rates, having a high-performance GPU cloud allows you to iterate in minutes rather than hours. ## Final Practical Tips * **Version Everything:** Never run an eval on "latest." Always pin your model weights and your agent code version. * **Use a Judge:** For open-ended tasks, use a larger model to grade the smaller agent's output. It’s cheaper than manual human review. * **Monitor TTFT:** If your agent is user-facing, the Time to First Token is the most important latency metric for perceived speed. --- # Fine-tuning a small model to replace an expensive API Learn how to distill knowledge from large models into specialized 7B/8B models using Podstack's on-demand GPUs to slash API costs and latency. Training · 2026-09-15 · 4 min read Reducing API costs is a top priority for engineering teams moving from the prototyping phase to production. While GPT-4o or Claude 3.5 Sonnet are incredible generalists, they are often "overkill" for specific tasks like sentiment analysis, entity extraction, or structured data formatting. By fine-tuning a "small" model (like Llama 3 8B or Mistral 7B) on your specific task data, you can often achieve parity with larger models at a fraction of the latency and cost. In this post, we’ll walk through the workflow of moving from an expensive API to a fine-tuned model running on-demand. ## Why Small Models Win in Production The "Large Model" tax is real. Beyond the per-token cost, you face rate limits and unpredictable latency spikes. Transitioning to a fine-tuned 7B or 8B parameter model offers three main advantages: 1. **Latency:** Small models can run inference in milliseconds, especially when hosted on optimized infra. 2. **Privacy:** Your data stays within your environment, never used to train a third party's foundation model. 3. **Consistency:** Fine-tuning allows you to bake "style" and "format" into the weights, reducing the need for long, complex system prompts that eat up input tokens. ## Step 1: Data Synthesis and Distillation The most effective way to replace an expensive API is to use that API to generate your training data—a process known as **distillation**. If you are replacing a structured extraction task, collect 1,000–5,000 examples of your raw input and the expensive API's output. Clean this data to ensure the ground truth is high-quality. Format this into a JSONL file: ```json {"instruction": "Extract the invoice total and currency.", "input": "...raw text...", "output": "150.00 USD"} ``` ## Step 2: Setting Up the Training Environment Fine-tuning requires specific GPU hardware. For an 8B model using QLoRA (Quantized Low-Rank Adaptation), an A100 or H100 is ideal to ensure fast iteration. First, ensure you have your environment configured. You'll need your API key to interact with your GPU resources: ```bash export PODSTACK_API_KEY="your_secret_key_here" ``` Using the Podstack API, you can spin up a job to handle the training. Unlike traditional VMs, you want a job-based approach where the GPU is released immediately after the weights are saved. ## Step 3: The Fine-Tuning Script We typically use the `unsloth` or `peft` libraries for efficient tuning. Here is a simplified Python snippet that defines a fine-tuning function. This function can be packaged as a Podstack job. ```python import os from trl import SFTTrainer from transformers import TrainingArguments from datasets import load_dataset from unsloth import FastLanguageModel def fine_tune_job(): # 1. Load Model and Tokenizer model, tokenizer = FastLanguageModel.from_pretrained( model_name = "unsloth/llama-3-8b-bnb-4bit", max_seq_length = 2048, load_in_4bit = True, ) # 2. Add LoRA adapters model = FastLanguageModel.get_peft_model( model, r = 16, target_modules = ["q_proj", "k_proj", "v_proj", "o_proj"], lora_alpha = 16, lora_dropout = 0, ) # 3. Load your distilled dataset dataset = load_dataset("json", data_files="distilled_data.jsonl", split="train") # 4. Define Trainer trainer = SFTTrainer( model = model, train_dataset = dataset, dataset_text_field = "text", max_seq_length = 2048, args = TrainingArguments( per_device_train_batch_size = 2, gradient_accumulation_steps = 4, warmup_steps = 5, max_steps = 60, learning_rate = 2e-4, fp16 = True, logging_steps = 1, output_dir = "outputs", ), ) trainer.train() model.save_pretrained_merged("final_model", tokenizer, save_method = "merged_16bit") if __name__ == "__main__": fine_tune_job() ``` ## Step 4: Deploying for Inference Once your training job finishes, you have a set of weights optimized for your specific task. You no longer need a massive general-purpose API. To make this useful, you should deploy the model as a serverless endpoint. This allows your application to call the model via a standard REST API, but you only pay for the seconds the GPU is actually processing a request. ## Practical Tips for Success * **Format Matters:** When fine-tuning, use the exact same prompt template during training that you will use during inference (e.g., Llama-3 Instruct format). * **Evaluation:** Don't just trust the "Loss" curve. Keep a "holdout" set of 100 prompts and run them through your fine-tuned model vs. the expensive API. Use an LLM-as-a-judge to grade the similarity. * **Start Small:** Try a 1B or 3B parameter model first. For simple classification or extraction, these "tiny" models often outperform GPT-4 after fine-tuning. ## Making it Work on Podstack Podstack is built specifically for this lifecycle. Instead of managing complex infrastructure or paying for idle GPU time while you debug your code, you can use the Podstack API to launch these jobs on-demand. You can trigger your training script as a job: `podstack run train.py --gpu h100` And once finished, deploy the result as a serverless function. Because Podstack bills per second, the cost of fine-tuning a model usually equates to just a few dollars—an investment that pays for itself within days of turning off your expensive API subscription. By moving your specialized tasks to small, fine-tuned models on Podstack, you gain full control over your stack, reduce your costs by up to 90%, and significantly improve the responsiveness of your application. --- # Fine-tuning a vision-language model for document understanding Learn how to fine-tune Vision-Language Models for document extraction using QLoRA and deploy them efficiently using Podstack's serverless GPU functions. Vision · 2026-09-12 · 3 min read Document understanding—extracting structured data from invoices, forms, and handwritten notes—has shifted from complex OCR pipelines to unified Vision-Language Models (VLMs). While base models like Florence-2 or PaliGemma are impressive out of the box, they often struggle with industry-specific layouts or niche terminology. Fine-tuning these models is the bridge between "general utility" and "production accuracy." In this guide, we’ll walk through a practical workflow for fine-tuning a VLM for document extraction, specifically focusing on the infrastructure efficiency required to handle image-heavy datasets. ## The Architecture of Document Fine-tuning Most modern VLMs consist of a vision encoder (like a ViT) and a language model head. When fine-tuning for document understanding, we aren't just teaching the model new words; we are teaching it the spatial relationship between visual anchors (logos, lines, checkboxes) and their semantic meaning. To get started, you need: 1. **A Dataset**: Images of documents paired with JSON or Markdown representations of their content. 2. **Preprocessing**: Resizing images while maintaining aspect ratios to preserve small text legibility. 3. **Compute**: High-VRAM GPUs (like the A100 or H100) are preferred because image tensors consume significantly more memory than text tokens. ## Step 1: Preparing the Dataset For document tasks, the `LayoutLM` or `Donut` formats are common, but for modern generative VLMs, we typically use a "Prompt -> JSON" format. Your training data should look like this: ```python # example_data.jsonl {"image": "invoice_01.png", "prompt": "Extract the total amount and vendor name.", "target": "{\"total\": \"150.00\", \"vendor\": \"Acme Corp\"}"} ``` ## Step 2: The Training Script We will use the Hugging Face `peft` library with QLoRA to keep memory usage low. This allows us to fine-tune a large VLM on a single on-demand GPU. ```python import torch from transformers import AutoProcessor, AutoModelForVision2Seq from peft import LoraConfig, get_peft_model model_id = "microsoft/Florence-2-base" # Load model and processor processor = AutoProcessor.from_pretrained(model_id, trust_remote_code=True) model = AutoModelForVision2Seq.from_pretrained( model_id, trust_remote_code=True, torch_dtype=torch.float16 ).to("cuda") # Configure LoRA config = LoraConfig( r=16, lora_alpha=32, target_modules=["q_proj", "v_proj"], # Target the attention layers lora_dropout=0.05, bias="none" ) model = get_peft_model(model, config) model.print_trainable_parameters() # Training loop logic goes here... # (DataLoaders, Optimizer, and Loss computation) ``` ## Step 3: Handling High-Resolution Images Document understanding is unique because small text can disappear if you downsample to standard 224x224 or 336x336 resolutions. **Practical Tip:** Use a "patching" strategy or a model that supports variable resolutions. If your GPU memory allows, increase the `max_patches` or input resolution in your processor configuration. This ensures that the 8pt font on a legal document remains legible to the vision encoder. ## Step 4: Deployment and Inference Once the model is fine-tuned, you don't want to keep a heavy GPU instance idling. For document understanding, traffic is often bursty—you might process 1,000 invoices in minutes and then nothing for an hour. This is where serverless GPU functions become essential. ## Scaling on Podstack Fine-tuning is compute-intensive, and serving is latency-sensitive. Podstack handles both ends of this lifecycle with a developer-first API. ### Training as a Job Instead of manually managing a persistent VM, you can trigger your training script as a Job. This ensures you only pay for the seconds the GPU is actually crunching numbers. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` ### Serverless Inference Once your weights are saved, you can deploy the model as a Python GPU function. Podstack’s serverless infrastructure handles the "cold start" optimization, allowing your VLM to spin up, process a document, and spin down instantly. ```python import podstack @podstack.gpu_function(gpu="l4") def extract_document_data(image_bytes): # Load model (cached) and run inference # Returns structured JSON return result ``` ## Summary of Practical Tips * **Augmentation is Key**: Randomly rotate or slightly jitter document images during training. Real-world scans are rarely perfectly aligned. * **Precision Matters**: Use `bf16` if your GPU supports it (A100/H100) to prevent overflow issues during long training runs. * **Monitor VRAM**: Keep an eye on your tensor shapes. Document images are 4D tensors `(batch, channels, height, width)`, and they grow quickly. * **Evaluation**: Don't just rely on Loss. Use **Levenshtein Distance** or **Tree Edit Distance** to measure how accurately the model is reconstructing the document's structure. By combining specialized VLM architectures with Podstack's on-demand GPU infrastructure, you can move from a raw dataset to a production-grade extraction engine without the overhead of managing complex clusters. --- # Fine-tuning Llama with LoRA on a single H100 Learn how to fine-tune Llama 3 using LoRA on a single H100 GPU, optimizing for bfloat16 and maximum throughput on Podstack's on-demand infrastructure. Training · 2026-09-09 · 3 min read Large Language Models (LLMs) like Llama 3 have democratized access to high-tier natural intelligence, but for specialized tasks—like adhering to a specific brand voice or mastering a niche technical domain—out-of-the-box performance often falls short. While full parameter fine-tuning is computationally expensive, Low-Rank Adaptation (LoRA) allows you to achieve state-of-the-art results on a single H100 GPU in under an hour. In this guide, we will walk through the practical steps to fine-tune Llama 3 using the Hugging Face ecosystem, optimized for the high-memory bandwidth of an NVIDIA H100. ## Why the H100 for LoRA? While you can technically run LoRA on smaller cards, the H100’s 80GB of HBM3 memory and Transformer Engine provide two distinct advantages: 1. **Throughput:** You can utilize much larger batch sizes, significantly reducing the wall-clock time for your training runs. 2. **Efficiency:** The H100 handles FP8 and bfloat16 precision natively, maintaining model stability during the weight update process without the overflow issues common in older architectures. ## Prerequisites Before starting, ensure you have your environment configured. You’ll need a Python environment with `torch`, `peft`, `transformers`, and `trl` installed. ```bash pip install torch transformers peft accelerate bitsandbytes trl datasets ``` You will also need to authenticate with Hugging Face to access the Llama weights: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` ## The Fine-Tuning Script We will use the SFT (Supervised Fine-Tuning) Trainer from the `trl` library. This script targets the linear layers of the Llama architecture for adaptation. ```python import torch from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments from datasets import load_dataset from trl import SFTTrainer from peft import LoraConfig, get_peft_model model_id = "meta-llama/Meta-Llama-3-8B" # 1. Load Dataset dataset = load_dataset("json", data_files="my_custom_data.jsonl", split="train") # 2. Configure LoRA lora_config = LoraConfig( r=16, lora_alpha=32, target_modules=["q_proj", "v_proj", "k_proj", "o_proj"], lora_dropout=0.05, bias="none", task_type="CAUSAL_LM" ) # 3. Load Model in bfloat16 (Optimized for H100) model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.bfloat16, device_map="auto" ) tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.pad_token = tokenizer.eos_token # 4. Define Training Arguments training_args = TrainingArguments( output_dir="./llama-3-lora", per_device_train_batch_size=8, gradient_accumulation_steps=4, learning_rate=2e-4, logging_steps=10, num_train_epochs=3, bf16=True, # Utilize H100 bfloat16 capabilities save_strategy="epoch", report_to="none" ) # 5. Initialize Trainer trainer = SFTTrainer( model=model, train_dataset=dataset, peft_config=lora_config, dataset_text_field="text", max_seq_length=2048, tokenizer=tokenizer, args=training_args, ) trainer.train() trainer.model.save_pretrained("./final_lora_adapter") ``` ## Practical Tips for H100 Optimization ### 1. Leverage `bf16` The H100 is designed for `bfloat16`. Unlike `fp16`, which has a limited dynamic range and often requires loss scaling to prevent gradients from zeroing out, `bf16` matches the dynamic range of `fp32`. Always set `bf16=True` in your `TrainingArguments` to maximize the H100’s hardware accelerators. ### 2. Maximize Batch Size With 80GB of VRAM, a standard 8B model fine-tune using LoRA barely scratches the surface. If you are using a sequence length of 2048, you can likely push your `per_device_train_batch_size` to 16 or 32. This keeps the GPU cores saturated and finishes the job faster, saving you money on per-second billing. ### 3. Target More Modules LoRA traditionally only targets the query and value projections (`q_proj`, `v_proj`). However, the H100 has enough headroom to target all linear layers—including `k_proj`, `o_proj`, and the MLP layers—without significant performance hits. This often leads to better convergence in fewer epochs. ## Deploying on Podstack Moving from local experimentation to a production-grade H100 is seamless with Podstack. Instead of managing drivers and CUDA versions, you can deploy this fine-tuning job using our API. First, set your environment variable: ```bash export PODSTACK_API_KEY="your_api_key_here" ``` You can trigger a fine-tuning job as a Podstack Job, which spins up an H100, executes your script, and spins down immediately when the `trainer.train()` call completes. This ensures you only pay for the exact seconds the H100 was active. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Once the adapter is saved, you can serve it using Podstack's serverless inference endpoints. Since LoRA adapters are small (usually <200MB), you can hot-swap them onto a base Llama 3 model in our serverless environment, allowing you to serve multiple fine-tuned versions of your model without paying for dedicated standing GPUs for each one. ## Conclusion Fine-tuning Llama 3 on an H100 is the gold standard for creating specialized AI agents. By utilizing LoRA and `bfloat16`, you balance efficiency with power. With Podstack, you get the raw power of the H100 with the agility of a serverless workflow, ensuring that your ML pipeline is as cost-effective as it is performant. --- # Fine-tuning SDXL for consistent brand illustrations Learn how to fine-tune SDXL using LoRA on Podstack GPUs to create consistent, brand-aligned illustrations with Python and serverless infrastructure. Image · 2026-09-06 · 3 min read In the rapidly evolving landscape of generative AI, one of the biggest challenges for design teams is maintaining visual consistency. While Stable Diffusion XL (SDXL) is capable of generating stunning imagery, its out-of-the-box outputs often lack the specific stylistic cohesion required for a brand’s visual identity. For developers and ML engineers, fine-tuning SDXL via Low-Rank Adaptation (LoRA) has emerged as the most efficient way to bake a specific brand aesthetic—colors, stroke weights, and character styles—into the model without the overhead of a full checkpoint training run. This guide covers the technical workflow for fine-tuning SDXL to produce consistent brand illustrations and how to deploy that workflow at scale using high-performance GPUs. ## The Strategy: Why LoRA? Training a full SDXL model (2.6 billion parameters) is computationally expensive and prone to catastrophic forgetting. LoRA solves this by adding a small number of new weights to the cross-attention layers. The result is a small file (typically 50MB to 200MB) that can be "hot-swapped" onto a base SDXL model. For brand consistency, this means you can train a LoRA on 15–30 high-quality brand assets, ensuring that every subsequent generation follows the same geometric logic and color palette. ## Step 1: Data Preparation and Captioning The quality of your fine-tune is dictated by your dataset. For a brand illustration model, you need: * **Consistency:** 20-50 PNG images with a transparent or solid background. * **Diversity:** Variation in subjects (e.g., people, UI elements, icons) but strictly the same artistic style. * **Naming:** Use a unique trigger word that doesn't exist in the standard English lexicon (e.g., `brndstyl`). Each image should have a corresponding `.txt` file with descriptive captions: `A digital illustration of a rocket ship in brndstyl style, flat design, corporate blue and white.` ## Step 2: Setting Up the Training Environment To fine-tune SDXL efficiently, you need significant VRAM (ideally 24GB or more). Using the Podstack API, you can spin up an optimized environment in seconds. First, ensure your API key is configured: ```bash export PODSTACK_API_KEY="your_api_key_here" ``` Next, initialize a job using the Podstack Python SDK to handle the training logic. We recommend using the `diffusers` library combined with `kohya_ss` or similar trainers. ```python import podstack # Define the GPU function for training @podstack.gpu_function(gpu="A100", memory="40GB") def train_brand_lora(dataset_path: str, output_name: str): import os from accelerate import Accelerator # Simple wrapper for the training script cmd = ( f"accelerate launch train_network.py " f"--pretrained_model_name_or_path='stabilityai/stable-diffusion-xl-base-1.0' " f"--train_data_dir='{dataset_path}' " f"--output_name='{output_name}' " f"--resolution=1024 " f"--train_batch_size=1 " f"--learning_rate=1e-4 " f"--network_module=networks.lora" ) os.system(cmd) return f"Training complete. Weights saved as {output_name}.safetensors" # Trigger the job on Podstack's serverless infrastructure job = train_brand_lora.deploy(dataset_path="./brand_assets", output_name="brand_v1") print(f"Job ID: {job.id}") ``` ## Step 3: Hyperparameter Tuning for Illustration Illustrations behave differently than photorealistic images. When fine-tuning for a brand style: 1. **Learning Rate:** Start at `1e-4`. If the style isn't bleeding through, increase to `2e-4`. 2. **Rank (Network Alpha/Dim):** For complex styles, use a rank of 64. For simple flat icons, 16 or 32 is often sufficient to prevent overfitting. 3. **UNet vs. Text Encoder:** Often, you only need to train the UNet. However, if your brand style involves specific character features, training the text encoder at a lower learning rate (`5e-5`) can help the model associate the trigger word more strongly. ## Step 4: Inference and Validation Once the `.safetensors` file is generated, you can run inference to validate the consistency. On Podstack, you can host this as a serverless endpoint to serve your design team’s internal tools. ```python from diffusers import DiffusionPipeline import torch pipe = DiffusionPipeline.from_pretrained( "stabilityai/stable-diffusion-xl-base-1.0", torch_dtype=torch.float16 ).to("cuda") # Load your brand LoRA pipe.load_lora_weights("./brand_v1.safetensors") prompt = "A man sitting at a desk typing on a laptop, brndstyl style, high contrast" image = pipe(prompt, num_inference_steps=30).images[0] image.save("output.png") ``` ## Scaling with Podstack The beauty of fine-tuning on Podstack is the shift from infrastructure management to model development. Instead of managing persistent virtual machines and worrying about idle costs, you use on-demand GPUs billed by the second. For teams building internal design tools, you can: * **Run Jobs:** Use the Podstack API to launch batch training sessions across multiple GPU types (A100s, H100s, or L4s) depending on your budget and speed requirements. * **Serverless Inference:** Once your brand LoRA is ready, deploy it as a Podstack endpoint. Your frontend applications can simply hit an API to generate brand-compliant assets, scaling to zero when not in use. By leveraging LoRA and high-performance cloud GPUs, maintaining a consistent visual language is no longer a manual bottleneck, but a scalable, programmatic component of your creative workflow. --- # Fine-tuning Whisper for accented speech recognition Learn how to fine-tune OpenAI's Whisper using LoRA for accented speech and deploy it as a serverless GPU function on Podstack for cost-effective inference. Audio · 2026-09-03 · 3 min read Automated Speech Recognition (ASR) has reached a turning point with OpenAI’s Whisper. While the pre-trained models are exceptionally robust for standard dialects, they often struggle with diverse accents, specialized jargon, or low-resource linguistic nuances. For developers building voice interfaces for global users, fine-tuning is the bridge between "decent" and "production-ready" accuracy. In this guide, we will walk through the practical workflow of fine-tuning Whisper on a custom accented dataset and deploying it as a serverless function using Podstack. ## The Strategy: Focused Fine-Tuning Whisper is an encoder-decoder Transformer. To improve accented speech recognition, we don't need to retrain the entire model. Instead, we use **LoRA (Low-Rank Adaptation)** to update a small fraction of the weights. This keeps the memory footprint low and prevents "catastrophic forgetting," where the model loses its general linguistic capabilities. ### 1. Data Preparation Quality is more important than quantity. For accent adaptation, 5–10 hours of high-quality transcribed audio is often sufficient to see a significant drop in Word Error Rate (WER). Use the `datasets` library to load your data. ```python from datasets import load_dataset, Audio # Load your custom accented dataset dataset = load_dataset("path/to/your/accented_data", split="train") # Whisper requires audio at 16kHz dataset = dataset.cast_column("audio", Audio(sampling_rate=16000)) ``` ### 2. Feature Extraction and Tokenization You need the `WhisperProcessor` to convert raw audio into Mel Spectrograms and text into label IDs. Ensure you specify the target language to help the model narrow its search space. ```python from transformers import WhisperProcessor model_id = "openai/whisper-medium" processor = WhisperProcessor.from_pretrained(model_id, language="English", task="transcribe") ``` ## Training on High-Performance GPUs Fine-tuning `whisper-medium` or `whisper-large-v3` requires significant VRAM. On Podstack, you can spin up an A100 or H100 on-demand to handle the compute-intensive training loops. ### 3. The Fine-Tuning Script Using the `PEFT` library makes the process efficient. Here is a condensed look at the training setup: ```python from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training from transformers import WhisperForConditionalGeneration, Seq2SeqTrainer, Seq2SeqTrainingArguments model = WhisperForConditionalGeneration.from_pretrained(model_id, load_in_8bit=True, device_map="auto") model = prepare_model_for_kbit_training(model) config = LoraConfig(r=32, lora_alpha=64, target_modules=["q_proj", "v_proj"], lora_dropout=0.05, bias="none") model = get_peft_model(model, config) training_args = Seq2SeqTrainingArguments( output_dir="./whisper-accented", per_device_train_batch_size=8, gradient_accumulation_steps=2, learning_rate=1e-4, warmup_steps=50, max_steps=1000, fp16=True, evaluation_strategy="steps", per_device_eval_batch_size=8, predict_with_generate=True, save_steps=200, logging_steps=25, report_to=["tensorboard"], ) trainer = Seq2SeqTrainer( args=training_args, model=model, train_dataset=dataset["train"], eval_dataset=dataset["test"], data_collator=data_collator, tokenizer=processor.feature_extractor, ) trainer.train() ``` ## Practical Tips for Success 1. **Augmentation Matters**: If your dataset is small, apply light background noise or speed perturbations to the audio. This forces the model to focus on the phonetic characteristics of the accent rather than the recording environment. 2. **SpecAugment**: Whisper training benefits significantly from SpecAugment (masking blocks of frequency or time in the spectrogram). Ensure this is enabled in your processor config. 3. **Evaluate with WER**: Don't rely on loss alone. Use the `evaluate` library to calculate the Word Error Rate on a held-out test set containing the target accent. ## Deploying as a Serverless Endpoint Once training is complete, the goal is to move from a heavy training script to a lightweight inference endpoint. This is where Podstack’s serverless GPU functions shine. You only pay for the seconds the GPU is actually processing audio. ### Step 4: The Inference Function Create a `main.py` that utilizes your fine-tuned weights: ```python import podstack @podstack.gpu_function(gpu="A10G") def transcribe_accented_speech(audio_bytes): # Load model and processor (cached on the GPU worker) # Process audio_bytes -> return text return {"text": transcription} ``` ### Step 5: Deploy via Podstack API Deployment is handled entirely via the API. Ensure your `PODSTACK_API_KEY` is set in your environment variables. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Podstack handles the containerization, GPU provisioning, and scaling. When an audio file is sent to your new endpoint, Podstack spins up the GPU, runs the inference, and spins it down immediately after, billing you only for the exact execution time. ## Why Podstack for Whisper? Fine-tuning and serving ASR models involves two distinct infrastructure challenges: massive throughput for training and low-latency, cost-effective scaling for inference. By using **Podstack**, you bridge this gap: * **On-Demand Jobs**: Run your fine-tuning scripts on high-memory GPUs (like the A100) and pay only for the hours the trainer is running. * **Serverless Inference**: Deploy your fine-tuned LoRA adapters as endpoints that scale to zero. You don't have to pay for an idle GPU waiting for a user to speak. * **Python-Native**: No need to write complex Dockerfiles or Kubernetes manifests. Just decorate your Python function and deploy. Fine-tuning Whisper for accented speech transforms a general-purpose tool into a specialized competitive advantage. With the right data and Podstack’s elastic GPU infrastructure, you can go from raw audio to a specialized production API in an afternoon. --- # Fractional GPUs: when a slice is all you need Learn how to optimize ML costs and performance by using fractional GPUs for inference and development tasks through memory management and Podstack’s GPU cloud. Infrastructure · 2026-08-31 · 4 min read The rapid evolution of Large Language Models (LLMs) and diffusion models has created a massive surge in demand for high-end hardware. However, not every machine learning task requires the full brute force of an H100 or an A100. In many production scenarios, allocating an entire 80GB GPU to a single small task is like using a sledgehammer to crack a nut—it’s inefficient and expensive. This is where fractional GPUs come in. By slicing a single physical GPU into multiple logical units, ML engineers can maximize resource utilization, reduce latency for concurrent requests, and significantly cut operational costs. ## Why Slice Your Compute? In a traditional setup, a GPU is treated as a monolithic resource. If your model only uses 4GB of VRAM and 15% of the CUDA cores, the remaining 90%+ of the hardware sits idle, yet you are billed for the full unit. Fractional GPUs solve this through two primary methods: 1. **Memory Mapping:** Restricting the amount of VRAM a process can see or allocate. 2. **Time-Slicing/MIG:** Partitioning the hardware at the driver or hardware level so multiple containers can run in parallel on one card. For tasks like preprocessing, small-scale inference (e.g., BERT or Whisper), and dev environments, fractional GPUs allow you to scale horizontally without your budget scaling linearly. ## When a Slice is All You Need Before you partition your resources, identify if your workload fits the "fractional" profile. Good candidates include: * **Serverless Inference:** Handling intermittent traffic for lightweight models where a dedicated GPU would spend 90% of its time idling. * **Microservices:** Running multiple specialized models (one for OCR, one for sentiment, one for summarization) on a single physical machine. * **Development & Prototyping:** Giving every developer on a team a "slice" of a powerful GPU rather than one developer hogging the whole machine. * **CI/CD Pipelines:** Running automated tests for GPU-accelerated code. ## Implementing Fractional Inference If you are deploying via Python, you can manage memory consumption directly to allow multiple processes to coexist. Below is a practical example of how to initialize a model with strict memory limits using `torch`. ```python import torch from transformers import AutoModelForCausalLM, AutoTokenizer def load_model_fractional(model_name: str, memory_fraction: float): # Set the fraction of the GPU memory to be used by this process # memory_fraction is a float between 0.0 and 1.0 torch.cuda.set_per_process_memory_fraction(memory_fraction, device=0) print(f"Allocated {memory_fraction * 100}% of GPU for this worker.") tokenizer = AutoTokenizer.from_pretrained(model_name) model = AutoModelForCausalLM.from_pretrained( model_name, device_map="cuda:0", torch_dtype=torch.float16 ) return model, tokenizer # Example: Use only 25% of the GPU for this specific inference worker model, tokenizer = load_model_fractional("gpt2", 0.25) ``` By setting `set_per_process_memory_fraction`, you prevent a single Python process from greedily grabbing all available VRAM, allowing you to spin up four identical workers on the same physical chip. ## Practical Tips for Fractional Workloads * **Monitor "Cold Starts":** When using fractional units in a serverless context, ensure your container images are optimized. Smaller images mean faster loading onto the sliced hardware. * **Watch the Interconnect:** While compute is sliced, the PCIe bandwidth is shared. If you have four slices all trying to move massive datasets from RAM to VRAM simultaneously, you may hit a bottleneck. * **Right-size your VRAM:** Don't just guess. Use profiling tools to see the peak memory usage of your model during a heavy inference request, then add a 20% buffer. If your model peaks at 6GB, an 8GB slice is your sweet spot. ## Deploying on Podstack Podstack makes fractional GPU management seamless by abstracting the hardware complexity. Instead of manually configuring NVIDIA partitions, you can define your resource requirements directly through the Podstack API. With Podstack, you only pay for the compute you actually consume, billed by the second. If you need a Python function to run on a fraction of a GPU for a specific job, you can deploy it instantly. First, ensure your environment is ready: ```bash export PODSTACK_API_KEY="your_secret_key_here" ``` You can then deploy a fractional GPU worker by specifying the resource requirements in your deployment manifest or via the API: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Podstack’s orchestration layer handles the bin-packing, ensuring that multiple "slices" are efficiently packed onto our high-performance GPU fleet. This means you get the power of enterprise-grade hardware without the enterprise-grade price tag for small tasks. ## Conclusion Maximizing GPU ROI is a core competency for modern ML teams. By moving away from the "one model, one GPU" mindset and embracing fractional slices, you can build more resilient, scalable, and cost-effective AI applications. Whether you are running serverless inference or batch processing jobs, remember: sometimes, a slice is all you really need. --- # From notebook to production: an MLOps checklist Learn the essential steps to transition ML models from Jupyter Notebooks to production-ready GPU deployments using modular code and specialized cloud tools. Workflows · 2026-08-28 · 3 min read Moving a model from a Jupyter Notebook to a production-ready environment is often where machine learning projects stall. In a notebook, state is global, execution is non-linear, and hardware is usually local or manually provisioned. In production, you need reproducibility, scalability, and cost-efficiency. Transitioning to an MLOps mindset means treating your model as a living software service. This checklist outlines the essential steps to bridge the gap between "it works on my machine" and a robust, deployed system. ## 1. Modularize the Monolith Notebooks are great for exploration but terrible for version control. Your first step is to extract your logic into structured Python modules. * **Separate concerns:** Create distinct files for data loading (`data.py`), model architecture (`model.py`), and the inference logic (`app.py`). * **Handle dependencies:** Replace manual `!pip install` cells with a `requirements.txt` or `pyproject.toml`. * **Environment Variables:** Never hardcode API keys or database URLs. Use a `.env` file for local development and inject them as environment variables in production. ## 2. Optimize for GPU Cold Starts In a serverless or on-demand GPU environment, the time it takes for your container to start and load the model into VRAM directly impacts latency. * **Weights Pre-loading:** Don’t download weights from the internet during runtime. Bake them into your container image or use a persistent volume. * **Model Quantization:** Use techniques like FP16 or INT8 to reduce the model's memory footprint without significantly sacrificing accuracy. * **Warmup Requests:** If your framework (like PyTorch or TensorFlow) initializes kernels on the first run, perform a "dummy" inference during the setup phase so the first user doesn't hit a 10-second delay. ## 3. Implement Robust Logging and Telemetry In production, you can't "see" the variables. You need structured logging. * **Input/Output Validation:** Use libraries like Pydantic to ensure the data hitting your model matches the expected schema. * **Performance Metrics:** Track GPU utilization, inference time per request, and memory consumption. * **Request IDs:** Assign a unique ID to every inference request to trace errors through your stack. ## 4. Containerize the Environment Docker is the industry standard for ensuring that the CUDA drivers, Python version, and library dependencies remain consistent between your local machine and the GPU cloud. For an ML workload, your `Dockerfile` should look something like this: ```python # example: deploying a simple GPU function import podstack import torch @podstack.gpu_function(gpu="A100", memory="20GB") def generate_inference(prompt: str): # Ensure the model is loaded efficiently model = load_my_model() device = "cuda" if torch.cuda.is_available() else "cpu" inputs = tokenizer(prompt, return_tensors="pt").to(device) with torch.no_grad(): output = model.generate(**inputs) return tokenizer.decode(output[0]) ``` ## 5. Automate the Deployment Pipeline Manual deployments are error-prone. Use a API-driven approach to push your code to the cloud. This allows you to integrate deployment into your CI/CD pipeline. A production-ready workflow often involves setting your credentials and triggering a build: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` ## 6. Scaling and Cost Management The most expensive mistake in MLOps is leaving an idle GPU running. * **Per-Second Billing:** Ensure your provider supports granular billing. If your job takes 45 seconds, you shouldn't pay for an hour. * **Auto-scaling:** Configure your endpoints to scale to zero when no requests are coming in, and scale up horizontally as traffic increases. ## Making it Happen on Podstack Podstack was designed to handle this checklist natively. Instead of managing complex Kubernetes clusters or worrying about driver compatibility, Podstack allows you to treat GPUs as simple Python functions. When you use the Podstack API, the platform handles the containerization, the GPU provisioning, and the networking automatically. You get on-demand access to high-end hardware like H100s or A100s with billing that stops the moment your function returns a value. To get started, install the SDK, set your `PODSTACK_API_KEY`, and move your model from that notebook into a high-performance production environment in minutes. By following this checklist and leveraging a specialized GPU cloud, you ensure your ML infrastructure is as sophisticated as the models you build. --- # Full-parameter fine-tuning with DeepSpeed ZeRO-3 Learn how to perform full-parameter fine-tuning on large models using DeepSpeed ZeRO-3 and Podstack's on-demand GPU infrastructure. Training · 2026-08-25 · 4 min read Modern Large Language Models (LLMs) have grown so large that even a single H100 or A100 often lacks the VRAM required for full-parameter fine-tuning. While techniques like LoRA and QLoRA offer a memory-efficient compromise, they only update a fraction of the model's weights. When your task requires the model to learn deep structural patterns or specialized domain knowledge, full-parameter fine-tuning remains the gold standard. DeepSpeed ZeRO-3 (Zero Redundancy Optimizer Stage 3) is the industry-standard solution for this challenge. By partitioning model states (parameters, gradients, and optimizer states) across all available GPUs, ZeRO-3 allows you to train models that are significantly larger than the memory of any single device. In this guide, we’ll walk through setting up a multi-GPU environment for full-parameter fine-tuning using DeepSpeed ZeRO-3 on Podstack. ## Understanding ZeRO-3 Before diving into the code, it is important to understand what ZeRO-3 actually does. Unlike ZeRO-1 (partitioning optimizer states) or ZeRO-2 (partitioning gradients), ZeRO-3 partitions the **model parameters** themselves. During the forward and backward passes, the necessary parameters are "gathered" from other GPUs just-in-time and discarded immediately after use. This creates a virtual pool of VRAM, enabling you to fine-tune a 70B parameter model across a cluster of GPUs where it otherwise wouldn't fit. ## Prerequisites To follow this guide, you will need: - A Podstack account. - The Podstack API installed (`pip install podstack-sdk`). - An environment variable `PODSTACK_API_KEY` set in your terminal. - A Hugging Face model (e.g., Llama-3-8B or Mistral-7B) and a dataset. ## Step 1: Configuring DeepSpeed DeepSpeed uses a JSON configuration file to manage its optimization strategies. For full-parameter fine-tuning, the `zero_optimization` block is the most critical part. Save the following as `ds_config.json`: ```json { "fp16": { "enabled": "auto" }, "bf16": { "enabled": "auto" }, "zero_optimization": { "stage": 3, "offload_optimizer": { "device": "cpu", "pin_memory": true }, "offload_param": { "device": "cpu", "pin_memory": true }, "overlap_comm": true, "contiguous_gradients": true, "sub_group_size": 1e9, "reduce_bucket_size": "auto", "stage3_prefetch_bucket_size": "auto", "stage3_param_persistence_threshold": "auto", "stage3_max_live_parameters": 1e9, "stage3_max_reuse_distance": 1e9, "stage3_gather_1d_copy_size": 1e8 }, "gradient_accumulation_steps": "auto", "gradient_clipping": "auto", "steps_per_print": 2000, "train_batch_size": "auto", "train_micro_batch_size_per_gpu": "auto", "wall_clock_breakdown": false } ``` *Tip: `offload_optimizer` and `offload_param` to `cpu` are optional but highly recommended if you are pushing the limits of your VRAM.* ## Step 2: The Training Script Using the Hugging Face `Trainer` API makes integrating DeepSpeed seamless. The trainer automatically detects the DeepSpeed configuration if passed via the command line or the `TrainingArguments` object. ```python from transformers import AutoModelForCausalLM, AutoTokenizer, TrainingArguments, Trainer from datasets import load_dataset import torch def train(): model_id = "meta-llama/Meta-Llama-3-8B" dataset = load_dataset("json", data_files="my_data.jsonl", split="train") tokenizer = AutoTokenizer.from_pretrained(model_id) tokenizer.pad_token = tokenizer.eos_token model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.bfloat16, use_cache=False # Crucial for training ) training_args = TrainingArguments( output_dir="./llama3-finetuned", per_device_train_batch_size=4, gradient_accumulation_steps=4, learning_rate=2e-5, num_train_epochs=3, bf16=True, deepspeed="ds_config.json", # Path to the config created in Step 1 logging_steps=10, save_strategy="epoch" ) trainer = Trainer( model=model, args=training_args, train_dataset=dataset, data_collator=lambda data: tokenizer( [d["text"] for d in data], padding=True, truncation=True, return_tensors="pt" ) ) trainer.train() if __name__ == "__main__": train() ``` ## Step 3: Launching on Podstack Podstack makes it easy to spin up multi-GPU instances without the overhead of complex orchestration. Since full-parameter fine-tuning is compute-intensive, we recommend using a node with at least 4x A100 or H100 GPUs. To launch your training job using the Podstack API: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Because Podstack bills per second, you only pay for the exact duration of the fine-tuning process. Once the `trainer.train()` call completes, the job terminates, and the billing stops instantly. ## Practical Tips for ZeRO-3 1. **CPU Offloading:** If you encounter Out-of-Memory (OOM) errors even with ZeRO-3, ensure `offload_optimizer` is set to `cpu`. This moves the optimizer states (which are often 2-3x larger than the model weights) to system RAM. 2. **Network Bottlenecks:** ZeRO-3 involves significant communication between GPUs. On Podstack, our high-speed interconnects handle this efficiently, but you should always aim to keep your `gradient_accumulation_steps` high to maximize compute-to-communication ratios. 3. **Checkpointing:** Full-parameter checkpoints are massive. Ensure your output volume has enough space to store the model weights (e.g., ~30GB for an 8B model in fp16). ## Conclusion DeepSpeed ZeRO-3 is a transformative technology for ML engineers, turning a cluster of GPUs into a single, massive memory pool. By combining this with the on-demand, per-second billing of Podstack, you can perform high-end full-parameter fine-tuning without the capital expenditure of a permanent GPU cluster. Once your model is fine-tuned, you can deploy it instantly as a serverless inference endpoint or a Python GPU function using the same Podstack ecosystem, ensuring a seamless transition from training to production. --- # Generating synthetic training data with LLMs Learn how to scale ML training by using LLMs to generate high-quality synthetic datasets with structured prompting and on-demand GPU infrastructure. Data · 2026-08-22 · 4 min read Large Language Models (LLMs) have shifted the bottleneck of machine learning from model architecture to data quality. While open-source datasets are abundant, they often lack the domain-specific nuances required for specialized tasks like legal document classification, medical entity extraction, or niche code generation. Synthetic data generation is the process of using powerful "teacher" models (like Llama 3.1 405B or Mixtral) to generate high-quality labeled examples to train smaller, more efficient "student" models. This approach allows you to build production-grade models that are faster, cheaper, and private, without needing thousands of manually labeled human examples. ## The Strategy: Prompt-to-Dataset The goal is to transform a small set of "seed" examples into a massive dataset. A typical workflow involves three stages: 1. **Seed Selection:** Curating 10-20 high-quality, human-verified examples. 2. **Expansion:** Using an LLM to generate variations, edge cases, and diverse scenarios based on those seeds. 3. **Validation:** Using a second LLM or a set of heuristic rules to filter out low-quality or hallucinated outputs. ## Step 1: Defining the Schema To ensure your synthetic data is machine-readable, always force the LLM to output structured data, typically JSON. If you are training a named entity recognition (NER) model, your prompt should define exactly how entities should be tagged. ## Step 2: Parallelized Generation Generating 100,000 rows of data sequentially is inefficient. To scale, you should wrap your generation logic in a function that can be mapped across hundreds of GPU cores simultaneously. Below is a practical Python example using a synthetic generation pattern. We define a prompt template and use a high-throughput inference engine to generate training pairs. ```python import os import json from podstack import RemoteFunction # Your Podstack API Key should be set in your environment # export PODSTACK_API_KEY="your_secret_key" @RemoteFunction(gpu="A100", memory="40GB") def generate_synthetic_batch(seed_topic: str): """ Generates a batch of synthetic instructions and responses for a specialized medical assistant. """ import vllm prompt = f""" Generate 5 diverse medical queries and expert responses related to: {seed_topic}. Format the output as a JSON list of objects with 'instruction' and 'context' keys. Ensure the tone is professional and medically accurate. """ # Initialize the model on Podstack's on-demand GPU llm = vllm.LLM(model="casperhansen/llama-3-70b-instruct-awq") sampling_params = vllm.SamplingParams(temperature=0.8, max_tokens=1024) outputs = llm.generate([prompt], sampling_params) return outputs[0].outputs[0].text # Deployment and execution if __name__ == "__main__": topics = ["Cardiology", "Neurology", "Pediatrics", "Oncology"] # Mapping the function across multiple GPU instances on Podstack results = [generate_synthetic_batch(t) for t in topics] with open("synthetic_data.jsonl", "w") as f: for res in results: f.write(res + "\n") ``` ## Step 3: Diversification and Filtering The biggest risk with synthetic data is "model collapse" or repetition. If you ask an LLM for "100 examples of a customer complaint," it might produce 100 variations of "My order is late." To combat this: * **Dynamic Prompting:** Inject random variables into your prompt, such as personas ("Write as a frustrated customer," "Write as a polite elderly person") or specific constraints ("The complaint must be about a software bug"). * **The Auditor Pattern:** Use a smaller, faster model to "score" the generated data. If the score falls below a threshold (e.g., if the JSON is malformed or the response is too short), discard it immediately. ## Step 4: Training the Student Once you have your `.jsonl` file, you can move to fine-tuning. Because synthetic data is perfectly formatted, you can often achieve better results with a 7B parameter model than you could with a larger model trained on messy, "natural" data. ## Practical Tips for ML Engineers 1. **Temperature is Key:** When generating data, use a higher temperature (0.7 - 0.9) to ensure variety. For the validation/auditor step, use a low temperature (0.0 - 0.2) for consistency. 2. **Cost Management:** Per-second billing is your friend here. Synthetic data generation is often bursty—you might need 50 GPUs for an hour, then none for the rest of the week. Don't pay for idle time. 3. **Check for Leakage:** Ensure your synthetic data doesn't contain the exact strings from your validation or test sets. This leads to inflated performance metrics that won't hold up in production. ## Scale your Dataset on Podstack Building high-quality synthetic datasets requires significant compute, but it shouldn't require complex infrastructure management. With Podstack, you can move from a Python script to a distributed generation pipeline in minutes. By using the Podstack API, you can deploy your generation functions as serverless endpoints or batch jobs that spin up on-demand GPUs (like A100s or H100s) and shut them down the moment the last row of data is generated. This per-second billing ensures that your synthetic data project remains cost-effective even at the million-row scale. To get started, simply install the SDK and authenticate: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Whether you are distilling a massive LLM into a specialized edge model or expanding a tiny labeled dataset, the combination of structured prompting and scalable GPU compute is the fastest path to a production-ready AI system. --- # GPU functions in Python: serverless ML in five lines Learn how to deploy scalable ML models using serverless GPU functions in Python with Podstack, featuring per-second billing and zero-config infrastructure. Workflows · 2026-08-19 · 3 min read The transition from a local Jupyter notebook to a production-grade ML microservice is often where projects stall. Between configuring CUDA drivers, managing Docker images, and setting up autoscaling groups, the "infrastructure tax" can consume more time than the actual model engineering. For ML engineers, the ideal workflow is simple: write a Python function, decorate it, and have it run on a high-end A100 or H100 without thinking about the underlying VM. This is the promise of serverless GPU functions. In this post, we’ll look at how to deploy a model in five lines of code, turning standard Python into a scalable API endpoint. ## The Shift to Functional GPU Compute Traditional cloud infrastructure treats GPUs like virtual servers—you rent a box, SSH in, and keep it running. Serverless GPU compute treats the GPU like a utility. With `podstack`, you define the hardware requirements directly in your code. When the function is called, the platform orchestrates a container, attaches the requested GPU, executes the logic, and spins down. You are billed only for the seconds the GPU was active. This is particularly effective for: - Batch inference jobs. - Image generation (Stable Diffusion). - LLM fine-tuning tasks. - Asynchronous video processing. ## Deploying in Five Lines To get started, ensure you have the Podstack API installed and your `PODSTACK_API_KEY` exported in your environment. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` The core logic relies on defining a function that the platform can pick up and containerize automatically. Here is how you deploy a Hugging Face model for sentiment analysis in a serverless environment: ```python import podstack @podstack.gpu(gpu="A10G", vram="24GB") def analyze_sentiment(text: str): from transformers import pipeline classifier = pipeline("sentiment-analysis", device=0) return classifier(text) # Deploy to an endpoint endpoint = podstack.deploy(analyze_sentiment) print(f"Service live at: {endpoint.url}") ``` In these five lines, we’ve defined the hardware (NVIDIA A10G), handled the environment isolation, and triggered a deployment. Podstack takes care of the cold-start optimization and the REST API wrapping. ## Managing Dependencies and Environments One of the biggest hurdles in GPU computing is the "it works on my machine" syndrome, usually caused by mismatched CUDA versions. When using GPU functions, you can specify your requirements in a `requirements.txt` or directly in the decorator. The Podstack engine handles the heavy lifting of building a container image that includes the necessary drivers and libraries. **Practical Tip:** To minimize cold-start times, try to load your models outside the function's global scope if using a persistent worker, or use Podstack’s "Volume" feature to cache model weights. This prevents the function from re-downloading gigabytes of data from Hugging Face every time a new instance spins up. ## Scaling from One to One Thousand The beauty of the serverless approach is the transition from "Job" to "Endpoint." 1. **Jobs:** If you need to process a million images, you can map your function across a list of inputs. Podstack will parallelize these across as many GPUs as your quota allows. 2. **Endpoints:** If you are building a user-facing app, the function acts as a standard HTTP endpoint. When traffic spikes, the platform spins up more instances; when traffic hits zero, your costs hit zero. ## Monitoring and Optimization Once your function is live, you can monitor performance via the API: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Keep an eye on VRAM utilization. If your model only uses 8GB of VRAM, don't pay for an A100. Downscaling to a T4 or an A10G can cut your costs by 70% without impacting latency for smaller models. Because Podstack bills per second, these optimizations show up on your invoice immediately. ## Why Podstack? Podstack was built to remove the friction between a Python script and a production GPU cluster. By providing on-demand GPUs billed by the second, it allows developers to focus on the `model.predict()` rather than the `docker build`. Whether you are running a single inference job or building the backbone of a new AI startup, the workflow remains the same: write Python, specify your GPU, and deploy. Ready to scale? Head over to your dashboard, grab your `PODSTACK_API_KEY`, and turn your Python functions into high-performance GPU endpoints today. --- # Hybrid search: combining BM25 and embeddings Learn how to combine BM25 and vector embeddings using Reciprocal Rank Fusion to build a robust, production-grade hybrid search system on Podstack GPUs. RAG · 2026-08-16 · 4 min read In the landscape of modern Information Retrieval (IR), we are often presented with a false dichotomy: use traditional keyword-based search (BM25) or modern vector-based semantic search (Embeddings). While vector embeddings excel at capturing context and synonyms—understanding that "dog" and "canine" are related—they often struggle with "exact match" scenarios, such as product serial numbers, technical acronyms, or specific proper nouns. This is where **Hybrid Search** comes in. By combining the lexical precision of BM25 with the semantic depth of dense vectors, you can build search systems that are significantly more robust than either method alone. ## The Architecture of Hybrid Search Hybrid search typically follows a two-pronged workflow: 1. **Lexical Branch (BM25):** The query is tokenized, and documents are scored based on term frequency and inverse document frequency. This handles exact keyword overlap. 2. **Dense Branch (Embeddings):** The query is passed through a transformer model (like BGE or E5) to generate a vector. A vector database then performs a cosine similarity search. 3. **Fusion:** The results from both lists are combined using an algorithm like **Reciprocal Rank Fusion (RRF)** to produce a final, re-ranked list of documents. ## Implementing Hybrid Search with Python To implement this effectively, you need a GPU to handle the embedding generation at scale. While you could run these on a CPU, latency will become a bottleneck as your document count grows. Here is a practical implementation using the `rank_bm25` library for the lexical side and a sentence-transformer for the embedding side. ```python import numpy as np from rank_bm25 import BM25Okapi from sentence_transformers import SentenceTransformer from sklearn.metrics.pairwise import cosine_similarity # 1. Prepare your data documents = [ "Podstack provides on-demand GPUs billed by the second.", "Hybrid search combines BM25 and vector embeddings for better recall.", "Deep learning models require high-performance A100 or H100 GPUs.", "Python functions can be deployed as serverless GPU endpoints." ] query = "How to run GPU functions on demand?" # 2. BM25 (Lexical Search) tokenized_corpus = [doc.split(" ") for doc in documents] bm25 = BM25Okapi(tokenized_corpus) lexical_scores = bm25.get_scores(query.split(" ")) # 3. Embeddings (Semantic Search) # Note: Run this on a Podstack GPU instance for production speeds model = SentenceTransformer('BAAI/bge-small-en-v1.5') doc_embeddings = model.encode(documents) query_embedding = model.encode([query]) semantic_scores = cosine_similarity(query_embedding, doc_embeddings)[0] # 4. Reciprocal Rank Fusion (RRF) def rrf_score(ranks, k=60): return sum(1.0 / (k + rank) for rank in ranks) # Combine and rank final_results = [] for i in range(len(documents)): # In a real app, you'd calculate actual rank positions # Here we use a weighted sum as a simplified fusion combined_score = (0.3 * lexical_scores[i]) + (0.7 * semantic_scores[i]) final_results.append((documents[i], combined_score)) final_results.sort(key=lambda x: x[1], reverse=True) for doc, score in final_results: print(f"Score: {score:.4f} | {doc}") ``` ## Practical Tips for Hybrid Search ### 1. Normalize Your Scores BM25 scores are unbounded (they can range from 0 to infinity), while cosine similarity is typically between -1 and 1. Before combining them, it is crucial to normalize both sets of scores to a 0-1 range, or use RRF, which relies on the *rank* (1st, 2nd, 3rd) rather than the raw score. ### 2. Tuning the Alpha In the fusion step, you will often see a parameter called `alpha`. An `alpha` of 1.0 is pure vector search; an `alpha` of 0.0 is pure BM25. For most RAG (Retrieval-Augmented Generation) applications, an alpha between 0.6 and 0.8 (weighting embeddings more heavily) tends to perform best. ### 3. Domain-Specific Tokenization If you are working in a niche field (like legal or medical), ensure your BM25 tokenizer doesn't strip out critical stop-words that might carry weight in that domain. ## Scaling with Podstack Running embedding models for millions of documents requires consistent, high-throughput compute. Podstack makes this transition seamless for ML engineers. Instead of managing complex infrastructure, you can wrap your embedding logic into a Python function and deploy it as a serverless GPU endpoint. You can spin up a dedicated worker to index your documents using the Podstack API: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` With Podstack’s per-second billing, you only pay for the exact time it takes to generate your embeddings. Once your vectors are stored, you can use Podstack's serverless inference to handle the query-time embedding generation, ensuring your hybrid search remains snappy and cost-effective. ## Conclusion Hybrid search is the gold standard for production-grade retrieval. By pairing the keyword-matching reliability of BM25 with the conceptual understanding of embeddings, you provide a search experience that handles both technical queries and natural language effortlessly. By leveraging Podstack's on-demand GPUs, you can ensure that the "semantic" half of your hybrid search remains fast, scalable, and easy to maintain. --- # Keeping secrets and API keys safe in ML pipelines Learn how to secure ML pipelines using environment variables, API best practices, and runtime secret injection for GPU jobs and serverless inference. Security · 2026-08-13 · 4 min read Managing credentials in machine learning pipelines presents a unique challenge. Unlike traditional web applications, ML workflows often span multiple environments: local notebooks for experimentation, distributed clusters for training, and serverless endpoints for inference. Hardcoding an API key for a vector database or a weights-and-biases logger might seem like a quick fix during a late-night debugging session, but it is a security debt that eventually comes due. Whether it’s an accidental Git commit or an exposed logging output, leaked secrets can lead to compromised data and runaway cloud costs. In this guide, we will walk through practical strategies to keep your ML secrets safe, from local development to production deployment. ## 1. Never Hardcode: Use Environment Variables The first rule of secret management is that secrets should never live in your source code. Instead, use environment variables. This decouples your configuration from your execution logic. In Python, the standard way to handle this is via the `os` module or the `python-dotenv` library for local development. ```python import os from dotenv import load_dotenv # Load variables from a .env file (local only) load_dotenv() # Access your keys huggingface_token = os.getenv("HF_TOKEN") database_url = os.getenv("DB_CONNECTION_STRING") if not huggingface_token: raise ValueError("HF_TOKEN not found in environment variables.") ``` **Pro Tip:** Add `.env` to your `.gitignore` immediately. For extra safety, create a `.env.example` file with the keys listed but the values blank, so teammates know which variables they need to provide. ## 2. Secrets in the API Workflow When working with infrastructure via an API, you often need to authenticate your local machine to the remote provider. For instance, when using the Podstack API, you should avoid passing keys as raw arguments in your shell history. Instead, export the key to your shell session: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` By using `export`, the key stays in memory for that terminal session and isn't written into script files that might be shared or version-controlled. ## 3. Injecting Secrets into GPU Jobs When you move from local code to a remote GPU job, your environment variables need to travel with your code—but securely. You shouldn't bake them into a Docker image, as images are often stored in registries where others might have access. The best practice is to inject secrets at runtime. When launching a job or a serverless inference endpoint, use the platform's native secret management system. This ensures that the secret is only decrypted and mounted into the container's environment when the GPU starts processing your task. ## 4. Scoping and Least Privilege One of the most common mistakes in ML engineering is using a "Master Admin" key for every task. If your inference endpoint only needs to read from an S3 bucket, don't give it a key that has delete permissions. * **Read-only keys:** Use these for fetching datasets or model weights. * **Write-only keys:** Use these for logging metrics or uploading checkpoints. * **Environment-specific keys:** Use different API keys for `development`, `staging`, and `production`. ## 5. Handling Secrets in Serverless Inference Serverless inference is particularly sensitive because endpoints are often public-facing. If your Python function calls an external API (like an LLM provider or a payment gateway), you must ensure the function itself doesn't log the secret to `stdout` or `stderr`. ML frameworks often log the entire environment during a crash. To prevent this, wrap your secret-accessing logic in try-except blocks that sanitize the error message before it hits the logs. ## Secure ML Workflows on Podstack Podstack is designed to make GPU orchestration seamless, and that includes security. Because Podstack bills by the second and scales your Python functions automatically, you need a way to ensure every spawned instance has the right credentials without manual intervention. When using the Podstack API to deploy on-demand jobs or serverless endpoints, you can manage your secrets through the Podstack dashboard or via the API's secret vault. For example, when deploying a GPU function: 1. Store your sensitive keys in the Podstack Secret Manager. 2. Reference them in your `podstack.yaml` or via the API flag `--env-secret HF_TOKEN=my_stored_secret`. 3. Podstack securely injects these into your Python GPU function at runtime. This approach ensures that even if you are running hundreds of parallel inference jobs across a fleet of H100s, your `PODSTACK_API_KEY` and third-party tokens remain encrypted at rest and protected during execution. By following these patterns—moving secrets to the environment, using runtime injection, and following the principle of least privilege—you can focus on optimizing your models without worrying about who might be watching your logs. --- # Mixed precision training explained: FP16, BF16 and FP8 Learn how to use FP16, BF16, and FP8 to double your training speed and reduce VRAM usage with practical PyTorch examples and hardware tips. Training · 2026-08-10 · 4 min read Modern deep learning models are growing exponentially in size, but our GPU memory remains a finite resource. If you’ve ever hit an `OutOfMemory` (OOM) error or felt that your training loops were sluggish, mixed precision training is the first optimization you should reach for. In this guide, we will break down the mechanics of FP16, BF16, and the emerging FP8 format, and show you how to implement them to maximize throughput on your GPU instances. ## The Numerical Landscape: FP32 vs. The Rest Traditionally, deep learning used **FP32 (Single Precision)**. It uses 32 bits to represent a number: 1 bit for the sign, 8 for the exponent, and 23 for the mantissa (precision). While accurate, it is computationally expensive and memory-intensive. Mixed precision training works by performing most operations in lower precision formats while keeping a "master copy" of weights in FP32 to ensure the model eventually converges. ### 1. FP16 (Half Precision) FP16 uses 16 bits: 5 for the exponent and 10 for the mantissa. * **Pros:** Significant speedups (up to 2-3x) and 50% less memory usage. * **Cons:** Small dynamic range. It is prone to "gradient underflow," where small gradients become zero, causing the model to stop learning. To fix this, we use **Loss Scaling**. ### 2. BF16 (Brain Floating Point) Developed to solve FP16’s limitations, BF16 also uses 16 bits but allocates them differently: 8 bits for the exponent (same as FP32) and 7 for the mantissa. * **Pros:** It handles large dynamic ranges without loss scaling. It is the "gold standard" for LLM training on modern hardware (NVIDIA Ampere architecture and newer). * **Cons:** Slightly less precise than FP16, but usually negligible for deep learning. ### 3. FP8 (The New Frontier) Introduced with the NVIDIA Hopper (H100) architecture, FP8 drops to just 8 bits. It comes in two variants: E4M3 (for weights/activations) and E5M2 (for gradients). * **Pros:** Massive throughput increases for inference and large-scale pre-training. * **Cons:** Requires specialized hardware and sophisticated scaling logic. ## Implementing Mixed Precision in Python Modern frameworks like PyTorch make switching to mixed precision remarkably easy using the `torch.cuda.amp` module (Automatic Mixed Precision). Here is a practical snippet for implementing FP16 with Loss Scaling: ```python import torch import torch.nn as nn from torch.cuda.amp import autocast, GradScaler # Define model and optimizer model = MyComplexModel().cuda() optimizer = torch.optim.Adam(model.parameters(), lr=1e-3) # Initialize the GradScaler for FP16 scaler = GradScaler() for data, target in dataloader: optimizer.zero_grad() # Runs the forward pass in FP16 with autocast(dtype=torch.float16): output = model(data.cuda()) loss = criterion(output, target.cuda()) # Scales loss, calls backward(), and unscales gradients for optimizer scaler.scale(loss).backward() # scaler.step() first unscales the gradients of the optimizer's assigned params. # If gradients contain infs or NaNs, optimizer.step() is skipped. scaler.step(optimizer) # Updates the scale for next iteration scaler.update() ``` If you are using an A100 or H100, you can often simplify this further by using `dtype=torch.bfloat16` inside `autocast` and removing the `GradScaler`, as BF16 is robust enough to handle gradients without scaling. ## Practical Tips for ML Engineers 1. **Check your Hardware:** FP16 is supported on almost all modern GPUs, but BF16 requires NVIDIA Ampere (A100, A30, A10) or newer. If you try to run BF16 on a T4 or V100, it will emulate it in FP32, resulting in a massive performance penalty. 2. **Batch Size Matters:** Because mixed precision reduces memory usage by half, you should double your batch size to fully saturate the GPU’s Tensor Cores. 3. **Mind the Tensor Cores:** For maximum efficiency, ensure your layer dimensions (input/output features) are multiples of 8 (or 16/32 for FP8). This allows the hardware to utilize specialized matrix math units. 4. **Watch the Loss:** If you see `NaN` losses immediately with FP16, your loss scaling might be failing. Try switching to BF16 if your hardware supports it. ## Running at Scale on Podstack When you're ready to move from local experimentation to heavy-duty training, Podstack provides the infrastructure to run these workloads with zero friction. Whether you need a single A100 for a few minutes or a cluster of H100s for a week, the per-second billing ensures you only pay for the compute you actually use. To get started, simply set your API key and deploy your training script as a job: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Because Podstack treats GPU functions as first-class citizens, you can also wrap your inference logic in a serverless endpoint. By using FP16 or FP8 for your inference functions, you can significantly reduce latency and lower your cost per request, as Podstack only bills for the active execution time of the function. ## Conclusion Mixed precision is no longer an "advanced" technique; it is a necessity for modern ML. By understanding the trade-offs between FP16, BF16, and FP8, you can drastically reduce training time and hardware costs. Start by auditing your current training scripts—switching just a few lines of code to enable `autocast` on a Podstack A100 could cut your bill in half while doubling your iteration speed. --- # Monitoring GPU utilization and spotting bottlenecks Learn how to identify data starvation, optimize VRAM usage, and use tools like nvidia-smi to eliminate GPU bottlenecks and reduce costs on Podstack. Infrastructure · 2026-08-07 · 4 min read Monitoring GPU utilization isn’t just about making sure your hardware is "on." For machine learning engineers, it is the difference between a model that trains in four hours and one that drags on for twelve. When you are billed by the second, every percentage point of idle time is literal wasted capital. In this guide, we will walk through the practical steps of identifying bottlenecks in your GPU workloads, from high-level monitoring to deep-dive profiling, and how to resolve them to maximize your throughput. ## The Three Pillars of GPU Monitoring To understand your workload, you need to track three primary metrics: 1. **GPU Utilization:** The percentage of time one or more kernels were executing on the GPU. If this is low, your GPU is waiting for data. 2. **Memory Usage (VRAM):** How much space your weights and buffers are taking up. High VRAM usage is fine; hitting the limit causes "Out of Memory" (OOM) errors. 3. **Power Draw and Thermal Throttling:** If the GPU is drawing significantly less power than its TDP (Thermal Design Power), it might be idling or being throttled due to heat. ## Identifying the "Data Starvation" Bottleneck The most common bottleneck in ML pipelines is the CPU-to-GPU handoff. If your preprocessing (image augmentation, tokenization, shuffling) happens on the CPU and can't keep up with the GPU's processing speed, the GPU sits idle. You can spot this using `nvidia-smi` or by logging metrics directly in your Python training script. If your utilization graphs look like a "sawtooth" (spiking to 90% then dropping to 0% repeatedly), you are data-starved. ```python import torch from torch.utils.data import DataLoader # A common fix for data bottlenecks dataloader = DataLoader( dataset, batch_size=64, shuffle=True, num_workers=4, # Use multiple CPU cores for loading pin_memory=True, # Speeds up CPU-to-GPU transfer prefetch_factor=2 # Loads next batches while GPU is busy ) # Check utilization programmatically def print_gpu_stats(): if torch.cuda.is_available(): print(f"Allocated: {torch.cuda.memory_allocated() / 1024**2:.2f} MB") print(f"Cached: {torch.cuda.memory_reserved() / 1024**2:.2f} MB") ``` ## Spotting Kernel Bottlenecks Sometimes your GPU utilization is at 100%, but your training is still slow. This often points to **low arithmetic intensity**. This happens when the GPU spends more time moving data between its own internal memory registers than actually performing math. **Common causes:** * **Small Batch Sizes:** The GPU thrives on parallelism. If your batch size is too small, you aren't filling the thousands of CUDA cores available. * **Precision:** Using `float32` when `float16` or `bfloat16` (Mixed Precision) would suffice. Modern GPUs have dedicated Tensor Cores for lower-precision math that are significantly faster. ## Practical Steps to Debug Bottlenecks 1. **Baseline with `nvidia-smi`:** Run `nvidia-smi -l 1` in your terminal to see a 1-second refresh of GPU utilization. Watch the `Volatile Uncorr. ECC` and `GPU-Util` columns. 2. **Profile the code:** Use the PyTorch Profiler or `cProfile` to see which specific function calls are taking the most time. 3. **Isolate the I/O:** Run a "dummy" training loop where you pass random tensors of the same shape to the model instead of loading from disk. If the speed increases dramatically, your bottleneck is your storage or preprocessing. ## Optimizing for Serverless and On-Demand Environments In an environment where you are billed per second, you want your GPU to spin up, hit 100% utilization immediately, and shut down. Long setup times or slow weight loading are "hidden" bottlenecks. Always serialize your models into efficient formats like Safetensors or ONNX to decrease the time spent in the "loading" phase before the GPU starts working. ## Streamlining Performance with Podstack Podstack is designed to eliminate the overhead that usually causes these bottlenecks. Because Podstack bills by the second, monitoring is built into the workflow. When you deploy a Python GPU function or a long-running job, you want to ensure your environment is configured correctly from the start. You can trigger a job or check your current deployments using the Podstack API. By setting your `PODSTACK_API_KEY`, you can automate the spinning up of high-performance instances that match your memory requirements. To launch a monitored job: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Podstack’s infrastructure minimizes the latency between the CPU and GPU, providing high-bandwidth interconnects that help prevent the data starvation issues mentioned above. If you notice your utilization is low during a serverless inference call, you can quickly adjust your concurrency settings or switch GPU types via the API to find the "Goldilocks" zone of performance and cost. ## Summary Monitoring GPU utilization isn't just about watching a percentage; it's about ensuring your code is worthy of the hardware it's running on. By identifying whether your bottleneck is in the CPU data pipeline, VRAM limits, or kernel efficiency, you can significantly reduce your training costs and iteration times. Start by checking your `num_workers`, move to mixed-precision training, and use a cloud that rewards your efficiency with per-second billing. --- # Multi-agent systems: supervisor and worker patterns Learn how to build resilient multi-agent systems using the supervisor-worker pattern with specialized GPU workers on Podstack. Agents · 2026-08-04 · 4 min read Multi-agent systems (MAS) are quickly becoming the standard for solving complex, non-linear problems that a single LLM prompt cannot handle. By breaking down a large task into specialized roles, you increase reliability, reduce hallucination, and allow for parallel execution. One of the most robust architectures for this is the **Supervisor and Worker pattern**. In this model, a supervisor agent acts as the orchestrator, delegating tasks to specialized workers, reviewing their output, and deciding when the job is complete. ## The Architecture: Supervisor vs. Worker In a standard sequential chain, Agent A passes data to Agent B, which passes it to Agent C. This is fragile; if Agent B fails, the whole chain collapses. The Supervisor pattern introduces a hub-and-spoke model: 1. **The Supervisor:** Responsible for state management, task routing, and quality control. It holds the "master plan." 2. **The Workers:** Specialized agents with access to specific tools (e.g., a search tool, a code interpreter, or a database connector). They perform one job and report back. This pattern is particularly effective for GPU-intensive workloads where different workers might require different hardware profiles—for example, a "Researcher" agent might need a small model for fast inference, while a "Coder" agent might require a massive parameter model for complex logic. ## Implementing the Pattern with Python To build this effectively, you need a way to manage state and route calls. Using a framework like LangGraph or a custom state machine, you can define your agents as nodes. Below is a practical example of how to structure a supervisor that delegates to a "Coder" and a "Reviewer." ```python import os from typing import TypedDict, Annotated, List from podstack import PodstackClient # Assuming Podstack's Python SDK # Configuration client = PodstackClient(api_key=os.getenv("PODSTACK_API_KEY")) class AgentState(TypedDict): task: str code: str feedback: str iterations: int status: str def supervisor(state: AgentState): # Logic to decide which worker to call next if not state["code"]: return "coder" elif state["iterations"] < 3 and "FAIL" in state["feedback"]: return "coder" else: return "end" def coder_worker(state: AgentState): # This runs on a Podstack GPU endpoint response = client.inference.run( model="llama-3-70b-instruct", prompt=f"Write code for: {state['task']}. Previous feedback: {state['feedback']}", gpu_type="a100-80gb" ) return {"code": response.text, "iterations": state["iterations"] + 1} def reviewer_worker(state: AgentState): # Runs a validation pass response = client.inference.run( model="llama-3-8b-instruct", prompt=f"Review this code for bugs: {state['code']}", gpu_type="a10g" ) return {"feedback": response.text} ``` ## Scaling with GPU Parallelism The primary bottleneck in multi-agent systems is latency. If your supervisor has to wait for four workers to finish sequentially, the user experience suffers. To optimize this: * **Parallel Execution:** If the supervisor identifies three sub-tasks that are independent, trigger them as concurrent jobs. * **Dynamic Scaling:** Use serverless inference for the supervisor (low compute, high logic) and dedicated on-demand GPUs for the heavy-lifting workers. * **Caching:** Store intermediate worker results so the supervisor doesn't re-run successful steps if a later step fails. ## Managing the Workflow via the API When moving from local development to production, you need to deploy your workers as scalable endpoints. Using the Podstack API, you can package your agent functions as serverless GPU functions that only charge you while the agent is actively processing a prompt. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` This approach allows your supervisor to reside in a lightweight container while spinning up massive GPU power for workers only when the task demands it. ## Practical Tips for Success 1. **Define Clear Exit Criteria:** A supervisor can get stuck in a loop if the worker keeps failing. Always implement a `max_iterations` counter in your state. 2. **Specialized Prompting:** Don't use a generic prompt for all workers. Give them "system personas" (e.g., "You are a Senior DevOps Engineer"). 3. **State Trimming:** LLM context windows fill up quickly in multi-agent loops. Ensure your supervisor summarizes the history instead of passing the full transcript every time. 4. **Error Handling:** If a worker times out, the supervisor should be programmed to either retry or attempt the task with a different model. ## Orchestrating Agents on Podstack Multi-agent systems are resource-hungry. The supervisor-worker pattern thrives when you have access to heterogenous compute—the ability to switch between a cost-effective A10G for simple tasks and a high-performance A100 for complex reasoning. Podstack’s per-second billing is uniquely suited for this architecture. Instead of paying for an idle cluster while your supervisor "thinks," you only pay for the high-performance GPU during the exact window the worker is executing its task. By utilizing the Podstack API and Python SDK, you can build a self-scaling agentic workforce that handles complex ML workflows without the overhead of traditional infrastructure management. --- # Preparing instruction datasets for supervised fine-tuning Learn how to format, clean, and synthesize high-quality instruction datasets for Supervised Fine-Tuning (SFT) to build better specialized LLMs. Data · 2026-08-01 · 4 min read Supervised Fine-Tuning (SFT) is the critical bridge between a raw base model and a functional AI assistant. While base models excel at predicting the next token, SFT teaches them to follow instructions, maintain a specific persona, and output data in structured formats. However, the quality of your fine-tuned model is directly proportional to the quality of your training data. A dataset with inconsistent formatting, noisy labels, or poor diversity will lead to a model that hallucinates or fails to follow prompts. This guide covers the practical workflow for preparing high-quality instruction datasets for SFT. ## 1. Choosing Your Data Format Most modern fine-tuning libraries, such as Axolotl or Hugging Face's TRL, expect data in one of two primary formats: **Instruction-Input-Output** or **Conversational (ChatML)**. For SFT, the conversational format is increasingly preferred because it handles multi-turn dialogues more naturally. A standard JSONL entry for conversational tuning typically looks like this: ```json { "messages": [ {"role": "system", "content": "You are a helpful coding assistant."}, {"role": "user", "content": "How do I reverse a list in Python?"}, {"role": "assistant", "content": "You can use the `.reverse()` method or slicing `[::-1]`."} ] } ``` ## 2. Data Synthesis and Augmentation Getting thousands of hand-written examples is expensive. Most engineers use a "Teacher Model" (like a larger Llama 3 or Mixtral variant) to generate synthetic instructions. If you have a collection of raw documents, you can use a Python script to transform them into instruction pairs. The goal is to generate a diverse set of questions that your raw data can answer. ```python import json def format_sft_entry(system_prompt, user_query, assistant_response): return { "messages": [ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_query}, {"role": "assistant", "content": assistant_response} ] } # Example of converting a raw internal FAQ to SFT format raw_data = [ {"q": "API Limit?", "a": "1000 requests per second."} ] formatted_data = [ format_sft_entry( "You are a technical support bot for Podstack.", item['q'], item['a'] ) for item in raw_data ] with open("train.jsonl", "w") as f: for entry in formatted_data: f.write(json.dumps(entry) + "\n") ``` ## 3. Cleaning and Quality Control Before you touch a GPU, you must prune your dataset. Here are three non-negotiable checks: * **Length Filtering:** Remove examples that are too short to be meaningful or so long they exceed your target context window (e.g., 4096 tokens). Truncating during training can cut off the "assistant" response, teaching the model to stop abruptly. * **Format Validation:** Ensure every JSON object is valid. One missing comma in a 50,000-line JSONL file can crash a multi-node training job three hours in. * **De-duplication:** Use MinHash or simple string matching to remove near-duplicate instructions. Over-representing specific phrasing causes the model to overfit and lose its generalization capabilities. ## 4. Tokenization and Prompt Templates Every model has a specific prompt template (e.g., Llama-3 uses `<|begin_of_text|>`, while Mistral uses `[INST]`). When preparing your dataset, you don't necessarily need to bake these tokens into the JSONL file. Most SFT trainers will apply the template automatically using a `tokenizer_config.json`. However, you *should* calculate the token counts of your prepared dataset. This helps you estimate the VRAM required and decide if you need to use techniques like Packing (combining multiple short sequences into a single block) to increase training efficiency. ## 5. Practical Tips for Better SFT * **Balance your categories:** If 90% of your data is about Python and 10% is about SQL, your model will likely struggle with SQL. Aim for an even distribution. * **System Prompt Variation:** Don't use the exact same system prompt for every single entry. Subtle variations help the model understand the *intent* of the system role rather than just memorizing a specific string. * **Quality over Quantity:** 1,000 high-quality, human-curated examples often outperform 50,000 noisy, machine-generated ones. ## Running the Job on Podstack Once your `train.jsonl` is ready, the next step is moving to a GPU environment. Podstack makes this seamless by allowing you to trigger training jobs directly via the API or deploy a Python function as a GPU worker. First, ensure your `PODSTACK_API_KEY` is set in your environment. You can then use the Podstack API to spin up an on-demand instance with the specific VRAM you need (like an A100 or H100) to run your training script. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Because Podstack bills per second, you can upload your dataset, run your SFT job, and tear it down the moment the weights are saved to your storage, ensuring you only pay for the compute used during the actual training iterations. ## Summary Dataset preparation is 80% of the work in fine-tuning. By focusing on conversational formatting, rigorous cleaning, and diverse synthesis, you create a foundation for a performant model. Once your data is staged, Podstack provides the high-performance GPU infrastructure to turn that data into a specialized model with minimal friction. --- # QLoRA on a budget: fine-tune a 70B model on one GPU Learn how to use QLoRA and Podstack to fine-tune a 70B parameter model on a single 80GB GPU, optimizing for memory efficiency and cost-per-second billing. Training · 2026-07-29 · 3 min read Fine-tuning large language models (LLMs) used to be a luxury reserved for those with massive compute clusters. With the release of Llama 3 and other high-performance 70B models, the barrier to entry has moved from "intelligence" to "infrastructure." However, thanks to **QLoRA (Quantized Low-Rank Adaptation)** and memory-efficient techniques, you no longer need an 8-GPU node to customize the world’s best open-weight models. In this guide, we’ll walk through how to fine-tune a 70B parameter model on a single 80GB GPU (like an NVIDIA A100 or H100) using Podstack, keeping your costs low and your iteration speed high. ## Why 70B on a Single GPU? A 70B model in full 16-bit precision requires roughly 140GB of VRAM just to load the weights—long before you even think about gradients or optimizer states. QLoRA changes the math by: 1. **4-bit Quantization:** Reducing the base model weights to 4-bit, shrinking the 140GB footprint to roughly 35-40GB. 2. **Low-Rank Adapters:** Only training a small fraction of parameters (the "adapters"), which drastically reduces the memory needed for gradients. 3. **Paged Optimizers:** Offloading optimizer states to CPU memory when necessary to prevent Out-of-Memory (OOM) errors. This allows us to fit the model, the data, and the training overhead into a single 80GB VRAM envelope. ## Step 1: Setting Up the Environment First, ensure you have your `PODSTACK_API_KEY` configured in your environment. We will use the Podstack API to spin up a high-memory GPU instance. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Once inside your container, install the essential libraries: `bitsandbytes` (for quantization), `peft` (for LoRA), and `trl` (for the SFT trainer). ```bash pip install -q -U bitsandbytes transformers peft accelerate datasets trl ``` ## Step 2: Configuring 4-bit Quantization The secret sauce is the `BitsAndBytesConfig`. We use `nf4` (NormalFloat 4), which is theoretically optimal for normally distributed weights like those found in LLMs. ```python import torch from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig from peft import LoraConfig, get_peft_model model_id = "meta-llama/Meta-Llama-3-70B-Instruct" bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16 ) model = AutoModelForCausalLM.from_pretrained( model_id, quantization_config=bnb_config, device_map="auto", token=True # Ensure your HF_TOKEN is set ) ``` ## Step 3: Defining the LoRA Adapter Instead of updating all 70 billion parameters, we target the linear layers (specifically the attention projections). This reduces the trainable parameters to less than 1% of the original model. ```python lora_config = LoraConfig( r=8, lora_alpha=32, target_modules=["q_proj", "v_proj", "k_proj", "o_proj"], lora_dropout=0.05, bias="none", task_type="CAUSAL_LM" ) model = get_peft_model(model, lora_config) model.print_trainable_parameters() ``` ## Step 4: Memory-Efficient Training To stay within the 80GB limit, use the `SFTTrainer` from the `trl` library with specific flags to save memory: - **Gradient Checkpointing:** Trades compute for memory by re-calculating activations during the backward pass. - **Groupeded Batching:** Ensures sequences of similar lengths are batched together to reduce padding waste. ```python from trl import SFTTrainer from transformers import TrainingArguments training_args = TrainingArguments( output_dir="./llama-70b-fine-tuned", per_device_train_batch_size=1, gradient_accumulation_steps=4, learning_rate=2e-4, logging_steps=10, bf16=True, optim="paged_adamw_32bit", # Crucial for saving VRAM save_strategy="epoch", gradient_checkpointing=True, max_steps=500 ) trainer = SFTTrainer( model=model, train_dataset=dataset, peft_config=lora_config, max_seq_length=2048, tokenizer=tokenizer, args=training_args, ) trainer.train() ``` ## Practical Tips for Success 1. **Monitor VRAM Spikes:** Use `watch nvidia-smi` in a separate terminal. If you hit OOM, reduce your `max_seq_length` or increase `gradient_accumulation_steps` while keeping `per_device_train_batch_size` at 1. 2. **Dataset Quality > Quantity:** For 70B models, 1,000 high-quality examples often outperform 50,000 noisy ones. 3. **Use Flash Attention 2:** If your GPU supports it (A100/H100), ensure `attn_implementation="flash_attention_2"` is passed to `from_pretrained`. It significantly speeds up training and reduces memory usage. ## Scaling with Podstack Fine-tuning a 70B model doesn't have to be an expensive architectural hurdle. On Podstack, you can spin up an 80GB GPU, run your QLoRA job, and shut it down the second it's finished. Because Podstack bills per second, you aren't paying for setup time or idle resources. Once your training is complete, you can deploy the resulting LoRA adapters as a serverless endpoint using the same Podstack API, allowing you to serve a 70B-grade intelligence without managing the underlying hardware. Ready to start? Grab your API key and deploy your first 70B trainer today. --- # Quantization for inference: GPTQ, AWQ and GGUF compared Compare GPTQ, AWQ, and GGUF quantization formats to optimize LLM inference speed and VRAM usage on Podstack's per-second GPU cloud. Inference · 2026-07-26 · 3 min read Quantization has become the cornerstone of modern LLM deployment. As models grow in size, fitting a 70B parameter model into consumer or mid-range enterprise GPUs requires more than just raw VRAM—it requires efficient weight compression. For ML engineers deploying on Podstack, choosing the right quantization format is the difference between sub-second latency and out-of-memory (OOM) errors. In this post, we break down the three industry standards: GPTQ, AWQ, and GGUF. ## Understanding the Landscape Quantization reduces the precision of model weights (typically from FP16 to 4-bit or 8-bit). While this introduces a slight "perplexity" hit, the gains in throughput and memory efficiency are massive. * **GPTQ (Generalized Post-Training Quantization):** A layer-wise compression method that excels at static 4-bit quantization. It is highly optimized for inference on NVIDIA GPUs using libraries like `AutoGPTQ` or `vLLM`. * **AWQ (Activation-aware Weight Quantization):** A newer approach that protects "salient" weights—the small percentage of weights that are most important for model accuracy. AWQ typically offers better generalization and slightly better performance than GPTQ at 4-bit. * **GGUF (GPT-Generated Unified Format):** The successor to GGML, designed by the llama.cpp community. It is unique because it is designed for CPU/GPU hybrid inference and is the standard for edge deployment, though it is increasingly used in high-performance cloud environments for its flexibility. ## GPTQ vs. AWQ: The GPU Battle If you are running dedicated inference endpoints on Podstack, your choice usually falls between GPTQ and AWQ. **AWQ** is generally considered the current state-of-the-art for 4-bit precision. It doesn't rely on the calibration data as heavily as GPTQ, making it more robust across different prompts. However, **GPTQ** has been around longer and has slightly better integration with legacy systems. **Use GPTQ if:** * You are using older NVIDIA architectures. * You need maximum compatibility with the `Transformers` library. **Use AWQ if:** * You want the best balance of speed and accuracy. * You are deploying on modern Ampere or Hopper GPUs (A100, H100, or A6000s) on Podstack. ## GGUF: The Flexibility King GGUF is a different beast. Unlike the other two, which are typically loaded via Python/Transformers, GGUF models are single-file binaries. They allow for "offloading" layers—if a model is too big for your GPU VRAM, you can put 30 layers on the GPU and the remaining 10 on the CPU. While Podstack provides high-performance GPUs that usually fit these models, GGUF is excellent for testing massive models (like Llama-3 70B) on smaller GPU instances. ## Practical Implementation: Deploying an AWQ Model Deploying a quantized model on Podstack is straightforward. Below is a practical example of how to serve a Llama-3-8B-AWQ model using `vLLM`, which provides an OpenAI-compatible API. First, ensure your environment is set up: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Once your node is live, you can initialize the quantized inference server: ```python from vllm import LLM, SamplingParams # Load the AWQ model # vLLM automatically detects the quantization method from the config model_id = "casperhansen/llama-3-8b-instruct-awq" llm = LLM(model=model_id, quantization="awq", dtype="half") sampling_params = SamplingParams(temperature=0.7, top_p=0.95, max_tokens=256) outputs = llm.generate(["What are the benefits of per-second billing for GPU clouds?"], sampling_params) for output in outputs: print(f"Generated text: {output.outputs[0].text}") ``` ## Practical Tips for ML Engineers 1. **Calibration Matters:** When quantizing your own models, the "calibration dataset" used during the process matters. Use data that closely resembles your production traffic to minimize accuracy loss. 2. **VRAM Calculation:** As a rule of thumb, a 4-bit quantized model requires approximately 0.7 GB of VRAM per billion parameters, plus extra for the KV cache (context window). A 70B model in 4-bit needs ~48GB to ~52GB of VRAM to run comfortably. 3. **Check Kernel Support:** Ensure your inference engine (vllm, TGI, or LMDeploy) has the specific kernels for the quantization format you choose. AWQ requires specific kernels to see the speedup; otherwise, it may be slower than FP16. ## Scaling on Podstack Choosing between GPTQ, AWQ, and GGUF depends on your specific performance requirements. For production-grade, high-throughput Python functions, **AWQ** is currently the gold standard. On Podstack, you can experiment with all three formats without heavy upfront costs. Because we offer **per-second billing**, you can spin up an A100 node, benchmark a GPTQ model against an AWQ model for 15 minutes, and tear it down, paying only for the exact time used. Whether you are deploying serverless inference endpoints or long-running GPU jobs, using the Podstack API makes it easy to swap model weights and formats on the fly. By leveraging quantization, you can run larger, more capable models on cheaper hardware, significantly optimizing your infrastructure spend. --- # Reranking retrieved passages for better accuracy Learn how to implement a two-stage retrieval pipeline using Cross-Encoders and reranking to significantly improve the precision of your RAG applications. RAG · 2026-07-23 · 3 min read Retrieving the right information is only half the battle in modern RAG (Retrieval-Augmented Generation) pipelines. While vector databases and embedding models are excellent at finding "semantically similar" documents across massive datasets, they often struggle with the nuances of relevance. A document might share many keywords or concepts with a query but fail to actually answer the specific question asked. This is where **reranking** comes in. By adding a second stage to your retrieval pipeline, you can significantly boost the precision of your context, leading to higher-quality LLM responses and fewer hallucinations. ## Why Retrieval Alone Isn't Enough Standard retrieval uses Bi-Encoders (like `all-MiniLM-L6-v2` or `BGE`). These models turn text into vectors independently. At query time, we perform a fast similarity search (cosine similarity). It’s efficient, but it loses the granular interaction between the query and the document. Rerankers typically use **Cross-Encoders**. A Cross-Encoder takes both the query and a candidate document as a single input pair, allowing the model to attend to the relationships between every word in the query and every word in the passage. This produces a much more accurate relevance score, but it is computationally expensive—too expensive to run against millions of documents. The practical solution is a "Two-Stage" pipeline: 1. **Retrieval:** Use a fast vector search to get the top 50-100 candidates. 2. **Reranking:** Use a Cross-Encoder to re-order those 100 candidates and keep the top 5. ## Implementing a Reranking Pipeline To implement this efficiently, you need a GPU-backed environment. Below is a practical implementation using the popular `sentence-transformers` library and a BGE reranker model. ### 1. Setup the Environment First, ensure you have your environment ready. On Podstack, you can deploy this as a serverless function or a long-running endpoint. ```bash pip install sentence-transformers podstack ``` ### 2. The Reranking Logic The following Python snippet demonstrates how to take a set of initial results from a vector store and re-score them. ```python from sentence_transformers import CrossEncoder # Initialize the Cross-Encoder model # BGE-Reranker is currently state-of-the-art for this task model = CrossEncoder('BAAI/bge-reranker-base', device='cuda') def rerank_passages(query, passages): # Construct pairs: [[query, doc1], [query, doc2], ...] model_inputs = [[query, p['text']] for p in passages] # Predict relevance scores scores = model.predict(model_inputs) # Pair scores with original metadata and sort for i, score in enumerate(scores): passages[i]['rerank_score'] = float(score) # Sort by descending score reranked = sorted(passages, key=lambda x: x['rerank_score'], reverse=True) return reranked # Example usage query = "How do I optimize GPU memory for inference?" initial_results = [ {"text": "GPU memory can be managed using quantization...", "id": 1}, {"text": "A GPU is a graphics processing unit...", "id": 2}, {"text": "To reduce VRAM usage, try Flash Attention or 4-bit loading.", "id": 3} ] refined_results = rerank_passages(query, initial_results) for res in refined_results: print(f"Score: {res['rerank_score']:.4f} | Content: {res['text'][:50]}...") ``` ## Practical Tips for Production Reranking 1. **Don't Rerank Everything:** The latency of a Cross-Encoder grows linearly with the number of documents. Limit your second stage to the top 50 or 100 results from your vector search. 2. **Max Sequence Length:** Be mindful of the context window of your reranker (usually 512 tokens). If your passages are very long, the model will truncate the end, potentially missing the most relevant part of the text. 3. **Batching:** If you are processing multiple queries simultaneously, batch the reranking calls to maximize GPU throughput. 4. **Thresholding:** After reranking, you might find that even the "top" result has a low score. Implement a minimum score threshold to prevent the LLM from being fed irrelevant "noise" which can lead to hallucination. ## Deploying on Podstack Reranking models like `bge-reranker-large` require significant VRAM and compute to keep latency low (sub-100ms). Podstack provides the ideal infrastructure for this by allowing you to deploy these models as serverless GPU functions or dedicated endpoints. Using the Podstack API, you can wrap your reranking logic into a high-performance endpoint that scales based on demand. Because Podstack bills per second, you only pay for the exact moment the GPU is re-scoring your documents, making it significantly more cost-effective than keeping a heavy GPU instance running 24/7. To deploy, set your API key: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` This allows your main application logic to remain lightweight, offloading the heavy matrix multiplications to Podstack’s optimized GPU cloud. ## Conclusion Reranking is the most effective "bang-for-your-buck" upgrade you can give a RAG system. It bridges the gap between the speed of vector search and the intelligence of deep language understanding. By integrating a Cross-Encoder into your workflow on Podstack, you ensure that your LLM always receives the most accurate, contextually relevant information possible. --- # Reserved GPU clusters for large training runs Learn how to provision and manage reserved GPU clusters for large-scale distributed ML training using Podstack’s API and high-performance infrastructure. Infrastructure · 2026-07-20 · 3 min read Modern machine learning teams have outgrown the era of "spinning up a single instance and hoping for the best." As models scale from millions to billions of parameters, the infrastructure requirement shifts from simple compute to tightly coupled clusters. When you are running a multi-day training job across dozens of A100s or H100s, any interruption or networking bottleneck translates directly into wasted budget. For large-scale training runs, standard on-demand instances can sometimes be preempted or suffer from sub-optimal inter-node communication. This is where **Reserved GPU Clusters** come in. By shifting from ad-hoc instances to a reserved, dedicated cluster, you ensure consistent high-performance networking (RDMA/InfiniBand) and 100% availability for the duration of your run. ## Why Reserving Matters for Large Training Training a large model—whether it’s an LLM or a high-fidelity diffusion model—requires data parallelism or sharding (like ZeRO or FSDP). These techniques are extremely sensitive to latency. 1. **Guaranteed Availability:** Large runs involve coordinated checkpoints. If one node fails or is reclaimed, the entire job stalls. Reservations guarantee your hardware is there for the long haul. 2. **Network Locality:** In a reserved cluster, your GPUs are physically co-located in the same rack or leaf switch, providing the highest possible bandwidth for gradient synchronization. 3. **Cost Predictability:** While Podstack offers per-second billing for standard jobs, large training runs benefit from the fixed-cost structure of a reservation, eliminating the overhead of frequent setup and teardown. ## Architecting the Run Before launching, you need to ensure your environment is containerized. For large runs, the most efficient path is to define a `podstack.yaml` configuration that describes your cluster requirements: the number of nodes, the specific GPU type, and the shared volume where your dataset resides. ### Step 1: Initialize Your Cluster Configuration First, ensure your API is authenticated. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Next, define your cluster. A typical 8-node H100 cluster for a PyTorch FSDP job looks like this in your local configuration: ```yaml cluster: name: "llm-finetune-alpha" gpu_type: "h100" nodes: 8 gpus_per_node: 8 storage: - name: "training-data" mount_path: "/data" ``` ### Step 2: Provisioning via the API Instead of requesting individual instances, you command Podstack to reserve the entire block. This ensures all nodes are provisioned in the same high-speed fabric. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Once the cluster is "Ready," you can deploy your training script across all nodes simultaneously. ## Orchestrating the Training Script For distributed training, we recommend using `torchrun`. It handles the `RANK`, `WORLD_SIZE`, and `MASTER_ADDR` environment variables required for nodes to communicate. Here is a simplified Python pattern for a distributed training entry point that utilizes Podstack’s environment: ```python import os import torch import torch.distributed as dist from torch.nn.parallel import DistributedDataParallel as DDP def setup(): # Podstack automatically populates these in cluster environments rank = int(os.environ["RANK"]) world_size = int(os.environ["WORLD_SIZE"]) master_addr = os.environ["MASTER_ADDR"] master_port = os.environ["MASTER_PORT"] dist.init_process_group( backend="nccl", init_method=f"tcp://{master_addr}:{master_port}", rank=rank, world_size=world_size ) def train(): setup() device = torch.device(f"cuda:{os.environ['LOCAL_RANK']}") # Your model and data loading logic here # model = MyLargeModel().to(device) # model = DDP(model, device_ids=[device]) print(f"Rank {os.environ['RANK']} initialized and training...") if __name__ == "__main__": train() ``` You can trigger this across the entire reservation using: `podstack clusters run "torchrun --nproc_per_node=8 train.py"` ## Practical Tips for Large Training Runs 1. **Automated Checkpointing:** Never rely on a single disk. Use Podstack’s persistent storage volumes to save checkpoints every few hours. If a software-level crash occurs, you can resume without losing days of progress. 2. **Monitor NCCL Performance:** Use the `NCCL_DEBUG=INFO` environment variable during your first few iterations to verify that your nodes are communicating over the fastest available interface. 3. **Warm-up Rounds:** Before starting a 48-hour run, perform a "dry run" of 10 steps. Check the logs across all nodes to ensure there are no CUDA version mismatches or NCCL timeouts. 4. **Health Checks:** Use `podstack clusters status --watch` to monitor the heartbeat of your nodes. ## Scaling with Podstack Large-scale AI training is no longer reserved for companies with their own data centers. With Podstack, you get the performance of a dedicated cluster with the flexibility of a modern cloud. By using our reserved GPU clusters, you eliminate the "noisy neighbor" effect and ensure your training job has the dedicated bandwidth it needs to converge quickly. Whether you are fine-tuning a Llama-3-70B model or training a custom vision transformer from scratch, Podstack’s per-second billing within your reservation ensures you only pay for the compute you actually use, backed by the reliability of a dedicated hardware stack. Use the Podstack API today to reserve your first H100 or A100 cluster and stop worrying about resource availability. --- # RLHF vs DPO vs ORPO: which alignment method to use Compare RLHF, DPO, and ORPO to find the best LLM alignment strategy, with practical code examples and tips for running jobs on Podstack GPUs. Training · 2026-07-17 · 4 min read Choosing the right alignment technique is one of the most critical decisions when fine-tuning Large Language Models (LLMs). While Supervised Fine-Tuning (SFT) teaches a model how to answer, alignment methods like RLHF, DPO, and ORPO teach a model what users prefer—balancing helpfulness with safety. For engineers building on Podstack, selecting the right method is a trade-off between computational overhead, data complexity, and final model performance. Here is a breakdown of how these methods work and which one you should choose for your next GPU job. ## RLHF: The Gold Standard (with High Overhead) Reinforcement Learning from Human Feedback (RLHF) was the pioneer. It traditionally involves a three-step process: 1. **SFT Phase:** Fine-tune the base model on high-quality demonstrations. 2. **Reward Modeling:** Train a separate model to predict which output a human would prefer. 3. **PPO Optimization:** Use Proximal Policy Optimization (PPO) to fine-tune the SFT model using the Reward Model. **When to use it:** Use RLHF when you need the absolute highest ceiling for performance and have a massive budget for compute and human labeling. **The Catch:** It is notoriously unstable. You have to keep four models in VRAM simultaneously (Policy, Reference, Reward, and Value models), making it extremely memory-intensive even on H100s. ## DPO: The Practical Successor Direct Preference Optimization (DPO) revolutionized alignment by eliminating the need for a separate reward model and the complexities of reinforcement learning. DPO treats alignment as a simple classification problem on preference pairs (chosen vs. rejected responses). **When to use it:** DPO is currently the industry standard for most production models. It is more stable than RLHF, easier to tune, and requires significantly less VRAM because you only need the policy model and a frozen reference model. **The Catch:** DPO can be prone to overfitting and often requires a very high-quality SFT model as a starting point. If the SFT model hasn't seen the data distribution used in DPO, performance can degrade. ## ORPO: The New Efficient Frontier Odds Ratio Preference Optimization (ORPO) is the newest contender. Unlike the others, ORPO does not require a separate SFT stage. It combines the instruction-tuning and preference alignment into a single objective function. It uses an odds ratio penalty to discourage the model from generating rejected responses while simultaneously learning the task. **When to use it:** Use ORPO if you want to save time and compute. Since it bypasses the SFT phase, it reduces the training pipeline complexity significantly. It is ideal for developers who want to go from a base model to an aligned chat model in a single run. ## Comparative Summary | Method | Complexity | GPU Memory | Stages | Stability | | :--- | :--- | :--- | :--- | :--- | | **RLHF** | Extreme | Very High | 3 | Low | | **DPO** | Moderate | Medium | 2 (SFT + DPO) | High | | **ORPO** | Low | Medium | 1 | High | ## Implementation Example: Running DPO Using the `trl` library, implementing DPO is straightforward. On Podstack, you can wrap this in a Python function and trigger it as a remote GPU job. ```python from trl import DPOConfig, DPOTrainer from transformers import AutoModelForCausalLM, AutoTokenizer from datasets import load_dataset def train_alignment(): # Load your preference dataset (chosen vs rejected) dataset = load_dataset("trl-lib/ultrafeedback_binarized", split="train") model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1") ref_model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-v0.1") tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-v0.1") training_args = DPOConfig( output_dir="./mistral-dpo", per_device_train_batch_size=4, gradient_accumulation_steps=4, learning_rate=5e-7, lr_scheduler_type="cosine", max_steps=1000, save_steps=100, logging_steps=10, ) dpo_trainer = DPOTrainer( model, ref_model, args=training_args, beta=0.1, # The hyperparameter for DPO train_dataset=dataset, tokenizer=tokenizer, ) dpo_trainer.train() ``` ## Practical Tips for Alignment 1. **Data Quality Over Quantity:** 1,000 high-quality preference pairs are worth more than 50,000 noisy ones. Use LLM-as-a-judge (like GPT-4o) to clean your datasets before training. 2. **Watch the Beta:** In DPO, the `beta` parameter controls how much you deviate from the reference model. A smaller beta (0.1) stays closer to the base, while a larger beta allows more aggressive alignment. 3. **Check for Catastrophic Forgetting:** Alignment can sometimes make models "dumber" at logic while making them more polite. Always run a benchmark (like GSM8K) after alignment. ## Running on Podstack Aligning models like Llama 3 or Mistral requires significant VRAM, especially if you aren't using LoRA. Podstack makes this seamless by allowing you to spin up on-demand A100 or H100 instances only for the duration of your training. Instead of managing infrastructure, you can use the Podstack API to deploy your training script as a job. Set your `PODSTACK_API_KEY` and trigger the run: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Because Podstack bills per second, you don't have to worry about idle costs after your alignment job finishes. If you are just testing ORPO, you can even use our Python GPU functions to run small-scale experiments directly from your local notebook. Which one should you choose? For most teams today, **DPO** offers the best balance of ease-of-use and performance, while **ORPO** is the clear winner for those looking to minimize training stages and compute costs. --- # Running Jupyter on a GPU for data science experiments Learn how to set up and optimize a Jupyter Notebook environment on high-performance GPUs for interactive data science and ML experiments. Workflows · 2026-07-14 · 4 min read Data science experiments thrive on interactivity. Whether you are fine-tuning a BERT model, exploring a new generative architecture, or processing massive dataframes with RAPIDS, the feedback loop of a Jupyter Notebook is indispensable. However, local environments rarely provide the VRAM needed for modern workloads, and managing persistent, expensive instances can drain budgets quickly. In this guide, we will walk through the process of setting up a Jupyter environment on a high-performance GPU, optimizing it for performance, and leveraging a per-second billing model to keep experimentation costs low. ## The Challenge of GPU-Accelerated Notebooks Setting up a Jupyter environment for ML isn't just about installing a package. You need to ensure the underlying drivers (CUDA), libraries (cuDNN), and the Python kernel are all synchronized. Furthermore, when running experiments in the cloud, you face a trade-off: keeping an instance running all day is expensive, but shutting it down often means losing your progress or spending 20 minutes re-configuring your environment. The ideal workflow involves launching a containerized environment where all dependencies are pre-baked, allowing you to jump straight into the code. ## Step 1: Preparing Your Environment To follow this guide, you will need the Podstack API and your API key. If you haven't installed the API yet, you can do so via pip: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` The API allows you to spin up on-demand GPU resources that bill you only for the seconds the notebook is actually running. ## Step 2: Selecting the Right Container Image For data science, using a raw Ubuntu image is inefficient. It is better to use an image optimized for GPU compute. The `pytorch/pytorch` or `tensorflow/tensorflow` images are standard, but for a full Jupyter experience, images from the **Jupyter Docker Stacks** with GPU support are preferred. ## Step 3: Launching the Jupyter Job On a serverless GPU cloud like Podstack, you can launch a Jupyter instance as a persistent job. This allows you to map a local port to the remote GPU instance so you can access the notebook in your local browser. Run the following command to start an NVIDIA A100 or L40S instance: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` *Note: In a production or shared environment, always set a secure token for your NotebookApp.* ## Step 4: Connecting and Running Code Once the job is active, Podstack provides a tunnel or a public URL to access your port. Open your browser to the provided address, and you are ready to verify your GPU access. In your first cell, run this snippet to confirm that your notebook is correctly utilizing the hardware: ```python import torch import sys def check_gpu(): if torch.cuda.is_available(): gpu_name = torch.cuda.get_device_name(0) vram = torch.cuda.get_device_properties(0).total_memory / 1e9 print(f"✅ Success! Connected to: {gpu_name}") print(f"📊 Available VRAM: {vram:.2f} GB") else: print("❌ GPU not detected. Check your drivers and image.") check_gpu() ``` ## Practical Tips for GPU Data Science 1. **Monitor VRAM in Real-time:** Open a terminal within Jupyter and run `watch -n 1 nvidia-smi`. This helps you identify memory leaks or instances where your batch size is too large before you hit an "Out of Memory" (OOM) error. 2. **Persistent Storage:** Data science experiments often involve large datasets. Instead of downloading them every time, mount a persistent volume to your Podstack job. This ensures that your `/home/jovyan/work` directory survives even after the GPU instance is spun down. 3. **Use Kernel Restarts:** GPU memory can sometimes get fragmented or fail to release after a heavy training run. If `torch.cuda.empty_cache()` doesn't work, restarting the Jupyter kernel is the cleanest way to reset the VRAM state. ## Scaling from Notebook to API Interactive experimentation is just the beginning. Once your model architecture is finalized in Jupyter, the next step is moving toward production. The transition from a `.ipynb` file to a scalable endpoint is where most friction occurs. With Podstack, you can take the logic you developed in your notebook and wrap it in a Python GPU function. Instead of managing a persistent server, you can deploy your inference code as a serverless endpoint that only triggers when a request arrives. ## Conclusion Running Jupyter on a GPU shouldn't be a configuration headache. By using containerized environments and on-demand GPU provisioning, you can focus on your data instead of your infrastructure. Podstack makes this workflow seamless by offering high-end GPUs like the H100 and A100 on a per-second billing basis. You can spin up a powerful environment for a quick experiment, run your cells, and shut it down immediately, ensuring you only pay for the compute you actually used. Ready to start? Head over to your terminal, set your `PODSTACK_API_KEY`, and launch your first accelerated notebook in seconds. --- # Scale-to-zero inference endpoints: cutting idle cost Learn how to implement scale-to-zero GPU inference endpoints using Podstack to eliminate idle costs and only pay for the seconds your model is running. Inference · 2026-07-11 · 4 min read In the modern machine learning lifecycle, the "training" phase often gets the most glory, but the "inference" phase is where the bills stack up. Traditionally, deploying a model meant provisioning a GPU instance and leaving it running 24/7. Even if your model only receives requests during business hours, you pay for every idle second. For teams managing multiple models or fluctuating traffic, this "always-on" architecture is a massive drain on capital. The solution is scale-to-zero inference: a serverless approach where the GPU hardware is only provisioned when a request arrives and is decommissioned immediately after a period of inactivity. ## The Architecture of Scale-to-Zero Scale-to-zero requires a specialized orchestration layer. In a standard setup, you have a load balancer, a queue, and an autoscaler. When a request hits the endpoint: 1. **Request Detection:** The system checks if an active container is running. 2. **Cold Start:** If no container exists, the orchestrator pulls the image and attaches a GPU. 3. **Execution:** The model processes the input and returns the result. 4. **Idle Timeout:** After a predefined period of silence (e.g., 60 seconds), the GPU is released. The technical challenge has always been the "cold start." Loading a 10GB LLM into VRAM takes time. However, by using optimized base images and per-second billing, the trade-off between a few seconds of latency and thousands of dollars in savings becomes an easy choice for most production workloads. ## Step 1: Packaging your Model To deploy a scale-to-zero endpoint, you need to containerize your inference logic. The most efficient way to do this is by creating a handler script that interacts with the GPU. Using a framework like FastAPI or a simple Python function allows the orchestrator to route traffic effectively. ```python # app.py import torch from transformers import pipeline class ModelHandler: def __init__(self): # The model loads only when the container starts self.pipe = pipeline( "text-generation", model="gpt2", device=0 # Target the attached GPU ) def predict(self, input_data): return self.pipe(input_data, max_length=50) # The orchestrator calls this function on every request def handle(event): handler = ModelHandler() return handler.predict(event["text"]) ``` ## Step 2: Deploying via the API Once your logic is defined, you can deploy it as a serverless endpoint. Using the Podstack API, you can define your hardware requirements and the scale-to-zero behavior directly from your terminal. First, ensure your environment is configured: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` In this command, `--min-replicas 0` is the critical flag. It instructs the cluster to spin down all resources when no requests are in the queue. The `--idle-timeout 60` ensures the GPU stays hot for one minute after a request, preventing "chatter" (repeated cold starts) during bursts of traffic. ## Practical Tips for Reducing Latency While scale-to-zero saves money, you want to minimize the wait time for your users. 1. **Keep Images Lean:** Use small base images. Every megabyte added to your Docker image increases the time it takes for the node to pull the image and start the container. 2. **Model Sharding:** If you are using massive models, consider using weights stored in a high-speed shared volume rather than baking them into the container image. 3. **Pre-warming:** If you know your traffic spikes at 9:00 AM, you can use a cron job to send a single "dummy" request at 8:59 AM to wake the endpoint. 4. **Optimize VRAM:** Use quantization (INT8 or FP8) to reduce the model size, which speeds up the transfer from disk to GPU memory. ## Why Per-Second Billing Matters Scale-to-zero is only effective if your provider supports granular billing. If a provider rounds up every session to the nearest hour, the financial benefit of scaling down vanishes. With per-second billing, if your model spins up, processes a request in 4 seconds, and then idles for 60 seconds before shutting down, you are billed only for those 64 seconds. For a developer running an image generation bot or an internal document processor, this can reduce monthly GPU costs by over 90% compared to a reserved instance. ## Seamless Scaling with Podstack Podstack was built specifically for this workflow. By abstracting the infrastructure layer, Podstack allows you to treat GPUs as simple Python functions. You don't need to manage Kubernetes clusters or complex load balancers. When you deploy on Podstack, our orchestrator monitors your request queue in real-time. We handle the rapid provisioning of on-demand GPUs and ensure that when your code isn't running, you aren't paying. Whether you need a single NVIDIA T4 for light tasks or a cluster of A100s for heavy inference, Podstack’s serverless endpoints provide the performance of dedicated hardware with the cost-efficiency of true scale-to-zero. --- # Self-hosting an embedding model for private search Learn how to self-host high-performance embedding models like BGE using FastAPI and Podstack for secure, private, and low-latency vector search. RAG · 2026-07-08 · 3 min read In the era of Retrieval-Augmented Generation (RAG), embeddings are the bedrock of modern search. While managed API services offer convenience, many engineering teams are shifting toward self-hosting their embedding models to reduce latency, eliminate per-token costs, and—most importantly—ensure data privacy. When you send a sensitive document to a third-party embedding API, that data leaves your infrastructure. By self-hosting on a private GPU cloud, your data stays within your controlled environment. In this post, we will walk through deploying a state-of-the-art embedding model as a scalable inference endpoint. ## Choosing the Right Model For most production use cases, the **BGE (BAAI General Embedding)** or **nomic-embed-text** families offer the best balance between dimensionality and performance. For this guide, we will use `BAAI/bge-small-en-v1.5`. It is lightweight, performs exceptionally well on the MTEB leaderboard, and runs with incredibly low latency on even modest GPU hardware. ## The Architecture: FastEmbed and FastAPI To keep our service "production-grade" yet lean, we will use **FastEmbed**. Developed by the Qdrant team, FastEmbed is optimized for speed and allows us to run inference without the heavy overhead of the full Transformers library if we choose. We will wrap this in a **FastAPI** application to handle concurrent requests. ## Implementation: The Inference Script Below is a Python implementation of our embedding server. This script initializes the model on the GPU and exposes a POST endpoint to convert text strings into vector representations. ```python import os from fastapi import FastAPI, HTTPException from pydantic import BaseModel from typing import List import numpy as np from fastembed import TextEmbedding app = FastAPI(title="Private Embedding Service") # Initialize the model (it will be cached on the first run) # We specify the GPU device for acceleration model = TextEmbedding(model_name="BAAI/bge-small-en-v1.5") class EmbeddingRequest(BaseModel): input: List[str] class EmbeddingResponse(BaseModel): embeddings: List[List[float]] @app.post("/v1/embeddings", response_model=EmbeddingResponse) async def get_embeddings(request: EmbeddingRequest): try: # Generate embeddings # FastEmbed returns an iterator of numpy arrays embeddings_iter = model.embed(request.input) embeddings_list = [emb.tolist() for emb in embeddings_iter] return EmbeddingResponse(embeddings=embeddings_list) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8080) ``` ## Practical Tips for Production 1. **Batching:** If you are processing thousands of documents for an initial index, always batch your requests. Large batches (e.g., 32 or 64 strings) utilize the GPU's parallel processing power much better than sequential single-string requests. 2. **Precision:** Use FP16 (Half-precision) where possible. Most modern GPUs will see a significant speedup with negligible loss in retrieval accuracy. 3. **Cold Starts:** In a serverless environment, ensure your model weights are pre-baked into your container image or stored on a persistent volume to avoid downloading several hundred megabytes on every boot. ## Deploying on Podstack Deploying this setup traditionally involves managing complex Kubernetes manifests or worrying about idle GPU costs. Podstack simplifies this by treating GPU functions as first-class citizens with per-second billing. To deploy our embedding service, we use the Podstack API. This allows us to push our code and have it instantly accessible via a secure endpoint. First, ensure your environment is set up: ```bash export PODSTACK_API_KEY="your_api_key_here" ``` Then, you can deploy your Python function directly. Podstack handles the GPU allocation and scaling automatically. Because Podstack supports serverless inference, you aren't paying for the GPU while your search engine is idle—only during the milliseconds it takes to generate the embedding. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Once deployed, you can integrate this endpoint into your LangChain or LlamaIndex pipeline by simply swapping the base URL. Your vectors never leave your private cloud, and you benefit from the raw performance of an A100 or L40S without the overhead of managing the underlying hardware. ## Closing Thoughts Self-hosting embedding models is no longer an infrastructure nightmare. With optimized libraries like FastEmbed and on-demand GPU platforms like Podstack, you can achieve sub-10ms embedding latency while keeping your data strictly private. This setup provides the foundation for a secure, scalable, and cost-effective neural search engine. --- # Serving LLMs with vLLM: throughput tuning guide Learn how to optimize vLLM throughput using memory tuning, quantization, and batching strategies on Podstack's high-performance GPU cloud. Inference · 2026-07-05 · 4 min read Serving Large Language Models (LLMs) in production is a balancing act between latency (how fast a single user gets a response) and throughput (how many total requests your system can handle simultaneously). While several inference frameworks exist, **vLLM** has emerged as the industry standard due to its PagedAttention algorithm, which drastically reduces memory waste. However, simply running vLLM with default settings often leaves performance on the table. To maximize your hardware ROI on Podstack, you need to tune the engine to match your specific workload. ## Understanding the vLLM Architecture vLLM's primary innovation is PagedAttention, which manages KV (Key-Value) cache memory like an operating system manages virtual memory. Instead of allocating a contiguous block of memory for a sequence—which leads to fragmentation—vLLM breaks the cache into blocks. When tuning for throughput, your goal is to keep the GPU’s Tensor Cores as busy as possible by fitting as many tokens as possible into these blocks without triggering an Out-of-Memory (OOM) error. ## Step 1: Optimizing GPU Memory Utilization The most important parameter in vLLM is `--gpu-memory-utilization`. By default, vLLM reserves 90% of the available VRAM. - **For Dedicated Throughput:** If you are running a single model on a dedicated Podstack GPU instance, you can often push this to `0.95`. - **For Multi-process Environments:** If you have sidecar processes or multiple model runners, you must lower this to avoid crashes. ```bash # Example: Launching vLLM with high memory utilization and specific block size vllm serve "facebook/opt-125m" \ --gpu-memory-utilization 0.95 \ --max-model-len 4096 \ --block-size 16 ``` ## Step 2: Tuning Batch Size and Concurrency Throughput scales with batch size. vLLM uses "continuous batching," meaning it doesn't wait for a full batch to start processing; it adds new requests to the iteration as soon as slots become available. To maximize throughput, you should tune: 1. **`max_num_seqs`**: The maximum number of sequences per iteration. For smaller models (e.g., Llama 3 8B) on high-end GPUs, increasing this from the default 256 to 512 or higher can saturate the GPU better. 2. **`max_num_batched_tokens`**: This limits the number of tokens processed in a single step. Increasing this helps throughput but can increase the "time to first token" (TTFT). ## Step 3: Quantization for Massive Throughput If your application can tolerate a slight dip in precision, quantization is the single most effective way to double or quadruple your throughput. By using 4-bit or 8-bit weights, you reduce the memory footprint of the model, allowing for significantly larger KV caches. vLLM supports AWQ and FP8 out of the box. Using an AWQ-quantized model allows you to serve a 70B parameter model on hardware that would normally only fit a 30B model, effectively increasing your throughput-per-dollar. ## Step 4: Distributed Serving (Tensor Parallelism) When working with massive models like Llama 3 70B or Mixtral, a single GPU might not have enough VRAM or memory bandwidth. Using Podstack's multi-GPU configurations, you can enable Tensor Parallelism (`--tensor-parallel-size` or `-tp`). For throughput, the rule of thumb is: use the smallest number of GPUs that can comfortably fit the model and a large KV cache. Spreading a small model across too many GPUs introduces communication overhead that can actually *decrease* total throughput. ## Deployment on Podstack Podstack makes it easy to deploy these optimized vLLM containers. Since Podstack bills by the second, you can spin up a high-throughput cluster for a batch job and tear it down immediately after completion. To deploy an optimized vLLM instance using the Podstack API: ```python import os from podstack import PodstackClient # Ensure your PODSTACK_API_KEY is set in your environment client = PodstackClient(api_key=os.getenv("PODSTACK_API_KEY")) # Define a high-throughput GPU function @client.gpu_function(gpu="A100", memory="80GB") def run_vllm_server(): # Inside the container, we execute the tuned vLLM command os.system(""" python -m vllm.entrypoints.openai.api_server \ --model neuralmagic/Meta-Llama-3-8B-Instruct-FP8 \ --max-num-seqs 512 \ --gpu-memory-utilization 0.95 \ --port 8000 """) ``` Alternatively, you can use the Podstack API to launch a job directly: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` ## Practical Tips for Production * **Monitor Cache Usage:** Watch the `vllm:gpu_cache_usage_perc` metric. If it’s constantly at 100%, you are likely hitting a bottleneck and need more VRAM or more instances. * **Request Prioritization:** If you have a mix of long-form generation and short chat replies, consider running separate Podstack endpoints tuned differently for each. * **Auto-scaling:** Use Podstack’s serverless inference capabilities to scale the number of vLLM replicas based on the queue depth, ensuring you aren't paying for idle GPUs when traffic drops. By fine-tuning memory allocation and leveraging quantization on Podstack’s on-demand infrastructure, you can achieve production-grade LLM performance without the overhead of traditional cloud management. --- # Speculative decoding for 2x faster generation Learn how to use speculative decoding to double your LLM inference speed on Podstack by using small draft models to accelerate large target models. Inference · 2026-07-02 · 3 min read In the world of Large Language Models (LLMs), speed is often the bottleneck between a prototype and a production-ready application. While high-end GPUs offer massive throughput, the autoregressive nature of LLMs—generating one token at a time—means that even the most powerful hardware spends a significant amount of time waiting for memory transfers. Speculative decoding has emerged as one of the most effective techniques to break this bottleneck, often yielding a 2x or even 3x speedup without sacrificing model quality. ## The Bottleneck: Memory Bound Generation Standard LLM generation is "memory-bound." To generate a single token, the GPU must load every single parameter of the model from VRAM into its compute cores. For a 70B parameter model, this is a massive overhead for a tiny amount of computation. Speculative decoding flips the script. It uses a smaller, much faster "draft" model to predict the next few tokens in a sequence. Then, the larger "target" model verifies these tokens in a single parallel forward pass. If the draft model is correct, the target model can accept multiple tokens at once, effectively bypassing the one-token-at-a-time limit. ## How Speculative Decoding Works The process follows three main steps: 1. **Drafting:** A small model (e.g., a 1.5B model) generates a sequence of $K$ candidate tokens. 2. **Verification:** The large target model (e.g., a 70B model) performs a single forward pass on all $K$ tokens. 3. **Acceptance:** The system compares the outputs. If the target model agrees with the draft, those tokens are kept. If they diverge, the system corrects the first mismatch and restarts. Because the draft model is significantly smaller, its generation is nearly "free" in terms of time. As long as the draft model is reasonably accurate, the overall wall-clock time drops significantly. ## Implementation with vLLM and Podstack One of the most robust ways to implement speculative decoding is using the `vLLM` engine. It supports speculative decoding natively. On Podstack, you can deploy this as a serverless endpoint or run it as a managed job. Here is how you can configure a vLLM server to use a Llama-3-70B model as the target and a Llama-3-8B model as the draft. ```python import os from podstack import PodstackClient # Initialize Podstack client using your API key client = PodstackClient(api_key=os.getenv("PODSTACK_API_KEY")) # Define the deployment configuration # We use 'speculative_model' to point to our fast drafter deployment_config = { "model": "meta-llama/Meta-Llama-3-70B-Instruct", "gpu": "A100-80GB", "engine_args": { "speculative_model": "meta-llama/Meta-Llama-3-8B-Instruct", "num_speculative_tokens": 5, "use_v2_block_manager": True } } # Deploy a serverless inference endpoint on Podstack endpoint = client.endpoints.create( name="llama-speculative-fast", config=deployment_config, min_replicas=1 ) print(f"Endpoint active at: {endpoint.url}") ``` Alternatively, if you prefer the API, you can launch a worker directly: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` ## Practical Tips for Maximum Performance To get the most out of speculative decoding, keep these three factors in mind: 1. **Model Alignment:** The draft and target models should ideally share the same tokenizer. Using a Llama-3-8B model to draft for a Llama-3-70B model is highly effective because they were trained on similar data distributions and use identical tokenization. 2. **Draft Length ($K$):** Setting `num_speculative_tokens` too high (e.g., 10+) can actually slow down generation if the draft model is inaccurate, as the overhead of verifying many rejected tokens adds up. Usually, a value between 4 and 6 is the sweet spot. 3. **Batch Size:** Speculative decoding provides the most benefit at low batch sizes (like real-time chat). As the batch size increases, the GPU becomes compute-bound rather than memory-bound, and the relative gains of speculative decoding diminish. ## Why Use Speculative Decoding on Podstack? Optimizing LLM inference isn't just about the algorithm; it’s about the underlying infrastructure. Podstack is designed specifically for these high-performance workloads. * **Per-Second Billing:** Speculative decoding reduces the time your GPU is active. Since Podstack bills by the second, faster generation directly translates to lower costs. * **On-Demand Scalability:** You can spin up A100s or H100s via the Podstack API the moment you need to run a high-throughput verification task. * **Serverless Efficiency:** By deploying speculative models as serverless endpoints, you ensure that you aren't paying for idle time, but when a request hits, it’s processed at 2x the standard speed. By combining the architectural advantages of speculative decoding with the elastic, per-second compute of Podstack, developers can deliver sub-second latency for even the largest open-source models. --- # Spot vs on-demand GPUs: saving money safely Learn how to leverage Spot GPUs without risking data loss by implementing aggressive checkpointing, stateless architecture, and automated job orchestration. Infrastructure · 2026-06-29 · 4 min read Training modern machine learning models or running large-scale inference is an exercise in resource management. For most ML engineers, the primary constraint isn't just algorithmic—it's the cloud bill. When looking at GPU availability, you generally face two options: On-Demand instances, which offer guaranteed availability at a premium, and Spot instances, which offer deep discounts in exchange for the risk of being reclaimed by the provider. The price difference is often staggering, with Spot instances sometimes costing 60-80% less than their On-Demand counterparts. However, saving money "safely" requires a shift in how you architect your workflows. Here is how to navigate the trade-off. ## Understanding the "Spot Risk" The fundamental challenge with Spot GPUs is volatility. If a higher-paying user requests On-Demand resources and the capacity is full, your Spot job will be pre-empted (terminated) with very little notice—usually between 30 seconds and two minutes. To save money safely, you must assume your hardware will disappear at any moment. If your training script isn't prepared for this, you don't just lose time; you lose the literal dollars spent on the compute hours leading up to the crash. ## Strategy 1: The Checkpoint Pattern The most critical step in utilizing Spot GPUs is aggressive checkpointing. In a standard training loop, you might save your model weights at the end of every epoch. On Spot instances, you should save based on time intervals or smaller step counts. Most modern frameworks like PyTorch Lightning or Hugging Face `transformers` have built-in support for resuming from a directory. Your code should always check for an existing checkpoint before starting. ```python import os import torch from podstack import Client # Initialize Podstack client if using managed storage client = Client(api_key=os.getenv("PODSTACK_API_KEY")) def train(): model = MyModel() optimizer = torch.optim.Adam(model.parameters()) checkpoint_path = "/persistent/storage/checkpoint.pt" # The Safety Net: Always check for previous state if os.path.exists(checkpoint_path): print("Resuming from checkpoint...") checkpoint = torch.load(checkpoint_path) model.load_state_dict(checkpoint['model_state_dict']) optimizer.load_state_dict(checkpoint['optimizer_state_dict']) start_epoch = checkpoint['epoch'] else: start_epoch = 0 for epoch in range(start_epoch, total_epochs): # ... training logic ... # Save frequently to minimize loss during pre-emption torch.save({ 'epoch': epoch, 'model_state_dict': model.state_dict(), 'optimizer_state_dict': optimizer.state_dict(), }, checkpoint_path) # Sync to persistent cloud volume client.volumes.sync("/persistent/storage") ``` ## Strategy 2: Stateless Inference via Serverless If you are running inference rather than training, you shouldn't be using long-running persistent instances at all. Serverless GPU functions are the ultimate evolution of the Spot vs. On-Demand debate. By wrapping your inference code in a function that triggers on-demand and scales to zero, you effectively get the pricing benefits of Spot with the reliability of On-Demand. Since inference is typically stateless, if a request fails due to a node being reclaimed, the load balancer simply retries the request on a different node. ## Strategy 3: Job Orchestration Instead of manually spinning up an instance, SSHing in, and running a script, use a Job orchestrator. A dedicated Job runner knows how to handle pre-emption signals. When a Spot instance is reclaimed, a smart orchestrator will automatically re-queue your job and wait for the next available slot, picking up exactly where your last checkpoint left off. ## Practical Tips for Spot Stability 1. **Decouple Storage and Compute:** Never store your data or model weights on the local disk of a Spot instance. Always use attached network volumes or object storage. When the instance dies, your local disk dies with it. 2. **Monitor via the API:** Use automated tools to check the status of your workloads. If a job stays in "Pending" for too long because Spot capacity is low, you might need to temporarily switch that specific high-priority job to On-Demand. 3. **Dockerize Everything:** To make your jobs truly "disposable" and portable across Spot nodes, ensure your environment is fully encapsulated in a Docker container. This eliminates "it worked on the last machine" syndrome. ## Saving Safely with Podstack Podstack is designed to take the manual labor out of this decision. We provide a developer-first interface where you can choose between guaranteed On-Demand performance or cost-optimized Job execution. Using the Podstack API, you can deploy your GPU functions or training jobs without worrying about the underlying hardware lifecycle. Because we bill per second, you never pay for "downtime" or the minutes it takes to spin a machine down after a crash. To launch a persistent training job that can handle the Spot lifecycle, you can simply point the API to your script: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` By combining persistent volumes with our per-second billing, you can aggressively use Spot-tier pricing for 90% of your development cycle, switching to On-Demand only when hitting critical production deadlines. This hybrid approach ensures your budget goes toward training better models, not just keeping the lights on in a data center. --- # Structured JSON output from open models Learn how to enforce JSON schemas on open-weight LLMs using Pydantic and deploy them as scalable serverless functions on Podstack's GPU cloud. Inference · 2026-06-26 · 3 min read In the current era of LLM integration, getting a model to "chat" is easy. Getting a model to act as a reliable component in a software pipeline is significantly harder. For developers building autonomous agents or automated data extractors, the biggest hurdle isn't the model’s reasoning—it's the format of its response. If your application expects a valid JSON object with specific keys but the model returns conversational filler or trailing commas, your code breaks. Achieving **structured JSON output** is the key to turning an unpredictable LLM into a reliable API. In this guide, we’ll explore how to enforce structured outputs using open-weight models like Llama 3 or Mixtral, and how to deploy these workflows as high-performance endpoints. ## Why Structured Output Matters Modern applications rarely consume raw text. Whether you are generating a list of UI components, extracting entities from a document, or determining which tool an agent should call, you need data in a machine-readable format. While proprietary models often have built-in "JSON mode," open models offer more flexibility. By using techniques like **Grammar-based sampling** or **Pydantic validation**, you can ensure the model's output strictly adheres to a predefined schema, preventing parsing errors entirely. ## Implementation: The Pydantic Approach The most robust way to handle structured data in Python is through Pydantic. By defining a class that represents your desired output, you create a contract between your logic and the model. Here is a practical implementation using a FastAPI-style structure that you can deploy as a serverless function. We use a library like `instructor` or the native `json_schema` capabilities of inference engines to force the model's hand. ```python import os from pydantic import BaseModel, Field from typing import List from podstack import PodstackClient # Define the schema class SentimentAnalysis(BaseModel): sentiment: str = Field(description="The emotional tone: positive, negative, or neutral") confidence_score: float = Field(ge=0, le=1) topics: List[str] = Field(description="Key topics mentioned in the text") # Initialize the Podstack client client = PodstackClient(api_key=os.getenv("PODSTACK_API_KEY")) def analyze_review(text: str): prompt = f"Analyze the following user review and return only JSON: {text}" # Using a high-performance open model endpoint response = client.inference.create( model="llama-3-70b-instruct", messages=[{"role": "user", "content": prompt}], response_format={ "type": "json_object", "schema": SentimentAnalysis.model_json_schema() } ) # Parse and validate the output data = SentimentAnalysis.model_validate_json(response.choices[0].message.content) return data review = "The GPU cold-start times are incredibly fast, but the documentation needs more examples." print(analyze_review(review)) ``` ## Practical Tips for Reliability 1. **System Prompts:** Even with schema enforcement, a clear system prompt helps. Use: *"You are a data extraction engine. Always return valid JSON that conforms to the provided schema. Do not include markdown formatting or conversational text."* 2. **Schema Simplification:** Large schemas can confuse smaller models (like 7B or 8B variants). If you have a complex nested object, consider breaking it into multiple smaller inference calls. 3. **Handling Hallucinations:** Structured output doesn't prevent factual errors; it only prevents formatting errors. Always include a `confidence_score` field in your schema to allow your application to flag uncertain extractions for human review. 4. **Temperature Settings:** When generating JSON, keep your `temperature` low (between 0.0 and 0.2). This makes the model more deterministic and less likely to wander outside the schema boundaries. ## Scaling with Serverless GPU Functions Once you have your logic ready, you need to run it at scale. Running a heavy model like Llama 3 locally is slow, and managing persistent clusters for sporadic traffic is expensive. This is where serverless GPU functions become a game-changer. Instead of managing a virtual machine, you can package your extraction logic as a job or an endpoint that scales automatically. Using the Podstack API, you can deploy your structured output function in seconds: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` ## Why Podstack? Reliable structured output requires low latency and high availability. Podstack provides the infrastructure to run these models on demand, billed per second of actual usage. Whether you are running a batch job to process millions of records or hosting an inference endpoint for a real-time app, our platform ensures you have access to the latest GPUs (like H100s and A100s) without the overhead of infrastructure management. By combining Python’s Pydantic ecosystem with Podstack’s serverless GPU functions, you can build production-ready ML features that are both robust and cost-effective. --- # Text-to-speech voices for apps and games Learn how to deploy high-fidelity neural text-to-speech models like XTTS v2 using Python and serverless GPU infrastructure for low-latency apps and games. Audio · 2026-06-23 · 4 min read Generating high-quality speech has transitioned from a niche research problem to a standard requirement for modern applications and games. Whether you are building an immersive RPG with thousands of lines of dialogue or a productivity app that reads documents aloud, users now expect human-like prosody, emotion, and zero latency. However, running state-of-the-art Text-to-Speech (TTS) models like Coqui XTTS v2 or Piper at scale presents a significant infrastructure hurdle. These models require substantial VRAM and low-latency GPU compute to avoid the "robotic lag" that ruins user immersion. In this post, we will look at how to deploy production-ready TTS engines using Python and serverless GPU infrastructure. ## Choosing Your TTS Architecture When integrating voices into your stack, you generally choose between two paths: 1. **Concatenative/Formant Synthesis:** Lightweight but sounds robotic. Great for microcontrollers, bad for modern apps. 2. **Neural TTS (End-to-End):** Models like Bark or XTTS use transformers to generate waveforms. They sound indistinguishable from humans but require GPUs to run in real-time. For most developers, the sweet spot is **XTTS v2**. It supports voice cloning with just a 6-second audio sample and handles over 16 languages. If you need raw speed and are less concerned with emotive nuance, **Piper** is an excellent alternative that can run on smaller GPU footprints. ## Setting Up the Inference Environment To deploy a TTS engine, you need an environment with CUDA support and the necessary deep learning libraries. Below is a practical implementation using the `TTS` library by Coqui, wrapped in a simple FastAPI interface. This allows your game or app to send text via a REST API and receive a high-fidelity WAV file in return. ```python import os from fastapi import FastAPI, Response from TTS.api import TTS import torch app = FastAPI() # Load model onto GPU device = "cuda" if torch.cuda.is_available() else "cpu" tts = TTS("tts_models/multilingual/multi-dataset/xtts_v2").to(device) @app.post("/synthesize") async def synthesize(text: str, speaker_wav: str = "reference.wav", language: str = "en"): # Path to save temporary output output_path = "output.wav" # Generate speech tts.tts_to_file( text=text, speaker_wav=speaker_wav, language=language, file_path=output_path ) with open(output_path, "rb") as f: return Response(content=f.read(), media_type="audio/wav") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=8080) ``` ## Optimizing for Latency In games, latency is the ultimate enemy. A 2-second delay before an NPC speaks breaks the "flow state." To minimize TTTF (Time to First Audio), consider these three optimizations: * **Streaming:** Instead of waiting for the full audio file to generate, use models that support chunked streaming. This allows the client to start playing the first syllable while the rest of the sentence is still being computed. * **VRAM Caching:** Ensure your model weights are pinned to the GPU memory. On serverless infrastructure, look for "warm starts" to avoid the cold-boot penalty of loading 2GB+ of model weights. * **Precision Switching:** Running inference in `FP16` (half-precision) usually yields a 2x speedup on modern GPUs with negligible loss in audio quality. ## Deploying at Scale Once your code is ready, the challenge shifts to scaling. If your game hits the front page of a store, you might jump from 10 to 10,000 concurrent users. Scaling a cluster of persistent GPU VMs is both expensive and operationally heavy. This is where serverless GPU functions become essential. By deploying your TTS logic as a dedicated function, you only pay for the seconds the GPU is actually crunching numbers to generate speech. Using the Podstack API, you can deploy the above script as a high-performance endpoint. First, ensure your `PODSTACK_API_KEY` is set in your environment variables, then use the API to push your logic: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` This approach allows your app to call a single endpoint that automatically scales across multiple GPUs based on incoming traffic. ## Practical Tips for Voice Quality * **Reference Audio:** For voice cloning, use a clean 24kHz mono WAV file. Background noise in the reference file will often be interpreted as "texture" by the model, resulting in static in the output. * **SSML Parsing:** Many TTS models benefit from structured text. Use punctuation effectively; adding extra commas can force the model to take natural "breaths," making the AI sound more human. * **Sentence Splitting:** For long paragraphs, split the text into sentences before sending them to the GPU. This prevents memory overflows and allows for parallel processing of different sentences. ## Conclusion Building high-quality voice synthesis is no longer restricted to big tech studios. By leveraging open-source neural models and modern GPU infrastructure, any developer can integrate realistic dialogue into their projects. Podstack makes this transition seamless by providing on-demand GPUs billed by the second. Instead of managing complex Kubernetes clusters or overpaying for idle VMs, you can deploy your TTS functions to Podstack and scale from a single developer test to a global user base instantly. Whether you need a persistent endpoint for a web app or high-throughput batch jobs for game dialogue pre-rendering, Podstack provides the raw power of A100s and H100s without the overhead. --- # Time-series forecasting with transformers on GPUs Learn how to implement and deploy Transformer-based time-series models on GPUs using Podstack for high-performance, cost-effective forecasting. Training · 2026-06-20 · 3 min read Moving from traditional autoregressive models like ARIMA or Prophet to Deep Learning has fundamentally changed how we approach time-series forecasting. While Recurrent Neural Networks (RNNs) and LSTMs were the previous standard, the industry has shifted toward Transformers. By leveraging multi-head self-attention mechanisms, Transformers can capture long-range dependencies and complex seasonal patterns that traditional models often miss. However, training Transformers on large-scale temporal data is computationally expensive. To move from experimentation to production, you need the right infrastructure. In this post, we’ll walk through the practical steps of deploying a time-series Transformer model using GPU acceleration. ## Why Transformers for Time-Series? The primary advantage of the Transformer architecture in time-series is its ability to look at the entire sequence simultaneously. Unlike LSTMs, which process data sequentially and often suffer from "vanishing gradients" over long horizons, Transformers use attention scores to weight the importance of different past time steps. When dealing with high-frequency data (like per-second sensor logs or millisecond financial ticks), the sequence length can become massive. This is where GPUs become non-negotiable. The parallel nature of self-attention calculations maps perfectly to GPU CUDA cores, offering a 10x to 50x speedup over CPU-based training. ## Setting Up Your Environment To follow along, you will need a Python environment with `torch` and a forecasting library like `GluonTS` or `Darts`, which provide high-level abstractions for Time-series Transformers (like Informer or Autoformer). First, ensure your environment is configured to communicate with your GPU cluster. Set your API key as an environment variable: ```bash export PODSTACK_API_KEY="your_api_key_here" ``` ## Implementing the Model In this example, we will use a vanilla Time-Series Transformer. We will define a model that takes a look-back window (past data) and predicts a future horizon. ```python import torch import torch.nn as nn import numpy as np class TimeSeriesTransformer(nn.Module): def __init__(self, input_dim, model_dim, num_heads, num_layers, output_dim): super(TimeSeriesTransformer, self).__init__() self.input_linear = nn.Linear(input_dim, model_dim) self.pos_encoder = nn.Parameter(torch.zeros(1, 1000, model_dim)) encoder_layers = nn.TransformerEncoderLayer(d_model=model_dim, nhead=num_heads) self.transformer_encoder = nn.TransformerEncoder(encoder_layers, num_layers=num_layers) self.output_linear = nn.Linear(model_dim, output_dim) def forward(self, src): # src shape: [batch_size, seq_len, input_dim] x = self.input_linear(src) + self.pos_encoder[:, :src.size(1), :] x = x.transpose(0, 1) # Transformer expects [seq_len, batch, dim] output = self.transformer_encoder(x) output = output.transpose(0, 1) return self.output_linear(output[:, -1, :]) # Predict next step # Initialize for a GPU device = torch.device("cuda" if torch.cuda.is_available() else "cpu") model = TimeSeriesTransformer(input_dim=1, model_dim=64, num_heads=8, num_layers=3, output_dim=1).to(device) print(f"Model initialized on: {device}") ``` ## Optimization Tips for Time-Series on GPUs 1. **Batch Size vs. Sequence Length**: In time-series, your "sequence length" (how far back you look) heavily impacts VRAM. If you encounter Out-of-Memory (OOM) errors, try reducing the sequence length before reducing the batch size to maintain gradient stability. 2. **Mixed Precision**: Use `torch.cuda.amp` (Automatic Mixed Precision). Time-series data often doesn't require 64-bit precision; FP16 can double your throughput on modern GPUs without losing forecasting accuracy. 3. **Data Loading**: The bottleneck is often moving data from the CPU to the GPU. Use `pin_memory=True` in your PyTorch DataLoaders to speed up the transfer to the GPU device. ## Deploying to Production Training a model is only half the battle. For time-series forecasting, you often need to run inference every time a new data point arrives. Running a full persistent server for a model that only triggers once a minute is wasteful. This is where serverless GPU functions or on-demand jobs become critical. Instead of managing a virtual machine that sits idle, you can package your inference code into a container and trigger it only when needed. To deploy your training script as a job using the Podstack API: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` This command provisions an A100 GPU, executes your training logic, and spins down the resource the moment the job finishes, ensuring you only pay for the seconds the GPU was active. ## Scalable Forecasting with Podstack Handling massive time-series datasets requires infrastructure that scales as fast as your data grows. Podstack is designed for this exact workflow. By using Podstack, you gain access to high-performance GPUs billed by the second, allowing you to iterate on complex Transformer architectures without the overhead of long-term contracts or complex orchestration. Whether you are running a one-off backtest across five years of data or deploying a serverless endpoint for real-time demand forecasting, Podstack’s API makes it seamless. You can trigger a GPU-accelerated Python function with a single command, process your temporal features, and receive the forecast in milliseconds. To get started, simply install the SDK, set your `PODSTACK_API_KEY`, and push your first forecasting job to the cloud. The transition from a local notebook to a global-scale GPU cluster has never been more direct. --- # Train a YOLO object detector for warehouse inventory Learn how to train and deploy a custom YOLOv8 object detector for warehouse inventory tracking using Podstack’s serverless GPU infrastructure and API. Vision · 2026-06-17 · 3 min read In modern logistics, manual inventory counting is a significant bottleneck. Automating this process using computer vision—specifically the YOLO (You Only Look Once) architecture—allows for real-time tracking of pallet movements, stock levels, and bin occupancy. However, training a high-accuracy object detector requires significant VRAM and compute power that local workstations often lack. In this guide, we will walk through the workflow of training a custom YOLOv8 model for warehouse inventory using Podstack’s serverless GPU infrastructure. ## 1. Preparing the Warehouse Dataset Before writing code, you need a labeled dataset. For warehouse inventory, your classes might include `pallet`, `cardboard_box`, `forklift`, or `shrink_wrap`. 1. **Collect Images:** Capture diverse angles of your shelving units, varying lighting conditions, and different load types. 2. **Annotate:** Use tools like CVAT or LabelImg to create bounding boxes. Export these in the YOLO format, which consists of a `.yaml` configuration file and folders for `images` and `labels`. 3. **Organize:** Ensure your directory structure looks like this: ```text /dataset /images /train /val /labels /train /val data.yaml ``` ## 2. Environment Setup To interact with Podstack, you’ll use the Podstack API. This allows you to deploy training jobs to high-end GPUs like the NVIDIA A100 or H100 without managing complex Kubernetes clusters or persistent virtual machines. First, install the SDK and authenticate: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` ## 3. Writing the Training Script We will use the `ultralytics` library to handle the YOLOv8 training logic. The following Python script defines a function that Podstack will execute on a remote GPU. ```python import os from ultralytics import YOLO from podstack import gpu_function @gpu_function(gpu="a100", memory="40gb") def train_inventory_model(dataset_path: str, epochs: int = 50): # Load a pre-trained Nano model (good for speed) model = YOLO("yolov8n.pt") # Train the model results = model.train( data=os.path.join(dataset_path, "data.yaml"), epochs=epochs, imgsz=640, device=0, project="warehouse_inventory", name="v1_initial_run" ) # Export the model for inference model.export(format="onnx") return "Training complete. Model exported to ONNX." if __name__ == "__main__": # This triggers the remote execution on Podstack train_inventory_model("./warehouse_data", epochs=100) ``` ## 4. Launching the Job on Podstack With Podstack, you don't need to manually provision a server and SSH into it. When you run a script wrapped in the `@gpu_function` decorator, Podstack packages your code, sends it to a GPU node, and streams the logs back to your terminal. Execute the training job: ```bash python train_yolo.py ``` Because Podstack bills by the second, you only pay for the exact duration of the training epochs. Once the `train()` function finishes, the GPU is instantly released. ## 5. Practical Tips for Warehouse Environments * **Handle Occlusion:** Warehouse items are often stacked behind one another. Use data augmentation techniques like "MixUp" or "Mosaic" (enabled by default in YOLOv8) to help the model learn to recognize partially obscured boxes. * **Camera Placement:** Training images should match the perspective of your deployment cameras. If your cameras are mounted 15 feet high on rafters, don't train exclusively on eye-level photos. * **Small Object Detection:** If you are tracking small labels or barcodes, increase the `imgsz` parameter to 1280, though this will require more VRAM (making the A100 80GB an ideal choice on Podstack). ## 6. Deploying for Inference Once training is finished, you can deploy your best `.pt` or `ONNX` file as a serverless inference endpoint. This allows your warehouse management system (WMS) to send an image via a REST API and receive a JSON response containing the count and location of items. On Podstack, you can transition from training to inference seamlessly. By using the the console or the API. ## Summary Training a YOLO model for warehouse inventory doesn't require maintaining a fleet of expensive hardware. By leveraging Podstack's on-demand GPU functions, you can scale your compute from zero to an A100 in seconds, run your training pipeline, and deploy your model to production—all within a single Python workflow. This per-second billing and serverless approach ensures that your ML budget is spent on innovation, not idle infrastructure. --- # Training a custom tokenizer for a domain language model Learn how to train a custom Byte-Level BPE tokenizer for specialized domains to improve LLM efficiency and context density using Python and Podstack GPUs. Training · 2026-06-14 · 4 min read Building a domain-specific Language Model (LLM) often starts with a fundamental question: should you use a generic tokenizer like the one from Llama-3 or GPT-4, or should you train your own? For niche domains—such as legal documentation, medical records, or proprietary codebases—generic tokenizers are often inefficient. They may split specialized terminology into too many sub-tokens, increasing sequence length and computational cost. By training a custom tokenizer, you ensure that your model "speaks" the domain language natively, leading to better downstream performance and faster inference. In this guide, we will walk through the practical steps of training a Byte-Level BPE (Byte Pair Encoding) tokenizer tailored for a custom dataset and how to scale this workflow using Podstack’s GPU infrastructure. ## Why Domain-Specific Tokenization Matters Most modern LLMs use tokenizers trained on massive, general-purpose web crawls. When these encounter specialized text, they struggle. For example, in a codebase, a generic tokenizer might split a specific function name like `__init_subclass__` into six or seven different tokens. A domain-trained tokenizer would likely represent it as one or two. This efficiency matters because: 1. **Context Window:** Fewer tokens per sentence mean you can fit more information into the model's context window. 2. **Compute Cost:** Models are billed or limited by token count. Lowering the token-to-word ratio directly reduces costs. 3. **Semantic Density:** Better tokenization helps the model learn the underlying structure of the language more effectively. ## Step 1: Preparing Your Dataset The quality of your tokenizer is strictly bound to your data. You need a large, representative corpus of raw text. For a custom tokenizer, aim for at least 1GB to 5GB of clean text. Ensure your data is in a simple format, such as a large `.txt` file or a series of JSONL files. Clean out boilerplate (like HTML tags or metadata) that won't be present during the model's actual use phase. ## Step 2: Training with the Tokenizers Library We will use the `tokenizers` library by Hugging Face, which is highly optimized and written in Rust. The following Python script demonstrates how to train a Byte-Level BPE tokenizer, which is the standard for models like GPT and Llama. ```python from tokenizers import Tokenizer, models, trainers, pre_tokenizers, decoders, processors import os # 1. Initialize a BPE model tokenizer = Tokenizer(models.BPE(unk_token="[UNK]")) # 2. Configure pre-tokenization (e.g., splitting by whitespace) tokenizer.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) # 3. Setup the trainer # Adjust vocab_size based on your domain complexity (usually 32k to 50k) trainer = trainers.BpeTrainer( vocab_size=50257, min_frequency=2, special_tokens=["", "", "", "", ""] ) # 4. Train the tokenizer files = [f"data/domain_corpus_{i}.txt" for i in range(10)] tokenizer.train(files, trainer) # 5. Post-processing for GPT-2 style encoding tokenizer.post_processor = processors.ByteLevel(trim_offsets=True) tokenizer.decoder = decoders.ByteLevel() # 6. Save your assets os.makedirs("domain-tokenizer", exist_ok=True) tokenizer.save("domain-tokenizer/tokenizer.json") print("Tokenizer training complete. Saved to /domain-tokenizer") ``` ## Step 3: Validation and Benchmarking Once trained, you must validate the tokenizer. Compare it against a baseline (like `bert-base-uncased` or `gpt2`). 1. **Fertility Rate:** Calculate the average number of tokens per word. A lower rate on your domain data compared to a general tokenizer indicates success. 2. **Unknown Tokens:** Ensure your `[UNK]` token count is near zero. 3. **Round-trip Consistency:** Ensure that `decode(encode(text)) == text`. ## Practical Tips for Production * **Don't ignore special tokens:** If your domain involves structured data (like LaTeX or Markdown), ensure your tokenizer handles those markers as single tokens where appropriate. * **Vocab Size Trade-off:** A larger vocabulary reduces sequence length but increases the embedding layer's memory footprint. For most domain tasks, 32,000 to 50,000 tokens is the "sweet spot." * **Normalization:** Decide early if you want your model to be case-sensitive. For code, case sensitivity is mandatory; for medical transcripts, it might be less critical. ## Scaling on Podstack While training a tokenizer is often a CPU-intensive task, the subsequent steps—training the actual Language Model and running large-scale validation—require high-performance GPUs. On Podstack, you can transition from tokenizer training to model training seamlessly. Using the Podstack API, you can deploy your training script as a job that spins up an H100 or A100 instance, executes your code, and spins down the moment the job is finished, ensuring you only pay for the seconds the GPU was active. To run your training script on a Podstack GPU instance: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Because Podstack bills per second, you can iterate on your tokenizer and model architecture without worrying about idle server costs. Once your model is ready, you can deploy it as a serverless endpoint using the same infrastructure, providing low-latency inference for your new domain-specific LLM. ## Conclusion Training a custom tokenizer is the first step toward building a model that truly understands your industry's nuances. By optimizing the "alphabet" your model uses, you save compute, increase speed, and improve accuracy. With the right data and the on-demand scale of Podstack, you can move from raw text to a specialized tokenizer in minutes. --- # Training a Stable Diffusion LoRA on your product photos Learn how to train a custom Stable Diffusion LoRA for product photos using high-performance GPUs and the Podstack API for efficient, per-second billing. Image · 2026-06-11 · 4 min read Fine-tuning foundation models for specific product aesthetics used to require a massive infrastructure overhead. With the rise of Low-Rank Adaptation (LoRA), we can now inject specific styles, objects, or faces into Stable Diffusion with remarkably small datasets and minimal compute time. If you are an ML engineer looking to generate high-fidelity marketing assets or consistent product visuals, training a LoRA is the most efficient path. In this guide, we will walk through the technical process of training a LoRA for your product photos and how to deploy that workflow onto high-performance GPUs. ## The LoRA Advantage Standard fine-tuning updates all weights in a model, which is computationally expensive and leads to massive file sizes. LoRA, however, freezes the pre-trained model weights and injects trainable rank decomposition matrices into the transformer layers. For product photography, this means: * **Speed:** Training typically takes 15-30 minutes on a modern GPU. * **Portability:** The resulting weights are often under 200MB. * **Precision:** You can maintain the structural integrity of your product while changing the environment, lighting, or context. ## Step 1: Data Preparation The quality of your output is directly correlated to your input data. For a product LoRA, aim for 15-30 high-resolution images. 1. **Variety:** Include different angles, lighting conditions, and simple backgrounds. 2. **Consistency:** Ensure the product itself is the consistent element. 3. **Captioning:** Use a unique trigger word (e.g., `ohwx product_name`). Create `.txt` files for each image describing the scene: `"a photo of ohwx product_name on a marble countertop, cinematic lighting."` ## Step 2: Setting Up the Training Script We recommend using `kohya_ss` or the Hugging Face `diffusers` library for training. Below is a simplified Python approach using the `diffusers` training script logic, which is highly compatible with headless GPU environments. ```python import os from accelerate import Accelerator # Configure your training parameters OUTPUT_DIR = "./lora_weights" DATA_DIR = "./product_images" MODEL_NAME = "runwayml/stable-diffusion-v1-5" # Or SDXL def train_lora(): # Example command execution for the Diffusers LoRA script os.system(f""" accelerate launch train_text_to_image_lora.py \ --pretrained_model_name_or_path="{MODEL_NAME}" \ --dataset_name="{DATA_DIR}" \ --dataloader_num_workers=8 \ --resolution=512 \ --center_crop \ --random_flip \ --train_batch_size=1 \ --gradient_accumulation_steps=4 \ --max_train_steps=1000 \ --learning_rate=1e-04 \ --max_grad_norm=1 \ --lr_scheduler="cosine" \ --lr_warmup_steps=0 \ --output_dir="{OUTPUT_DIR}" \ --checkpointing_steps=500 \ --validation_prompt="A photo of ohwx product_name in a forest" \ --seed=42 """) if __name__ == "__main__": train_lora() ``` ## Step 3: Hyperparameter Tuning When training on product photos, keep these three settings in mind: * **Learning Rate:** A rate of `1e-4` is standard for LoRAs. If the model fails to capture the product details, try increasing it slightly; if the images "deep fry" or look distorted, lower it. * **Network Rank (Dimension):** A rank of 8 or 16 is usually sufficient for objects. Higher ranks (e.g., 64) capture more detail but increase the risk of over-fitting. * **Steps:** For 20 images, 1,000 to 1,500 steps is the sweet spot. ## Step 4: Running on Podstack Training LoRAs requires significant VRAM (ideally 24GB+) to handle the gradient calculations and image latents. Podstack provides the ideal environment for this because you can spin up a high-performance GPU, run your training job, and shut it down the second it's finished—paying only for the seconds you used. First, ensure you have your API key set in your environment: ```bash export PODSTACK_API_KEY="your_secret_key_here" ``` You can then use the Podstack API to dispatch your training script as a job. This allows you to avoid managing long-running SSH sessions or manual VM shutdowns. ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` Podstack handles the orchestration, provisioning the A100, executing your training script, and storing the logs. Once the `lora_weights` are generated, you can download them or push them directly to a model registry. ## Step 5: Inference and Validation Once you have your `.safetensors` file, you can run inference using Podstack’s serverless endpoints. By creating a Python GPU function, you can load your base model and the LoRA dynamically to generate images on demand. ```python from diffusers import StableDiffusionPipeline import torch def generate_product_image(prompt, lora_path): pipe = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16) pipe.unet.load_attn_procs(lora_path) pipe.to("cuda") image = pipe(prompt).images[0] return image ``` ## Practical Tips for Success 1. **Aspect Ratio:** If your product is tall (like a wine bottle), include vertical shots and train at resolutions that support that aspect ratio. 2. **Regularization:** If the model starts losing the ability to generate anything *except* your product, add a "regularization" dataset of generic photos of the same class (e.g., "a bottle"). 3. **Checkpointing:** Save checkpoints every 500 steps. Often, an earlier checkpoint will have a better balance of flexibility and product accuracy than the final one. ## Scaling with Podstack Training a single LoRA is a great start, but many teams need to automate this for hundreds of products. Podstack’s per-second billing and job-based architecture make it the perfect backbone for a product photography pipeline. You can programmatically trigger training jobs via the API or API every time a new product is added to your catalog, ensuring your creative team always has the latest assets at their fingertips without the headache of managing fixed infrastructure. --- # Video generation models: what's possible today Explore the current state of SVD and CogVideoX, and learn how to deploy high-performance video generation pipelines using Python GPU functions on Podstack. Video · 2026-06-08 · 3 min read The landscape of generative AI has shifted rapidly from static images to high-fidelity video. For ML engineers and developers, the "toy" phase of video generation is over; we are now in the era of production-grade temporal consistency and cinematic quality. Whether you are building automated marketing pipelines, game assets, or synthetic training data, the tooling has matured enough to move these models into your backend stack. In this post, we’ll explore the current state of video generation models and how to deploy them effectively on high-performance infrastructure. ## What’s Possible: The Current Landscape Today’s models generally fall into two categories: **text-to-video (T2V)** and **image-to-video (I2V)**. While text prompts provide creative freedom, image-to-video is currently the gold standard for production use cases because it allows developers to lock in character consistency and composition before animating. 1. **SVD (Stable Video Diffusion):** The industry workhorse. It’s open-weight, highly customizable, and performs exceptionally well on 24GB VRAM GPUs (like the A10G or L4). It’s perfect for 2-4 second cinematic clips. 2. **CogVideoX:** A newer, high-parameter transformer-based model that offers significantly better text adherence and longer duration capabilities compared to early diffusion models. 3. **AnimateDiff:** Not a standalone model, but a set of motion modules applied to Stable Diffusion. This is the go-to for stylized, consistent animations (like anime or specific art styles). ## The Engineering Challenge: Latency and Compute Video generation is compute-intensive. Generating a 5-second clip at 24fps requires denoising 120 individual frames while maintaining temporal cross-attention between them. On consumer hardware, this can take minutes. To make video generation "production-ready," you need: * **A100 or H100 GPUs** for low-latency inference. * **Serverless infrastructure** to handle the bursty nature of video requests. * **Fast cold-start times** to ensure users aren't waiting for a container to pull. ## Practical Implementation: Deploying a Video Endpoint To move beyond local notebooks, you should wrap your model in a serverless function. This allows you to call the GPU only when a video needs to be rendered, billing by the second. Using a Python-centric approach, you can define a function that loads a model like SVD and exposes it via an API. Here is a conceptual example of how you might structure a worker using the `podstack` environment: ```python import os import torch from diffusers import StableVideoDiffusionPipeline from PIL import Image # The PODSTACK_API_KEY is used by the API to authenticate your deployment # Podstack does not ship a command-line interface. Deploy from the console or call the API at https://podstack.ai/api/v1. def generate_video(image_path: str): # Load model to GPU pipe = StableVideoDiffusionPipeline.from_pretrained( "stabilityai/stable-video-diffusion-img2vid-xt", torch_dtype=torch.float16, variant="fp16" ) pipe.enable_model_cpu_offload() # Optimize VRAM usage # Load initial frame image = Image.open(image_path).convert("RGB").resize((1024, 576)) # Generate frames # SVD-XT produces 25 frames generator = torch.manual_seed(42) frames = pipe(image, decode_chunk_size=8, generator=generator).frames[0] # Export to mp4 video_path = "output_clip.mp4" # Logic to save frames as video... return video_path ``` ## Practical Tips for Developers If you are building video features today, keep these optimization strategies in mind: * **CFG Scale Tuning:** For video, a Classifier-Free Guidance (CFG) scale between 1.5 and 3.0 is usually the "sweet spot." Too high, and the video becomes over-saturated and "jittery." * **Resolution and Aspect Ratio:** Always generate at the model's native training resolution (e.g., 1024x576 for SVD). Upscaling should be a secondary post-processing step to save expensive GPU time. * **Frame Interpolation:** Instead of generating 60 frames directly (which is memory intensive), generate 15-20 frames and use a lighter model like RIFE or FILM to interpolate the "in-between" frames. This cuts compute costs by 60-70%. * **Batching:** If you are running a high-volume job, batch your video requests to keep the GPU at 100% utilization, minimizing the overhead of loading weights into VRAM. ## Bringing it to Production with Podstack Deploying these models shouldn't require managing complex Kubernetes clusters or overpaying for idle GPUs. With Podstack, you can turn your Python GPU functions into production-ready endpoints in seconds. By using the Podstack API, you can launch on-demand jobs for batch video processing or set up serverless inference endpoints that scale based on your traffic. Since Podstack bills per second, you only pay for the exact time the GPU is denoising frames. To get started, simply set your credentials: ```text Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key. ``` This workflow allows you to focus on prompt engineering and model selection while Podstack handles the underlying compute orchestration, ensuring your video generation pipeline is both fast and cost-effective.