Repository navigation
Expand file tree
/
Copy pathDockerfile.aeo
More file actions
248 lines (211 loc) · 11.6 KB
/
Copy pathDockerfile.aeo
File metadata and controls
248 lines (211 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# syntax=docker/dockerfile:1
#
# Docker image for the AI visibility (AEO) Temporal worker, which runs on aeo-task-queue.
#
# The worker scores how AI answers talk about each brand with ONNX sentiment models baked in below. It needs the
# ML dependencies of the `sentiment` group in pyproject.toml (transformers, ONNX Runtime, torch), and each model it
# loads has its own bake step: pinned to a Hugging Face revision, checked against SHA256 hashes, and smoke tested.
#
# Same as pyproject.toml so that uv can pick it up and doesn't need to download a different Python version.
# Keep this uv version the same as Dockerfile and Dockerfile.llm-analytics. It must satisfy [tool.uv] required-version
# in pyproject.toml, because `uv sync` refuses to run with an older uv.
FROM ghcr.io/astral-sh/uv:0.13.10@sha256:a3ea1357342c1a4bf9a0c53a3deb1b55379aefa037338d8113d5771efa01774f AS uv
FROM python:3.14.10-slim-bookworm@sha256:e60ad028afdcdd14772a3d46decf0eaf616720f9102aeb4397a2045ff6718c3d
SHELL ["/bin/bash", "-e", "-o", "pipefail", "-c"]
# Copy uv
COPY --from=uv /uv /uvx /bin/
# Set working directory
WORKDIR /code
# uv settings for Docker builds
ENV UV_COMPILE_BYTECODE=1
ENV UV_LINK_MODE=copy
ENV UV_PROJECT_ENVIRONMENT=/python-runtime
ENV UV_PYTHON_DOWNLOADS=never
# Install system dependencies
RUN apt-get update && \
apt-get install -y --no-install-recommends \
# Upgrades the CA bundle that the pinned base image freezes.
"ca-certificates" \
"build-essential" \
# sentencepiece (aeo-sentiment group) has no wheel for this Python, so uv builds it, and its build runs cmake.
"cmake" \
"git" \
"libpq-dev" \
"libxmlsec1=1.2.37-2" \
"libxmlsec1-dev=1.2.37-2" \
"libffi-dev" \
"zlib1g-dev" \
"pkg-config" \
&& \
rm -rf /var/lib/apt/lists/*
# Install Python dependencies including sentiment ML deps
RUN --mount=type=cache,id=uv-libxmlsec1.2.37-2,target=/root/.cache/uv \
--mount=type=bind,source=uv.lock,target=uv.lock \
--mount=type=bind,source=pyproject.toml,target=pyproject.toml \
--mount=type=bind,source=tools/hogli,target=tools/hogli \
# uv sync validates workspace membership even with --no-dev, so every
# workspace member must be present in the build context. packages/owners-yaml is also a real install
# source here: owners-yaml is a runtime dependency (stamphog's digest reads owners.yaml
# through it, and posthog/urls.py imports that chain unconditionally), and --no-editable copies
# it into the venv so the image never depends on this bind mount's path surviving.
--mount=type=bind,source=packages/owners-yaml,target=packages/owners-yaml \
--mount=type=bind,source=packages/personhog-proto,target=packages/personhog-proto \
uv sync --locked --no-dev --no-editable --no-install-project --group sentiment --group aeo-sentiment --no-binary-package lxml --no-binary-package xmlsec
ENV PATH=/python-runtime/bin:$PATH \
PYTHONPATH=/python-runtime \
POSTHOG_SENTIMENT_MODEL_CACHE=/opt/posthog-sentiment-model \
POSTHOG_ASPECT_SENTIMENT_MODEL_CACHE=/opt/posthog-aspect-sentiment-model
# owners-yaml is installed from a bind mount that does not survive into the image, so a missing
# --no-editable above leaves an editable install pointing at /code/packages/owners-yaml and every Django
# entrypoint dies on `import owners_yaml` at runtime instead of here. The root Dockerfile asserts
# the same invariant with `test -d packages/owners-yaml/owners_yaml`; this image never copies that source
# tree, so assert importability instead of presence. personhog-proto is installed from a bind mount
# the same way. Django loads posthog.models at startup, which imports posthog.personhog_client and
# through it the generated personhog package, so a stale or editable install breaks every Django
# entrypoint.
RUN python -c "import owners_yaml, personhog.service.v1.service_pb2_grpc"
# Pre-bake the live sentiment model (twitter-roberta), which labels brand mentions today. Remove this step once the
# aspect model below takes over as the live labeler; Dockerfile.llm-analytics keeps its own copy for AI observability.
#
# Pre-bake the sentiment ONNX model so workers don't download from HuggingFace on startup.
# Downloads from a pinned HuggingFace revision, exports to ONNX, verifies file integrity
# via SHA256 checksums, and runs a smoke test to confirm correct inference output.
#
# To update the model:
# 1. Update MODEL_REVISION to the new commit SHA from HuggingFace
# 2. Run the export locally to compute new SHA256 hashes for config.json and tokenizer.json
# 3. Update EXPECTED_HASHES below
# 4. Rebuild the image
RUN <<'BAKE_MODEL'
python -c "
import hashlib, os, sys, torch
from transformers import AutoTokenizer, pipeline
from optimum.onnxruntime import ORTModelForSequenceClassification
MODEL_NAME = 'cardiffnlp/twitter-roberta-base-sentiment-latest'
MODEL_REVISION = '3216a57f2a0d9c45a2e6c20157c20c49fb4bf9c7'
EXPECTED_HASHES = {
'config.json': '6f9c837680f529dd63871255651ca177bc259fd7c7f64cd5a4d6fcf0c36b8863',
'tokenizer.json': '727009a8214ddfa5af1deedf1006d4d06e8e51e54aa5f03566263d4e19bfcdce',
}
SOURCE_HASHES = {
'pytorch_model.bin': '4d24a3e32a88ed1c4e5b789fc6644e2e767500554e954b27dccf52a8e762cbae',
}
cache_dir = os.environ['POSTHOG_SENTIMENT_MODEL_CACHE']
os.makedirs(cache_dir, exist_ok=True)
# The bytes the export reads. config.json and tokenizer.json are checked after the export below; this checks the
# weights (and the vocabulary) before anything parses them.
from huggingface_hub import hf_hub_download
for filename, expected_sha in SOURCE_HASHES.items():
path = hf_hub_download(MODEL_NAME, filename, revision=MODEL_REVISION)
actual_sha = hashlib.sha256(open(path, 'rb').read()).hexdigest()
if actual_sha != expected_sha:
print(f'SOURCE HASH MISMATCH for {filename}: expected {expected_sha}, got {actual_sha}', file=sys.stderr)
sys.exit(1)
print(f' verified source {filename}: {actual_sha}')
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, revision=MODEL_REVISION)
# PyTorch 2.9+ defaults torch.onnx.export to dynamo=True which breaks optimum
original_export = torch.onnx.export
def export_with_dynamo_disabled(*args, **kwargs):
kwargs.setdefault('dynamo', False)
return original_export(*args, **kwargs)
torch.onnx.export = export_with_dynamo_disabled
model = ORTModelForSequenceClassification.from_pretrained(MODEL_NAME, revision=MODEL_REVISION, export=True)
torch.onnx.export = original_export
model.save_pretrained(cache_dir)
tokenizer.save_pretrained(cache_dir)
for filename, expected_sha in EXPECTED_HASHES.items():
filepath = os.path.join(cache_dir, filename)
actual_sha = hashlib.sha256(open(filepath, 'rb').read()).hexdigest()
if actual_sha != expected_sha:
print(f'HASH MISMATCH for {filename}:', file=sys.stderr)
print(f' expected: {expected_sha}', file=sys.stderr)
print(f' actual: {actual_sha}', file=sys.stderr)
sys.exit(1)
print(f' verified {filename}: {actual_sha}')
pipe = pipeline('sentiment-analysis', model=model, tokenizer=tokenizer, top_k=None, truncation=True, max_length=512)
result = pipe('I love this product')[0]
labels = {r['label']: r['score'] for r in result}
assert labels.get('positive', 0) > 0.5, f'Smoke test failed: expected positive > 0.5, got {labels}'
print(f' smoke test passed: positive={labels[\"positive\"]:.4f}')
print(f'Model baked into {cache_dir}')
"
# The download cache holds the PyTorch weights the export read; the image keeps only the ONNX copy.
rm -rf /root/.cache/huggingface
BAKE_MODEL
# Pre-bake the aspect sentiment model (DeBERTa-v3), which scores (sentence, brand) pairs
# (products/aeo/backend/sentiment_shadow.py). Same pinning, hash check and smoke test as above; update it the same way.
RUN <<'BAKE_ASPECT_MODEL'
python -c "
import hashlib, os, sys, torch
from transformers import AutoTokenizer
from optimum.onnxruntime import ORTModelForSequenceClassification
MODEL_NAME = 'yangheng/deberta-v3-base-absa-v1.1'
MODEL_REVISION = '10c9dff335a44073e1352360c3a7bc54dc58eb01'
EXPECTED_HASHES = {
'config.json': '8611badc19ca2f32c59654794b29831a2fd9f863fa3411effc123eb779b3dc06',
'tokenizer.json': '5124ef2ead1a10a717703bc436de7f353da76d6340e4587719b42b1693707964',
}
SOURCE_HASHES = {
'model.safetensors': '270559fb59fec507f6a105d2c7765af0b61c685670dbbcf52e551c6fa160601e',
'spm.model': 'c679fbf93643d19aab7ee10c0b99e460bdbc02fedf34b92b05af343b4af586fd',
}
cache_dir = os.environ['POSTHOG_ASPECT_SENTIMENT_MODEL_CACHE']
os.makedirs(cache_dir, exist_ok=True)
# The bytes the export reads. config.json and tokenizer.json are checked after the export below; this checks the
# weights (and the vocabulary) before anything parses them.
from huggingface_hub import hf_hub_download
for filename, expected_sha in SOURCE_HASHES.items():
path = hf_hub_download(MODEL_NAME, filename, revision=MODEL_REVISION)
actual_sha = hashlib.sha256(open(path, 'rb').read()).hexdigest()
if actual_sha != expected_sha:
print(f'SOURCE HASH MISMATCH for {filename}: expected {expected_sha}, got {actual_sha}', file=sys.stderr)
sys.exit(1)
print(f' verified source {filename}: {actual_sha}')
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, revision=MODEL_REVISION)
original_export = torch.onnx.export
def export_with_dynamo_disabled(*args, **kwargs):
kwargs.setdefault('dynamo', False)
return original_export(*args, **kwargs)
torch.onnx.export = export_with_dynamo_disabled
model = ORTModelForSequenceClassification.from_pretrained(MODEL_NAME, revision=MODEL_REVISION, export=True)
torch.onnx.export = original_export
model.save_pretrained(cache_dir)
tokenizer.save_pretrained(cache_dir)
for filename, expected_sha in EXPECTED_HASHES.items():
filepath = os.path.join(cache_dir, filename)
actual_sha = hashlib.sha256(open(filepath, 'rb').read()).hexdigest()
if actual_sha != expected_sha:
print(f'HASH MISMATCH for {filename}:', file=sys.stderr)
print(f' expected: {expected_sha}', file=sys.stderr)
print(f' actual: {actual_sha}', file=sys.stderr)
sys.exit(1)
print(f' verified {filename}: {actual_sha}')
encoded = tokenizer(['PostHog is the best option for startups.'], ['PostHog'], return_tensors='pt')
probabilities = model(**encoded).logits.softmax(-1)[0].tolist()
labels = {model.config.id2label[i].lower(): p for i, p in enumerate(probabilities)}
assert labels.get('positive', 0) > 0.5, f'Smoke test failed: expected positive > 0.5, got {labels}'
print(f' smoke test passed: positive={labels[\"positive\"]:.4f}')
print(f'Model baked into {cache_dir}')
"
rm -rf /root/.cache/huggingface
# SentencePiece only converts the vocabulary above. The worker reads tokenizer.json, so the image does not ship it.
uv pip uninstall --python /python-runtime/bin/python sentencepiece
python -c "import importlib.util, sys; sys.exit(importlib.util.find_spec('sentencepiece') is not None)"
BAKE_ASPECT_MODEL
# Copy project files. Must stay below the model bakes, which read nothing from the repo; moving it above them
# invalidates those layers on every source-only commit.
COPY manage.py manage.py
COPY common/esbuilder common/esbuilder
COPY common/hogvm common/hogvm/
COPY common/migration_utils common/migration_utils/
COPY common/log-scrubbing/credentials.txt common/log-scrubbing/
COPY posthog posthog/
COPY products/ products/
COPY ee ee/
COPY bin/temporal-django-worker bin/temporal-django-worker
RUN chmod +x bin/temporal-django-worker
# Run as an unprivileged user, like the main PostHog image. The worker only reads /code and the baked models.
RUN groupadd -g 10001 posthog && \
useradd -u 10001 -g posthog -m -d /home/posthog posthog
USER posthog
CMD ["bin/temporal-django-worker"]