Claude Code for TorchServe: PyTorch Model Serving — Claude Skills 360 Blog
Blog / AI / Claude Code for TorchServe: PyTorch Model Serving
AI

Claude Code for TorchServe: PyTorch Model Serving

Published: August 31, 2027
Read time: 5 min read
By: Claude Skills 360

TorchServe is PyTorch’s production model serving framework. pip install torchserve torch-model-archiver. Package a model: torch-model-archiver --model-name sentiment --version 1.0 --serialized-file model.pt --handler handler.py --extra-files index_to_name.json. Creates sentiment.mar. torchserve --start --model-store model_store/ --models sentiment=sentiment.mar serves on ports 8080 (inference) and 8081 (management). Handler class extends BaseHandler: override initialize(context) for model loading, preprocess(data) for input parsing, inference(data) for model forward pass, postprocess(output) for response formatting. @torch.jit.script or torch.export for optimized model packaging. Batch inference: --batch_size 8 --max_batch_delay 100 in config.properties or via Management API POST /models/{name}?batch_size=8&max_batch_delay=100. Model versioning: torch-model-archiver --version 2.0 then PUT /models/sentiment/2.0/set-default. Traffic split: PUT /models/sentiment?min_worker=2&initial_workers=2 and Management API for version weights. config.properties sets inference_address, management_address, metrics_address, number_of_netty_threads, job_queue_size, default_response_timeout. Metrics: metrics_address=http://0.0.0.0:8082 exposes Prometheus-compatible /metrics. Docker: official pytorch/torchserve:latest-gpu image. Kubernetes: Deployment + Service + HorizontalPodAutoscaler. Claude Code generates TorchServe handlers, model archiver scripts, config.properties, Docker setups, and TypeScript inference clients.

CLAUDE.md for TorchServe

## TorchServe Stack
- Version: torchserve >= 0.9, torch-model-archiver >= 0.9
- Handler: extend BaseHandler — initialize/preprocess/inference/postprocess
- Archive: torch-model-archiver --model-name --version --serialized-file --handler --extra-files
- Serve: torchserve --start --model-store ./model_store --models name=file.mar
- Inference: POST http://localhost:8080/predictions/{model_name}
- Management: GET/PUT/POST http://localhost:8081/models
- Config: config.properties — batch_size, max_batch_delay, number_of_netty_threads
- Metrics: http://localhost:8082/metrics (Prometheus format)

Custom Handler

# handler.py — TorchServe custom handler for sentiment classification
from __future__ import annotations
import json
import logging
import os
import time
from typing import Any

import torch
import torch.nn.functional as F
from ts.torch_handler.base_handler import BaseHandler

logger = logging.getLogger(__name__)


class SentimentHandler(BaseHandler):
    """
    Custom TorchServe handler for HuggingFace sentiment classification.
    Extends BaseHandler with tokenization preprocessing.
    """

    def __init__(self):
        super().__init__()
        self.tokenizer       = None
        self.labels: list[str] = []
        self.initialized     = False

    # ── Lifecycle ────────────────────────────────────────────────────────────

    def initialize(self, context) -> None:
        """Load model and tokenizer. Called once per worker on startup."""
        self.manifest  = context.manifest
        props          = context.system_properties
        model_dir      = props.get("model_dir")
        self.device    = torch.device(
            "cuda" if torch.cuda.is_available() and props.get("gpu_id") is not None else "cpu"
        )

        # Load serialized model (TorchScript or state_dict)
        serialized_file = self.manifest["model"]["serializedFile"]
        model_pt_path   = os.path.join(model_dir, serialized_file)
        self.model      = torch.jit.load(model_pt_path, map_location=self.device)
        self.model.eval()

        # Load tokenizer (packaged as extra_files)
        from transformers import AutoTokenizer
        self.tokenizer = AutoTokenizer.from_pretrained(model_dir)

        # Load label mapping from extra_files
        label_file = os.path.join(model_dir, "index_to_name.json")
        if os.path.exists(label_file):
            with open(label_file) as f:
                mapping = json.load(f)
            self.labels = [mapping[str(i)] for i in range(len(mapping))]
        else:
            self.labels = ["NEGATIVE", "NEUTRAL", "POSITIVE"]

        self.initialized = True
        logger.info("SentimentHandler initialized on %s", self.device)

    # ── Preprocessing ────────────────────────────────────────────────────────

    def preprocess(self, data: list[dict]) -> dict[str, torch.Tensor]:
        """
        Tokenize incoming text requests.
        data is a list of {"body": {"text": "...", "max_length": 512}} dicts.
        """
        texts = []
        max_length = 512

        for item in data:
            body = item.get("body") or item.get("data")
            if isinstance(body, (bytes, bytearray)):
                body = json.loads(body.decode("utf-8"))
            texts.append(body.get("text", ""))
            if "max_length" in body:
                max_length = min(body["max_length"], 512)

        tokens = self.tokenizer(
            texts,
            max_length=max_length,
            truncation=True,
            padding=True,
            return_tensors="pt",
        )
        return {k: v.to(self.device) for k, v in tokens.items()}

    # ── Inference ────────────────────────────────────────────────────────────

    def inference(self, inputs: dict[str, torch.Tensor]) -> torch.Tensor:
        """Run model forward pass."""
        with torch.no_grad():
            outputs = self.model(**inputs)
            probs   = F.softmax(outputs.logits, dim=-1)
        return probs

    # ── Postprocessing ───────────────────────────────────────────────────────

    def postprocess(self, probs: torch.Tensor) -> list[dict]:
        """Format results as JSON-serializable dicts."""
        results = []
        for row in probs:
            idx = int(row.argmax())
            results.append({
                "label": self.labels[idx] if idx < len(self.labels) else str(idx),
                "score": round(float(row[idx]), 4),
                "all_scores": {
                    self.labels[i]: round(float(s), 4)
                    for i, s in enumerate(row)
                    if i < len(self.labels)
                },
            })
        return results

Model Archiver Script

# scripts/archive_model.py — package model for TorchServe
import subprocess
import json
import os
import shutil
from pathlib import Path


def export_torchscript(model_name: str = "cardiffnlp/twitter-roberta-base-sentiment-latest"):
    """Export HuggingFace model to TorchScript for TorchServe."""
    import torch
    from transformers import AutoModelForSequenceClassification, AutoTokenizer

    print(f"Loading {model_name}...")
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model     = AutoModelForSequenceClassification.from_pretrained(model_name)
    model.eval()

    # Trace with dummy input
    dummy = tokenizer("Hello world", return_tensors="pt")
    with torch.no_grad():
        traced = torch.jit.trace(model, (dummy["input_ids"], dummy["attention_mask"]))

    os.makedirs("model_artifacts", exist_ok=True)
    torch.jit.save(traced, "model_artifacts/model.pt")

    # Save tokenizer files
    tokenizer.save_pretrained("model_artifacts/")

    # Create label mapping
    label_map = {
        "0": "NEGATIVE",
        "1": "NEUTRAL",
        "2": "POSITIVE",
    }
    with open("model_artifacts/index_to_name.json", "w") as f:
        json.dump(label_map, f)

    print("Exported TorchScript model to model_artifacts/")
    return "model_artifacts"


def archive_model(
    model_dir:   str = "model_artifacts",
    version:     str = "1.0",
    model_store: str = "model_store",
) -> str:
    """Create .mar archive with torch-model-archiver."""
    os.makedirs(model_store, exist_ok=True)

    # Collect extra files (tokenizer vocab, config, etc.)
    extra = [
        f for f in Path(model_dir).glob("**/*")
        if f.is_file() and f.name not in ("model.pt",)
        and f.suffix in (".json", ".txt", ".model")
    ]
    extra_files_arg = ",".join(str(f) for f in extra)

    cmd = [
        "torch-model-archiver",
        "--model-name",      "sentiment",
        "--version",         version,
        "--serialized-file", f"{model_dir}/model.pt",
        "--handler",         "handler.py",
        "--export-path",     model_store,
        "--force",
    ]
    if extra_files_arg:
        cmd += ["--extra-files", extra_files_arg]

    print("Running:", " ".join(cmd))
    subprocess.run(cmd, check=True)
    mar_path = f"{model_store}/sentiment.mar"
    print(f"Created: {mar_path}")
    return mar_path


if __name__ == "__main__":
    artifact_dir = export_torchscript()
    archive_model(model_dir=artifact_dir)
    print("Ready: torchserve --start --model-store model_store/ --models sentiment=sentiment.mar")

config.properties

# config.properties — TorchServe server configuration
inference_address=http://0.0.0.0:8080
management_address=http://0.0.0.0:8081
metrics_address=http://0.0.0.0:8082

# Threading
number_of_netty_threads=8
job_queue_size=1000

# Batching defaults (overridable per-model via Management API)
batch_size=8
max_batch_delay=50

# Timeouts
default_response_timeout=120
unregister_model_timeout=120

# Model store
model_store=/home/model-server/model-store
load_models=sentiment.mar

# Logging
vmargs=-Xmx4g -XX:MaxDirectMemorySize=512m -XX:ReservedCodeCacheSize=240m -XX:+UseContainerSupport

# Metrics
metrics_format=prometheus
enable_envvars_config=true

Docker Setup

# Dockerfile — TorchServe GPU container
FROM pytorch/torchserve:0.9.0-gpu

USER root

# Install extra Python deps
RUN pip install --no-cache-dir \
    transformers>=4.40.0 \
    sentencepiece \
    protobuf

# Copy artifacts
COPY model_store/  /home/model-server/model-store/
COPY handler.py    /home/model-server/handler.py
COPY config.properties /home/model-server/config.properties

USER model-server

EXPOSE 8080 8081 8082

CMD ["torchserve", \
     "--start", \
     "--model-store", "/home/model-server/model-store", \
     "--ts-config",   "/home/model-server/config.properties", \
     "--foreground"]

TypeScript Client

// lib/torchserve/client.ts — TypeScript client for TorchServe
const TORCHSERVE_URL = process.env.TORCHSERVE_URL ?? "http://localhost:8080"
const MGMT_URL       = process.env.TORCHSERVE_MGMT_URL ?? "http://localhost:8081"

export type SentimentResult = {
  label:      string
  score:      number
  all_scores: Record<string, number>
}

export async function predict(text: string): Promise<SentimentResult> {
  const res = await fetch(`${TORCHSERVE_URL}/predictions/sentiment`, {
    method:  "POST",
    headers: { "Content-Type": "application/json" },
    body:    JSON.stringify({ text }),
  })
  if (!res.ok) throw new Error(`TorchServe ${res.status}: ${await res.text()}`)
  return res.json()
}

export async function predictBatch(texts: string[]): Promise<SentimentResult[]> {
  const results = await Promise.all(texts.map(text => predict(text)))
  return results
}

/** Management API — list registered models */
export async function listModels(): Promise<{ models: { modelName: string; modelVersion: string }[] }> {
  const res = await fetch(`${MGMT_URL}/models`)
  return res.json()
}

/** Management API — scale workers for a model */
export async function scaleWorkers(modelName: string, minWorkers: number, maxWorkers: number): Promise<void> {
  const url = `${MGMT_URL}/models/${modelName}?min_worker=${minWorkers}&max_worker=${maxWorkers}`
  const res = await fetch(url, { method: "PUT" })
  if (!res.ok) throw new Error(`Scale failed: ${await res.text()}`)
}

/** Management API — set default version for A/B routing */
export async function setDefaultVersion(modelName: string, version: string): Promise<void> {
  const res = await fetch(`${MGMT_URL}/models/${modelName}/${version}/set-default`, { method: "PUT" })
  if (!res.ok) throw new Error(`Version set failed: ${await res.text()}`)
}

For the Ray Serve alternative when needing Python-native multi-model pipelines with actor-based horizontal scaling, dynamic autoscaling, and DeploymentHandle composition across a Ray cluster — Ray Serve handles complex DAGs of models while TorchServe is specifically optimized for PyTorch model packaging, TorchScript/TensorRT optimization, and the model archiver workflow that creates self-contained .mar artifacts from trained models. For the Triton Inference Server alternative when needing NVIDIA’s maximum-throughput inference server with TensorRT engine optimization, concurrent model execution, and multi-framework support (ONNX, TensorFlow SavedModel, TensorRT, PyTorch TorchScript) in a single server — Triton maximizes raw GPU throughput for production-scale serving while TorchServe provides a simpler Python-idiomatic API suitable for PyTorch-only deployments. The Claude Skills 360 bundle includes TorchServe skill sets covering custom handlers, model archiving, batching configuration, and Docker deployment. Start with the free tier to try PyTorch serving generation.

Keep Reading

AI

Claude Code for email.contentmanager: Python Email Content Accessors

Read and write EmailMessage body content with Python's email.contentmanager module and Claude Code — email contentmanager ContentManager for the class that maps content types to get and set handler functions allowing EmailMessage to support get_content and set_content with type-specific behaviour, email contentmanager raw_data_manager for the ContentManager instance that handles raw bytes and str payloads without any conversion, email contentmanager content_manager for the standard ContentManager instance used by email.policy.default that intelligently handles text plain text html multipart and binary content types, email contentmanager get_content_text for the handler that returns the decoded text payload of a text-star message part as a str, email contentmanager get_content_binary for the handler that returns the raw decoded bytes payload of a non-text message part, email contentmanager get_data_manager for the get-handler lookup used by EmailMessage get_content to find the right reader function for the content type, email contentmanager set_content text for the handler that creates and sets a text part correctly choosing charset and transfer encoding, email contentmanager set_content bytes for the handler that creates and sets a binary part with base64 encoding and optional filename Content-Disposition, email contentmanager EmailMessage get_content for the method that reads the message body using the registered content manager handlers, email contentmanager EmailMessage set_content for the method that sets the message body and MIME headers in one call, email contentmanager EmailMessage make_alternative make_mixed make_related for the methods that convert a simple message into a multipart container, email contentmanager EmailMessage add_attachment for the method that attaches a file or bytes to a multipart message, and email contentmanager integration with email.message and email.policy and email.mime and io for building high-level email readers attachment extractors text body accessors HTML readers and policy-aware MIME construction pipelines.

5 min read Feb 12, 2029
AI

Claude Code for email.charset: Python Email Charset Encoding

Control header and body encoding for international email with Python's email.charset module and Claude Code — email charset Charset for the class that wraps a character set name with the encoding rules for header encoding and body encoding describing how to encode text for that charset in email messages, email charset Charset header_encoding for the attribute specifying whether headers using this charset should use QP quoted-printable encoding BASE64 encoding or no encoding, email charset Charset body_encoding for the attribute specifying the Content-Transfer-Encoding to use for message bodies in this charset such as QP or BASE64, email charset Charset output_codec for the attribute giving the Python codec name used to encode the string to bytes for the wire format, email charset Charset input_codec for the attribute giving the Python codec name used to decode incoming bytes to str, email charset Charset get_output_charset for returning the output charset name, email charset Charset header_encode for encoding a header string using the charset's header_encoding method, email charset Charset body_encode for encoding body content using the charset's body_encoding, email charset Charset convert for converting a string from the input_codec to the output_codec, email charset add_charset for registering a new charset with custom encoding rules in the global charset registry, email charset add_alias for adding an alias name that maps to an existing registered charset, email charset add_codec for registering a codec name mapping for use by the charset machinery, and email charset integration with email.message and email.mime and email.policy and email.encoders for building international email senders non-ASCII header encoders Content-Transfer-Encoding selectors charset-aware message constructors and MIME encoding pipelines.

5 min read Feb 11, 2029
AI

Claude Code for email.utils: Python Email Address and Header Utilities

Parse and format RFC 2822 email addresses and dates with Python's email.utils module and Claude Code — email utils parseaddr for splitting a display-name plus angle-bracket address string into a realname and email address tuple, email utils formataddr for combining a realname and address string into a properly quoted RFC 2822 address with angle brackets, email utils getaddresses for parsing a list of raw address header strings each potentially containing multiple comma-separated addresses into a list of realname address tuples, email utils parsedate for parsing an RFC 2822 date string into a nine-tuple compatible with time.mktime, email utils parsedate_tz for parsing an RFC 2822 date string into a ten-tuple that includes the UTC offset timezone in seconds, email utils parsedate_to_datetime for parsing an RFC 2822 date string into an aware datetime object with timezone, email utils formatdate for formatting a POSIX timestamp or the current time as an RFC 2822 date string with optional usegmt and localtime flags, email utils format_datetime for formatting a datetime object as an RFC 2822 date string, email utils make_msgid for generating a globally unique Message-ID string with optional idstring and domain components, email utils decode_rfc2231 for decoding an RFC 2231 encoded parameter value into a tuple of charset language and value, email utils encode_rfc2231 for encoding a string as an RFC 2231 encoded parameter value, email utils collapse_rfc2231_value for collapsing a decoded RFC 2231 tuple to a Unicode string, and email utils integration with email.message and email.headerregistry and datetime and time for building address parsers date formatters message-id generators header extractors and RFC-compliant email construction utilities.

5 min read Feb 10, 2029

Put these ideas into practice

Claude Skills 360 gives you production-ready skills for everything in this article — and 2,350+ more. Start free or go all-in.

Back to Blog

Get 360 skills free