cog

replicateApache-2.0活跃维护

把机器学习模型打包成标准 Docker 容器,自动生成 HTTP 推理服务接口,省去自己写 Dockerfile 和部署脚本的麻烦。

Containers for machine learning

v0.23.1发布于 2026-10-20 17:53 UTC9,497star +1 / 7 天702fork同步于 2026-11-10 11:30 UTC

怎么上手

由 README 提炼,执行前请确认
brew install replicate/tap/cog
硬件要求按 README 说明

README 未给出具体显存要求;cog.yaml 中可设 gpu: true,示例用 docker run --gpus all 启用 GPU;未说明支持的 GPU 厂商与型号。

需要 CUDA有 Docker 镜像
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

把机器学习模型打包成标准生产级 Docker 容器的开源工具,省去手写 Dockerfile 和调 CUDA 的麻烦

把机器学习模型打包成标准 Docker 容器,自动生成 HTTP 推理服务接口,省去自己写 Dockerfile 和部署脚本的麻烦。

核心能力

  • 用 cog.yaml 声明环境并自动生成符合最佳实践的 Docker 镜像
  • 自动匹配 CUDA/cuDNN/PyTorch/TensorFlow/Python 兼容组合
  • 用 Python 类型注解定义输入输出并生成 OpenAPI schema 做校验
  • 基于 Rust/Axum 动态生成 RESTful HTTP 推理服务
  • 支持 cog run 本地推理、cog build 构建镜像、cog serve 起服务

容易踩的坑

必须先安装 Docker,若装的是 Docker Engine 而非 Docker Desktop 还需另装 Buildx;Windows 不原生支持,需在 Windows 11 上用 WSL 2 按 Linux 方式安装;macOS 手动安装二进制后若遇 Gatekeeper 拦截需执行 xattr -d com.apple.quarantine 解除隔离

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v0.23.1
  1. v0.23.1最新正式版2026-10-20 · 2026-10-20 17:53 UTC

    Bug fixes

    • Predictions now fail when an output upload fails. Previously, a file upload that timed out or was rejected could leave a prediction marked succeeded with output: null, or silently drop files from list outputs. Any failed upload now fails the prediction with an error, and cancellation still reports canceled. (#3197)
  2. v0.23.02026-09-22 · 2026-09-22 22:05 UTC
    查看更新说明

    New features

    • GPU compatibility warnings in cog doctor. cog doctor now warns when the resolved PyTorch and CUDA wheel ships no kernels for the local GPU, catching images that build successfully but fail when they run CUDA operations. (#3104)
    • OpenTelemetry tracing. Models can opt into distributed traces spanning Cog's HTTP server, parent and worker processes, and Python model code. Cog continues incoming W3C trace context, exports through OTLP, and leaves tracing disabled by default. (#3157)
    • JSON output for cog push. cog push <target> --json emits one versioned JSON document with digest-pinned image, model, and managed-weight references for image and bundle projects. Progress and diagnostics remain on stderr. (#3178)

    Improvements

    • .dockerignore guidance. The getting-started documentation now explains Cog's Docker build context and how to exclude development-only files to reduce build time and image size. (#3165)

    Bug fixes

    • CUDA 13 builds work with uv-managed Python. Cog now passes --break-system-packages and creates the expected python alias for both prebuilt and direct CUDA 13 base images. (#3160)
  3. v0.22.02026-08-14 · 2026-08-14 00:52 UTC
    查看更新说明

    Breaking changes

    • Local servers now bind to 127.0.0.1 instead of 0.0.0.0. cog serve, cog run -p, cog predict, and cog train no longer expose the prediction endpoint to your whole network by default. To get the old behavior back, use cog serve --host 0.0.0.0 or cog run -p 0.0.0.0:8888 — -p now accepts host:port. (#2812)

    New features

    • Browser playground. cog playground starts a local, schema-driven web UI for talking to a running model — a Postman-like tool that reads the model's OpenAPI schema and builds the input form for you, with a request inspector and webhook relay. Point it at anything speaking the Cog HTTP API with --target. (#3123)

    • cog serve --playground. Serve the model and the playground in one command. The playground gets its own port (--playground-port, default 9000, 0 picks a free one) and both URLs are printed on startup. (#3154)

    • @cog.concurrent decorator. Configure async runner concurrency on the method that does the work instead of in cog.yaml:

      class Runner(cog.BaseRunner):
          @cog.concurrent(max=4)
          async def run(self, prompt: str = cog.Input()) -> str:
              return await generate(prompt)
      

      The value is extracted statically at build time. concurrency.max in cog.yaml still works and still takes precedence, but it now warns on build — remove it when you migrate. (#3089)

    • Input validation before build and run. cog predict, cog run, and cog train now validate -i inputs against the model's OpenAPI schema before building the image or starting the container, so a typo fails in a second rather than after a full build. Covers unknown input names, missing required inputs, type mismatches, enum values, numeric bounds, string length, and regex patterns. The schema is generated statically from cog.yaml; for existing images it's read from the openapi_schema label. (#3097)

    • accept on Path and File inputs. Declare the MIME types or extensions an input takes — Input(accept="image/*"), Input(accept="audio/wav,audio/mp3"), Input(accept=".safetensors,.bin") — and Cog emits it as x-cog-accept in the OpenAPI schema so UIs and clients know what to offer. Using accept on a non-file type is a build error. (#2863)

    • Local wheels and source archives in requirements. build.python_requirements now accepts bare local paths like ./dist/mylib-0.1.0-py3-none-any.whl or ./packages/localpkg.tar.gz. Paths resolve relative to the requirements file, and only the referenced artifacts get staged into the build. .whl, .zip, .tar.gz, .tgz, .tar.bz2, and .tar.xz are supported. (#3095)

    Improvements

    • Readable logs from local commands. cog serve, cog run, cog predict, and cog train now run the model with console-formatted logs instead of production JSON. Deployed models are unaffected. (#2806)
    • Download progress for cog weights. cog weights import and cog weights pull show live Docker-style progress while they populate the local weight store. (#3087)
    • Prebuilt base images are documented. New base images page covers what's on Cog's prebuilt base images, how --use-cog-base-image works, and how it interacts with --use-cuda-base-image. (#3088)

    Bug fixes

    • GPU builds on CUDA base images work again. Builds on nvidia/cuda images failed with externally-managed-environment because uv-managed Python is marked PEP 668 externally managed and uv 0.9.x enforces it. Cog now passes --break-system-packages wherever it installs into a uv-managed Python, not just in cog base-image. (#3073)
    • Explicit cudnn with a CUDA minor version now validates. A config pairing cuda: "11.6" with cudnn: "8" was rejected up front even though 11.6 resolves fine to a patch-level base image like nvidia/cuda:11.6.2-cudnn8-devel-ubuntu20.04. Validation now matches versions the same way image selection do
  4. v0.21.02026-06-16 · 2026-06-16 20:30 UTC
    查看更新说明

    New features

    • Server-Sent Event prediction streams. HTTP prediction requests can now ask for Accept: text/event-stream to receive start, output, log, metric, and terminal completed events for predictors that explicitly opt in with @streaming / @cog.streaming. Reconnecting clients can replay retained in-flight prediction events with PUT /predictions/{id}. (#3019)
    • JSON-native union inputs. Cog now supports union-typed predictor inputs in generated schemas and HTTP request handling, allowing compatible JSON-native values to be resolved correctly. (#3048)

    Improvements

    • Example models now live in the Cog repository. The example models from replicate/cog-examples have moved into this repository under examples/, with updated run.py / BaseRunner examples for common workflows including images, training, notebooks, streaming, concurrency, context, and Replicate API usage. (#3055)
    • Experimental warning for cog weights. Every cog weights subcommand now prints a warning that the weights workflow is experimental and should not be relied on in production workflows yet. (#3025)
    • Static schema parser target resolution. The static Python schema parser now uses run() as the primary prediction entry point while preserving legacy predict() fallback behavior, and resolves inherited and imported targets more consistently. (#3027)

    Bug fixes

    • cog.Secret inputs now work with coglet-backed predictions. Predictors that annotate inputs as Secret, Optional[Secret], or Secret | None now receive cog.types.Secret values at runtime again, restoring behavior that regressed in the Rust/coglet runtime rewrite. (#3057)
    • cog doctor --fix now shows available remediation text. Findings without an auto-fix now display their remediation message instead of incorrectly saying no auto-fix is available. (#3031)
    • Cog-managed weight uploads now send the correct layer media type. Weight layer uploads now propagate the Cog weight media type during registry finalization while preserving regular image-layer behavior. (#3033)
    • Predictor validation now handles PEP 563 string annotations. Predictor files using from __future__ import annotations no longer reject valid setup() -> None methods or accept invalid run() -> None methods because None annotations were stored as strings. (#3034)
    • cog serve now mounts weights like cog run. Models served locally now receive configured weights consistently with local prediction runs. (#3044)
    • Omitted optional inputs now resolve to None at the HTTP edge. Optional predictor inputs omitted from HTTP requests are now passed as None instead of being treated inconsistently by request handling. (#3051)
  5. v0.21.0-rc.3pre-release2026-06-05 · 2026-06-05 14:49 UTC
    查看更新说明

    Changelog

    • d6c2b7064006b93cf4e608fd7157950bd5296417 Bump version to 0.21.0-rc.3 (#3050)
    • 63c65dfcbe0f2507ded4f1518d41be9480f323fb feat: support JSON-native union inputs (#3048)

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    Cog: Containers for machine learning

    Cog is an open-source tool that lets you package machine learning models in a standard, production-ready container.

    You can deploy your packaged model to your own infrastructure, or to Replicate.

    Highlights

    • 📦 Docker containers without the pain. Writing your own Dockerfile can be a bewildering process. With Cog, you define your environment with a simple configuration file and it generates a Docker image with all the best practices: Nvidia base images, efficient caching of dependencies, installing specific Python versions, sensible environment variable defaults, and so on.

    • 🤬️ No more CUDA hell. Cog knows which CUDA/cuDNN/PyTorch/Tensorflow/Python combos are compatible and will set it all up correctly for you.

    • ✅ Define the inputs and outputs for your model with standard Python. Then, Cog generates an OpenAPI schema and validates the inputs and outputs.

    • 🎁 Automatic HTTP inference server: Your model's types are used to dynamically generate a RESTful HTTP API using a high-performance Rust/Axum server.

    • 🚀 Ready for production. Deploy your model anywhere that Docker images run. Your own infrastructure, or Replicate.

    How it works

    Define the Docker environment your model runs in with cog.yaml:

    build:
      gpu: true
      system_packages:
        - "libgl1"
        - "libglib2.0-0"
      python_version: "3.13"
      python_requirements: requirements.txt
    run: "run.py:Runner"
    

    Define how your model runs with run.py:

    from cog import BaseRunner, Input, Path
    import torch
    
    class Runner(BaseRunner):
        def setup(self):
            """Load the model into memory to make running multiple inferences efficient"""
            self.model = torch.load("./weights.pth")
    
        # The arguments and types the model takes as input
        def run(self,
              image: Path = Input(description="Grayscale input image")
        ) -> Path:
            """Run the model"""
            processed_image = preprocess(image)
            output = self.model(processed_image)
            return postprocess(output)
    

    In the above we accept a path to the image as an input, and return a path to our transformed image after running it through our model.

    Now, you can run the model:

    $ cog run -i [email protected]
    --> Building Docker image...
    --> Running...
    --> Output written to output.jpg
    

    Or, build a Docker image for deployment:

    $ cog build -t my-classification-model
    --> Building Docker image...
    --> Built my-classification-model:latest
    
    $ docker run -d -p 5000:5000 --gpus all my-classification-model
    
    $ curl http://localhost:5000/predictions -X POST \
        -H 'Content-Type: application/json' \
        -d '{"input": {"image": "https://.../input.jpg"}}'
    

    Or, combine build and run via the serve command:

    $ cog serve -p 8080
    
    $ curl http://localhost:8080/predictions -X POST \
        -H 'Content-Type: application/json' \
        -d '{"input": {"image": "https://.../input.jpg"}}'
    

    Why are we building this?

    It's really hard for researchers to ship machine learning models to production.

    Part of the solution is Docker, but it is so complex to get it to work: Dockerfiles, pre-/post-processing, Flask servers, CUDA versions. More often than not the researcher has to sit down with an engineer to get the damn thing deployed.

    Andreas and Ben created Cog. Andreas used to work at Spotify, where he built tools for building and deploying ML models with Docker. Ben worked at Docker, where he created Docker Compose.

    We realized that, in addition to Spotify, other companies were also using Docker to build and deploy machine learning models. Uber and others have built similar systems. So, we're making an open source version so other people can do this too.

    Hit us up if you're interested in using it or want to collaborate with us. Email us at [email protected].

    Prerequisites

    • macOS, Linux or Windows 11. Cog works on macOS, Linux and Windows 11 with WSL 2
    • Docker. Cog uses Docker to create a container for your model. You'll need to install Docker before you can run Cog. If you install Docker Engine instead of Docker Desktop, you will need to install Buildx as well.

    Install

    Choose your platform for installation instructions.

    The easiest way to install Cog on macOS is with Homebrew:

    brew install replicate/tap/cog
    

    You can also use the install script:

    # bash, zsh, and other shells
    sh <(curl -fsSL https://cog.run/install.sh)
    
    # fish shell
    sh (curl -fsSL https://cog.run/install.sh | psub)
    
    # download with wget and run in a separate command
    wget -qO- https://cog.run/install.sh
    sh ./install.sh
    

    Or install manually:

    sudo curl -o /usr/local/bin/cog -L "https://github.com/replicate/cog/releases/latest/download/cog_$(uname -s)_$(uname -m | sed 's/aarch64/arm64/')"
    sudo chmod +x /usr/local/bin/cog
    sudo xattr -d com.apple.quarantine /usr/local/bin/cog 2>/dev/null || true
    

    If you see a Gatekeeper warning saying the binary "cannot be opened because the developer cannot be verified", run:

    sudo xattr -d com.apple.quarantine /usr/local/bin/cog
    

    You can install Cog using the install script:

    # bash, zsh, and other shells
    sh <(curl -fsSL https://cog.run/install.sh)
    
    # fish shell
    sh (curl -fsSL https://cog.run/install.sh | psub)
    
    # download with wget and run in a separate command
    wget -qO- https://cog.run/install.sh
    sh ./install.sh
    

    Or install manually:

    sudo curl -o /usr/local/bin/cog -L "https://github.com/replicate/cog/releases/latest/download/cog_$(uname -s)_$(uname -m | sed 's/aarch64/arm64/')"
    sudo chmod +x /usr/local/bin/cog
    

    Cog does not natively support Windows, but you can run it on Windows 11 using WSL 2. Once WSL 2 is set up, follow the Linux installation instructions above.

    To install Cog inside a Docker image:

    RUN sh -c "INSTALL_DIR=\"/usr/local/bin\" SUDO=\"\" $(curl -fsSL https://cog.run/install.sh)"
    

    Upgrade

    If you're using macOS and you previously installed Cog with Homebrew, run the following:

    brew upgrade replicate/tap/cog
    

    Otherwise, you can upgrade to the latest version by running the same commands you used to install it.

    Development

    See CONTRIBUTING.md for how to set up a development environment and build from source.

    Next steps

    Need help?

    Ask DeepWiki

    Contributors ✨

    Thanks goes to these wonderful people (emoji key):

    This project follows the all-contributors specification. Contributions of any kind welcome!