必须先安装 Docker,若装的是 Docker Engine 而非 Docker Desktop 还需另装 Buildx;Windows 不原生支持,需在 Windows 11 上用 WSL 2 按 Linux 方式安装;macOS 手动安装二进制后若遇 Gatekeeper 拦截需执行 xattr -d com.apple.quarantine 解除隔离
brew install replicate/tap/cogREADME 未给出具体显存要求;cog.yaml 中可设 gpu: true,示例用 docker run --gpus all 启用 GPU;未说明支持的 GPU 厂商与型号。
把机器学习模型打包成标准生产级 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 起服务
容易踩的坑
- 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
succeededwithoutput: null, or silently drop files from list outputs. Any failed upload now fails the prediction with an error, and cancellation still reportscanceled. (#3197)
- Predictions now fail when an output upload fails. Previously, a file upload that timed out or was rejected could leave a prediction marked
- v0.23.02026-09-22 · 2026-09-22 22:05 UTC
查看更新说明
New features
- GPU compatibility warnings in
cog doctor.cog doctornow 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> --jsonemits 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
.dockerignoreguidance. 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-packagesand creates the expectedpythonalias for both prebuilt and direct CUDA 13 base images. (#3160)
- GPU compatibility warnings in
- v0.22.02026-08-14 · 2026-08-14 00:52 UTC
查看更新说明
Breaking changes
- Local servers now bind to
127.0.0.1instead of0.0.0.0.cog serve,cog run -p,cog predict, andcog trainno longer expose the prediction endpoint to your whole network by default. To get the old behavior back, usecog serve --host 0.0.0.0orcog run -p 0.0.0.0:8888—-pnow acceptshost:port. (#2812)
New features
-
Browser playground.
cog playgroundstarts 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,0picks a free one) and both URLs are printed on startup. (#3154) -
@cog.concurrentdecorator. Configure async runner concurrency on the method that does the work instead of incog.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.maxincog.yamlstill 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, andcog trainnow validate-iinputs 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 fromcog.yaml; for existing images it's read from theopenapi_schemalabel. (#3097) -
acceptonPathandFileinputs. 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 asx-cog-acceptin the OpenAPI schema so UIs and clients know what to offer. Usingaccepton a non-file type is a build error. (#2863) -
Local wheels and source archives in requirements.
build.python_requirementsnow accepts bare local paths like./dist/mylib-0.1.0-py3-none-any.whlor./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.xzare supported. (#3095)
Improvements
- Readable logs from local commands.
cog serve,cog run,cog predict, andcog trainnow run the model with console-formatted logs instead of production JSON. Deployed models are unaffected. (#2806) - Download progress for
cog weights.cog weights importandcog weights pullshow 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-imageworks, and how it interacts with--use-cuda-base-image. (#3088)
Bug fixes
- GPU builds on CUDA base images work again. Builds on
nvidia/cudaimages failed withexternally-managed-environmentbecause uv-managed Python is marked PEP 668 externally managed and uv 0.9.x enforces it. Cog now passes--break-system-packageswherever it installs into a uv-managed Python, not just incog base-image. (#3073) - Explicit
cudnnwith a CUDA minor version now validates. A config pairingcuda: "11.6"withcudnn: "8"was rejected up front even though11.6resolves fine to a patch-level base image likenvidia/cuda:11.6.2-cudnn8-devel-ubuntu20.04. Validation now matches versions the same way image selection do
- Local servers now bind to
- 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-streamto receivestart,output,log,metric, and terminalcompletedevents for predictors that explicitly opt in with@streaming/@cog.streaming. Reconnecting clients can replay retained in-flight prediction events withPUT /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-exampleshave moved into this repository underexamples/, with updatedrun.py/BaseRunnerexamples for common workflows including images, training, notebooks, streaming, concurrency, context, and Replicate API usage. (#3055) - Experimental warning for
cog weights. Everycog weightssubcommand 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 legacypredict()fallback behavior, and resolves inherited and imported targets more consistently. (#3027)
Bug fixes
cog.Secretinputs now work with coglet-backed predictions. Predictors that annotate inputs asSecret,Optional[Secret], orSecret | Nonenow receivecog.types.Secretvalues at runtime again, restoring behavior that regressed in the Rust/coglet runtime rewrite. (#3057)cog doctor --fixnow 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 annotationsno longer reject validsetup() -> Nonemethods or accept invalidrun() -> Nonemethods becauseNoneannotations were stored as strings. (#3034) cog servenow mounts weights likecog run. Models served locally now receive configured weights consistently with local prediction runs. (#3044)- Omitted optional inputs now resolve to
Noneat the HTTP edge. Optional predictor inputs omitted from HTTP requests are now passed asNoneinstead of being treated inconsistently by request handling. (#3051)
- Server-Sent Event prediction streams. HTTP prediction requests can now ask for
- 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)
用户点评
登录用户的真实使用记录,可按版本和硬件筛选还没有人点评。第一个说出真实体验的人最有价值。
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
Dockerfilecan 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
- Get started with an example model
- Get started with your own model
- Using Cog with notebooks
- Using Cog with Windows 11
- Browse the example models in this repo
- Deploy models with Cog
cog.yamlreference to learn how to define your model's environment- Run interface reference to learn how the
Runnerinterface works - Training interface reference to learn how to add a fine-tuning API to your model
- HTTP API reference to learn how to use the HTTP API that models serve
Need help?
Contributors ✨
Thanks goes to these wonderful people (emoji key):
This project follows the all-contributors specification. Contributions of any kind welcome!