Spaces:
Sleeping
Sleeping
Upload 5 files
Browse files- Dockerfile +18 -12
- ag4masses-public.ipynb +473 -0
- alphageometry.py +778 -0
- download.sh +31 -0
- models.py +178 -0
Dockerfile
CHANGED
@@ -1,7 +1,7 @@
|
|
1 |
FROM nvidia/cuda:12.5.1-cudnn-devel-ubuntu20.04
|
2 |
|
3 |
ENV DEBIAN_FRONTEND=noninteractive \
|
4 |
-
|
5 |
|
6 |
# Remove any third-party apt sources to avoid issues with expiring keys.
|
7 |
# Install some basic utilities
|
@@ -51,7 +51,7 @@ RUN mkdir $HOME/.cache $HOME/.config \
|
|
51 |
# Set up the Conda environment
|
52 |
ENV CONDA_AUTO_UPDATE_CONDA=false \
|
53 |
PATH=$HOME/miniconda/bin:$PATH
|
54 |
-
RUN curl -sLo ~/miniconda.sh https://repo.continuum.io/miniconda/Miniconda3-
|
55 |
&& chmod +x ~/miniconda.sh \
|
56 |
&& ~/miniconda.sh -b -p ~/miniconda \
|
57 |
&& rm ~/miniconda.sh \
|
@@ -73,7 +73,7 @@ RUN --mount=target=/root/packages.txt,source=packages.txt \
|
|
73 |
&& rm -rf /var/lib/apt/lists/*
|
74 |
|
75 |
RUN --mount=target=/root/on_startup.sh,source=on_startup.sh,readwrite \
|
76 |
-
|
77 |
|
78 |
RUN mkdir /data && chown user:user /data
|
79 |
|
@@ -92,14 +92,20 @@ COPY --chown=user . $HOME/app
|
|
92 |
|
93 |
RUN chmod +x start_server.sh
|
94 |
|
95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
96 |
|
97 |
ENV PYTHONUNBUFFERED=1 \
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
CMD ["./start_server.sh"]
|
|
|
1 |
FROM nvidia/cuda:12.5.1-cudnn-devel-ubuntu20.04
|
2 |
|
3 |
ENV DEBIAN_FRONTEND=noninteractive \
|
4 |
+
TZ=Asia/Shanghai
|
5 |
|
6 |
# Remove any third-party apt sources to avoid issues with expiring keys.
|
7 |
# Install some basic utilities
|
|
|
51 |
# Set up the Conda environment
|
52 |
ENV CONDA_AUTO_UPDATE_CONDA=false \
|
53 |
PATH=$HOME/miniconda/bin:$PATH
|
54 |
+
RUN curl -sLo ~/miniconda.sh https://repo.continuum.io/miniconda/Miniconda3-py310_4.10.3-Linux-x86_64.sh \
|
55 |
&& chmod +x ~/miniconda.sh \
|
56 |
&& ~/miniconda.sh -b -p ~/miniconda \
|
57 |
&& rm ~/miniconda.sh \
|
|
|
73 |
&& rm -rf /var/lib/apt/lists/*
|
74 |
|
75 |
RUN --mount=target=/root/on_startup.sh,source=on_startup.sh,readwrite \
|
76 |
+
bash /root/on_startup.sh
|
77 |
|
78 |
RUN mkdir /data && chown user:user /data
|
79 |
|
|
|
92 |
|
93 |
RUN chmod +x start_server.sh
|
94 |
|
95 |
+
RUN download.sh
|
96 |
+
|
97 |
+
COPY --chown=user login.html /home/user/miniconda/lib/python3.10/site-packages/jupyter_server/templates/login.html
|
98 |
+
|
99 |
+
COPY --chown=user public.ipynb /data/public.ipynb
|
100 |
+
|
101 |
+
# COPY --chown=user models.py /data/public.ipynb
|
102 |
|
103 |
ENV PYTHONUNBUFFERED=1 \
|
104 |
+
GRADIO_ALLOW_FLAGGING=never \
|
105 |
+
GRADIO_NUM_PORTS=1 \
|
106 |
+
GRADIO_SERVER_NAME=0.0.0.0 \
|
107 |
+
GRADIO_THEME=huggingface \
|
108 |
+
SYSTEM=spaces \
|
109 |
+
SHELL=/bin/bash
|
110 |
+
|
111 |
+
CMD ["./start_server.sh"]
|
ag4masses-public.ipynb
ADDED
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "code",
|
5 |
+
"execution_count": null,
|
6 |
+
"metadata": {
|
7 |
+
"executionInfo": {
|
8 |
+
"elapsed": 611,
|
9 |
+
"status": "ok",
|
10 |
+
"timestamp": 1733595497864,
|
11 |
+
"user": {
|
12 |
+
"displayName": "Tong Peng",
|
13 |
+
"userId": "14680520704856526492"
|
14 |
+
},
|
15 |
+
"user_tz": 300
|
16 |
+
},
|
17 |
+
"id": "-IHoHd-t5sLP",
|
18 |
+
"trusted": true
|
19 |
+
},
|
20 |
+
"outputs": [],
|
21 |
+
"source": [
|
22 |
+
"import sys, os\n",
|
23 |
+
"\n",
|
24 |
+
"AG4MDIR='/home/user/ag4masses'\n",
|
25 |
+
"AGLIB=f'{AG4MDIR}/aglib'\n",
|
26 |
+
"AGDIR=f\"{AGLIB}/alphageometry\"\n",
|
27 |
+
"MELIAD_PATH=f\"{AGDIR}/meliad\"\n",
|
28 |
+
"DATA=f\"{AGLIB}/ag_ckpt_vocab\"\n",
|
29 |
+
"TESTDIR=f\"/data/ag4mtest\""
|
30 |
+
]
|
31 |
+
},
|
32 |
+
{
|
33 |
+
"cell_type": "markdown",
|
34 |
+
"metadata": {
|
35 |
+
"id": "ASgGFu0NYHUH"
|
36 |
+
},
|
37 |
+
"source": [
|
38 |
+
"# Download Files"
|
39 |
+
]
|
40 |
+
},
|
41 |
+
{
|
42 |
+
"cell_type": "code",
|
43 |
+
"execution_count": null,
|
44 |
+
"metadata": {
|
45 |
+
"trusted": true
|
46 |
+
},
|
47 |
+
"outputs": [],
|
48 |
+
"source": [
|
49 |
+
"# Run this cell to refresh code and get the latest versions\n",
|
50 |
+
"# AG4MDIR and MELIAD_PATH are in /kaggle/working and will be saved as outputs of the Notebook\n",
|
51 |
+
"# !rm -fr {AG4MDIR} {MELIAD_PATH}"
|
52 |
+
]
|
53 |
+
},
|
54 |
+
{
|
55 |
+
"cell_type": "code",
|
56 |
+
"execution_count": null,
|
57 |
+
"metadata": {
|
58 |
+
"executionInfo": {
|
59 |
+
"elapsed": 5,
|
60 |
+
"status": "ok",
|
61 |
+
"timestamp": 1733594216384,
|
62 |
+
"user": {
|
63 |
+
"displayName": "Tong Peng",
|
64 |
+
"userId": "14680520704856526492"
|
65 |
+
},
|
66 |
+
"user_tz": 300
|
67 |
+
},
|
68 |
+
"id": "GgR_vO8XX9Vr",
|
69 |
+
"trusted": true
|
70 |
+
},
|
71 |
+
"outputs": [],
|
72 |
+
"source": [
|
73 |
+
"if not os.path.exists(MELIAD_PATH):\n",
|
74 |
+
" !git clone https://github.com/google-research/meliad.git {MELIAD_PATH}\n",
|
75 |
+
"\n",
|
76 |
+
"if not os.path.exists(AG4MDIR):\n",
|
77 |
+
" !git clone https://github.com/tpgh24/ag4masses.git {AG4MDIR}\n",
|
78 |
+
"\n",
|
79 |
+
"# Temporarily modified files, upload into dataset tmpfiles\n",
|
80 |
+
"# !cp /kaggle/input/tmpfiles/numericals.py {AGDIR}\n",
|
81 |
+
"# !cp /kaggle/input/tmpfiles/alphageometry.py {AGDIR}\n",
|
82 |
+
"\n",
|
83 |
+
"if not os.path.exists(TESTDIR):\n",
|
84 |
+
" !mkdir {TESTDIR}"
|
85 |
+
]
|
86 |
+
},
|
87 |
+
{
|
88 |
+
"cell_type": "code",
|
89 |
+
"execution_count": null,
|
90 |
+
"metadata": {
|
91 |
+
"executionInfo": {
|
92 |
+
"elapsed": 40247,
|
93 |
+
"status": "ok",
|
94 |
+
"timestamp": 1733594312243,
|
95 |
+
"user": {
|
96 |
+
"displayName": "Tong Peng",
|
97 |
+
"userId": "14680520704856526492"
|
98 |
+
},
|
99 |
+
"user_tz": 300
|
100 |
+
},
|
101 |
+
"id": "gP4zAZh2MHcv",
|
102 |
+
"outputId": "4796397b-8952-411e-bd33-8fd813865735",
|
103 |
+
"trusted": true
|
104 |
+
},
|
105 |
+
"outputs": [],
|
106 |
+
"source": [
|
107 |
+
"if not os.path.exists(DATA):\n",
|
108 |
+
" # download data: vocabulary, trained model\n",
|
109 |
+
" !mkdir {DATA}\n",
|
110 |
+
"\n",
|
111 |
+
" ### Convoluted process. This does no work, seems due to Google Drive restrictions\n",
|
112 |
+
" # !gdown --folder https://bit.ly/alphageometry/\n",
|
113 |
+
" #\n",
|
114 |
+
" ### First got file links from Google Drive web UI, under Share menu. It will download HTML files with download button. Extract URL from the file.\n",
|
115 |
+
" ### For checkpoint_10999999, because the file is big, there is an additional step asking for confirmation, got the final URL from the 2nd HTML,\n",
|
116 |
+
" ### Link constructed using AI from HTML form.\n",
|
117 |
+
" # !gdown https://drive.google.com/file/d/1mRd6J0UkeWoFUjeVB7BQi5lVNLvPBe31/view?usp=drive_link -O {AGLIB}/ag_ckpt_vocab/geometry.757.vocab\n",
|
118 |
+
" # !gdown https://drive.google.com/file/d/1t-r3KfU8aDbS1UHpdyM3LH21rwSCIXTz/view?usp=drive_link -O {AGLIB}/ag_ckpt_vocab/geometry.757.model\n",
|
119 |
+
" # !gdown https://drive.google.com/file/d/1qXkmmgoJ8oTYJdFV1xw0xGPpQj6SyOYA/view?usp=drive_link -O {AGLIB}/ag_ckpt_vocab/checkpoint_10999999\n",
|
120 |
+
"\n",
|
121 |
+
" !wget -O {DATA}/geometry.757.vocab \"https://drive.usercontent.google.com/uc?id=1mRd6J0UkeWoFUjeVB7BQi5lVNLvPBe31&export=download\"\n",
|
122 |
+
" !wget -O {DATA}/geometry.757.model \"https://drive.usercontent.google.com/uc?id=1t-r3KfU8aDbS1UHpdyM3LH21rwSCIXTz&export=download\"\n",
|
123 |
+
" !wget -O {DATA}/checkpoint_10999999 \"https://drive.usercontent.google.com/download?id=1qXkmmgoJ8oTYJdFV1xw0xGPpQj6SyOYA&export=download&confirm=t&uuid=ae22f4de-cb77-4145-af5f-8cfbb59e867e\"\n",
|
124 |
+
"\n",
|
125 |
+
"!ls -l {DATA}"
|
126 |
+
]
|
127 |
+
},
|
128 |
+
{
|
129 |
+
"cell_type": "markdown",
|
130 |
+
"metadata": {},
|
131 |
+
"source": [
|
132 |
+
"# Setup Env"
|
133 |
+
]
|
134 |
+
},
|
135 |
+
{
|
136 |
+
"cell_type": "code",
|
137 |
+
"execution_count": null,
|
138 |
+
"metadata": {
|
139 |
+
"executionInfo": {
|
140 |
+
"elapsed": 14190,
|
141 |
+
"status": "ok",
|
142 |
+
"timestamp": 1733594230570,
|
143 |
+
"user": {
|
144 |
+
"displayName": "Tong Peng",
|
145 |
+
"userId": "14680520704856526492"
|
146 |
+
},
|
147 |
+
"user_tz": 300
|
148 |
+
},
|
149 |
+
"id": "X8Aj3G0neT6K",
|
150 |
+
"outputId": "9538ceba-8065-44d6-a32f-35127e5f2575",
|
151 |
+
"trusted": true
|
152 |
+
},
|
153 |
+
"outputs": [],
|
154 |
+
"source": [
|
155 |
+
"# Python packages for AlphaGeometry\n",
|
156 |
+
"!pip cache purge\n",
|
157 |
+
"!pip install --upgrade pip\n",
|
158 |
+
"!pip install --upgrade packaging setuptools setuptools_scm wheel \n",
|
159 |
+
"!pip install --require-hashes --no-deps -r {AG4MDIR}/alphageometry/requirements.txt"
|
160 |
+
]
|
161 |
+
},
|
162 |
+
{
|
163 |
+
"cell_type": "code",
|
164 |
+
"execution_count": null,
|
165 |
+
"metadata": {
|
166 |
+
"executionInfo": {
|
167 |
+
"elapsed": 15694,
|
168 |
+
"status": "ok",
|
169 |
+
"timestamp": 1733594246256,
|
170 |
+
"user": {
|
171 |
+
"displayName": "Tong Peng",
|
172 |
+
"userId": "14680520704856526492"
|
173 |
+
},
|
174 |
+
"user_tz": 300
|
175 |
+
},
|
176 |
+
"id": "u9fuBSr2qEwN",
|
177 |
+
"outputId": "97bbce78-8b49-4d3b-a831-d188a4a9e536",
|
178 |
+
"trusted": true
|
179 |
+
},
|
180 |
+
"outputs": [],
|
181 |
+
"source": [
|
182 |
+
"# Python packages for Nvidia gpu.\n",
|
183 |
+
"# The versions of Python packages used by AlphaGeometry seem to only work with Cuda 11, not 12\n",
|
184 |
+
"!pip install -U \"jax==0.4.6\" \"jaxlib[cuda11_cudnn86]==0.4.6\" -f https://storage.googleapis.com/jax-releases/jax_cuda_releases.html\n",
|
185 |
+
"!pip install nvidia-cuda-runtime-cu11\n",
|
186 |
+
"!pip install nvidia-pyindex\n",
|
187 |
+
"# !pip list"
|
188 |
+
]
|
189 |
+
},
|
190 |
+
{
|
191 |
+
"cell_type": "code",
|
192 |
+
"execution_count": null,
|
193 |
+
"metadata": {
|
194 |
+
"trusted": true
|
195 |
+
},
|
196 |
+
"outputs": [],
|
197 |
+
"source": [
|
198 |
+
"# Linux packages for Nvidia gpu.\n",
|
199 |
+
"# The versions of Python packages used by AlphaGeometry seem to only work with Cuda 11, not 12\n",
|
200 |
+
"!apt-get update\n",
|
201 |
+
"!DEBIAN_FRONTEND=noninteractive apt install -y cuda-11-8\n",
|
202 |
+
"# !apt list|grep cuda"
|
203 |
+
]
|
204 |
+
},
|
205 |
+
{
|
206 |
+
"cell_type": "code",
|
207 |
+
"execution_count": null,
|
208 |
+
"metadata": {
|
209 |
+
"id": "fChy49CNhf01",
|
210 |
+
"trusted": true
|
211 |
+
},
|
212 |
+
"outputs": [],
|
213 |
+
"source": [
|
214 |
+
"# Information about Nvidia drivers\n",
|
215 |
+
"!nvcc --version\n",
|
216 |
+
"!nvidia-smi"
|
217 |
+
]
|
218 |
+
},
|
219 |
+
{
|
220 |
+
"cell_type": "markdown",
|
221 |
+
"metadata": {
|
222 |
+
"id": "jUWvch7kYhxt"
|
223 |
+
},
|
224 |
+
"source": [
|
225 |
+
"# Execution"
|
226 |
+
]
|
227 |
+
},
|
228 |
+
{
|
229 |
+
"cell_type": "code",
|
230 |
+
"execution_count": null,
|
231 |
+
"metadata": {
|
232 |
+
"trusted": true
|
233 |
+
},
|
234 |
+
"outputs": [],
|
235 |
+
"source": [
|
236 |
+
"#!! cannot have ' in the script, including in comments\n",
|
237 |
+
"jobScript = '''\n",
|
238 |
+
"# !/bin/bash\n",
|
239 |
+
"set -e\n",
|
240 |
+
"set -x\n",
|
241 |
+
"\n",
|
242 |
+
"# stdout, solution is written here\n",
|
243 |
+
"OUTFILE=$TESTDIR/${PROB}.out\n",
|
244 |
+
"# stderr, a lot of information, error message, log etc.\n",
|
245 |
+
"ERRFILE=$TESTDIR/${PROB}.log\n",
|
246 |
+
"\n",
|
247 |
+
"# stdout and stderr are written to both ERRFILF and console\n",
|
248 |
+
"exec >$ERRFILE 2>&1\n",
|
249 |
+
"\n",
|
250 |
+
"echo PROB=$PROB\n",
|
251 |
+
"echo PROB_FILE=$PROBFILE\n",
|
252 |
+
"echo MODEL=$MODEL\n",
|
253 |
+
"\n",
|
254 |
+
"# Directory where output files go\n",
|
255 |
+
"echo TESTDIR=$TESTDIR\n",
|
256 |
+
"# Directory containing AG4Masses source files\n",
|
257 |
+
"echo AG4MDIR=$AG4MDIR\n",
|
258 |
+
"# Directory containing external libraries including ag_ckpt_vocab and meliad\n",
|
259 |
+
"echo AGLIB=$AGLIB\n",
|
260 |
+
"\n",
|
261 |
+
"AGDIR=$AG4MDIR/alphageometry\n",
|
262 |
+
"export PYTHONPATH=$PYTHONPATH:$AGDIR:$AGLIB\n",
|
263 |
+
"\n",
|
264 |
+
"echo BATCH_SIZE=$BATCH_SIZE\n",
|
265 |
+
"echo BEAM_SIZE=$BEAM_SIZE\n",
|
266 |
+
"echo DEPTH=$DEPTH\n",
|
267 |
+
"echo NWORKERS=$NWORKERS\n",
|
268 |
+
"\n",
|
269 |
+
"echo ERRFILE=$ERRFILE\n",
|
270 |
+
"echo OUTFILE=$OUTFILE\n",
|
271 |
+
"\n",
|
272 |
+
"DATA=$AGLIB/ag_ckpt_vocab\n",
|
273 |
+
"MELIAD_PATH=$AGLIB/meliad\n",
|
274 |
+
"export PYTHONPATH=$PYTHONPATH:$MELIAD_PATH\n",
|
275 |
+
"\n",
|
276 |
+
"DDAR_ARGS=( \\\n",
|
277 |
+
" --defs_file=$AGDIR/defs.txt \\\n",
|
278 |
+
" --rules_file=$AGDIR/rules.txt \\\n",
|
279 |
+
")\n",
|
280 |
+
"\n",
|
281 |
+
"SEARCH_ARGS=(\n",
|
282 |
+
" --beam_size=$BEAM_SIZE\n",
|
283 |
+
" --search_depth=$DEPTH\n",
|
284 |
+
")\n",
|
285 |
+
"\n",
|
286 |
+
"LM_ARGS=(\n",
|
287 |
+
" --ckpt_path=$DATA \\\n",
|
288 |
+
" --vocab_path=$DATA/geometry.757.model \\\n",
|
289 |
+
" --gin_search_paths=$MELIAD_PATH/transformer/configs,$AGDIR \\\n",
|
290 |
+
" --gin_file=base_htrans.gin \\\n",
|
291 |
+
" --gin_file=size/medium_150M.gin \\\n",
|
292 |
+
" --gin_file=options/positions_t5.gin \\\n",
|
293 |
+
" --gin_file=options/lr_cosine_decay.gin \\\n",
|
294 |
+
" --gin_file=options/seq_1024_nocache.gin \\\n",
|
295 |
+
" --gin_file=geometry_150M_generate.gin \\\n",
|
296 |
+
" --gin_param=DecoderOnlyLanguageModelGenerate.output_token_losses=True \\\n",
|
297 |
+
" --gin_param=TransformerTaskConfig.batch_size=$BATCH_SIZE \\\n",
|
298 |
+
" --gin_param=TransformerTaskConfig.sequence_length=128 \\\n",
|
299 |
+
" --gin_param=Trainer.restore_state_variables=False\n",
|
300 |
+
");\n",
|
301 |
+
"\n",
|
302 |
+
"true \"==========================================\"\n",
|
303 |
+
"\n",
|
304 |
+
"python -m alphageometry \\\n",
|
305 |
+
"--alsologtostderr \\\n",
|
306 |
+
"--problems_file=$PROB_FILE \\\n",
|
307 |
+
"--problem_name=$PROB \\\n",
|
308 |
+
"--mode=$MODEL \\\n",
|
309 |
+
"\"${DDAR_ARGS[@]}\" \\\n",
|
310 |
+
"\"${SEARCH_ARGS[@]}\" \\\n",
|
311 |
+
"\"${LM_ARGS[@]}\" \\\n",
|
312 |
+
"--out_file=$OUTFILE \\\n",
|
313 |
+
"--n_workers=$NWORKERS 2>&1\n",
|
314 |
+
"\n",
|
315 |
+
"'''"
|
316 |
+
]
|
317 |
+
},
|
318 |
+
{
|
319 |
+
"cell_type": "code",
|
320 |
+
"execution_count": null,
|
321 |
+
"metadata": {
|
322 |
+
"trusted": true
|
323 |
+
},
|
324 |
+
"outputs": [],
|
325 |
+
"source": [
|
326 |
+
"os.environ[\"TESTDIR\"]=TESTDIR\n",
|
327 |
+
"os.environ[\"AG4MDIR\"]=AG4MDIR\n",
|
328 |
+
"os.environ[\"AGLIB\"]=AGLIB\n",
|
329 |
+
"\n",
|
330 |
+
"# BATCH_SIZE: number of outputs for each LM query\n",
|
331 |
+
"# BEAM_SIZE: size of the breadth-first search queue\n",
|
332 |
+
"# DEPTH: search depth (number of auxilary points to add)\n",
|
333 |
+
"# NWORKERS: number of parallel run worker processes.\n",
|
334 |
+
"# \n",
|
335 |
+
"# Memory usage is affected by BATCH_SIZE, NWORKER and complexity of the problem.\n",
|
336 |
+
"# Larger NWORKER and BATCH_SIZE tends to cause out of memory issue\n",
|
337 |
+
"#\n",
|
338 |
+
"# The results in Google paper can be obtained by setting BATCH_SIZE=32, BEAM_SIZE=512, DEPTH=16\n",
|
339 |
+
"#\n",
|
340 |
+
"# 1/2025: Kaggle free version provides GPU T4x2, 4 virtual CPUs, 29G RAM. Can set \n",
|
341 |
+
"# NWORKERS=2\n",
|
342 |
+
"# CUDA_VISIBLE_DEVICES=0,1\n",
|
343 |
+
"\n",
|
344 |
+
"os.environ[\"BATCH_SIZE\"]=\"16\"\n",
|
345 |
+
"os.environ[\"BEAM_SIZE\"]=\"64\"\n",
|
346 |
+
"os.environ[\"DEPTH\"]=\"8\"\n",
|
347 |
+
"os.environ[\"NWORKERS\"]=\"2\"\n",
|
348 |
+
"\n",
|
349 |
+
"os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"0,1\"\n",
|
350 |
+
"\n",
|
351 |
+
"# test problems can be uploaded into a dataset, e.g. for dataset \"tmpfiles\", \"/kaggle/input/tmpfiles/test-problems.txt\"\n",
|
352 |
+
"os.environ[\"PROB_FILE\"]=f\"{AG4MDIR}/data/ag4m_problems.txt\"\n",
|
353 |
+
"PROB=\"imo-2024-q4\"\n",
|
354 |
+
"os.environ[\"PROB\"]=PROB\n",
|
355 |
+
"# alphageometry|ddar\n",
|
356 |
+
"os.environ[\"MODEL\"]=\"alphageometry\"\n",
|
357 |
+
"\n",
|
358 |
+
"# In an interactive Kaggle session, run the job in background, so we can do other things in the Notebook.\n",
|
359 |
+
"# For long jobs, commit the Notebook and run in Batch mode.\n",
|
360 |
+
"# An interactive session will be terminated after about 20 minutes of idle time.\n",
|
361 |
+
"if os.environ[\"KAGGLE_KERNEL_RUN_TYPE\"]==\"Batch\":\n",
|
362 |
+
" os.system(f\"echo '{jobScript}'|bash\")\n",
|
363 |
+
"else:\n",
|
364 |
+
" os.system(f\"echo '{jobScript}'|bash &\")\n"
|
365 |
+
]
|
366 |
+
},
|
367 |
+
{
|
368 |
+
"cell_type": "code",
|
369 |
+
"execution_count": null,
|
370 |
+
"metadata": {
|
371 |
+
"trusted": true
|
372 |
+
},
|
373 |
+
"outputs": [],
|
374 |
+
"source": [
|
375 |
+
"#!cat /kaggle/input/tmpfiles/test-problems.txt"
|
376 |
+
]
|
377 |
+
},
|
378 |
+
{
|
379 |
+
"cell_type": "code",
|
380 |
+
"execution_count": null,
|
381 |
+
"metadata": {
|
382 |
+
"trusted": true
|
383 |
+
},
|
384 |
+
"outputs": [],
|
385 |
+
"source": [
|
386 |
+
"# In an interactive Kaggle session, run this to see the log file. We can cancel this cell's execution\n",
|
387 |
+
"# to do other things in the Notebook\n",
|
388 |
+
"if os.environ[\"KAGGLE_KERNEL_RUN_TYPE\"] != \"Batch\":\n",
|
389 |
+
" !tail -f {TESTDIR}/{PROB}.log"
|
390 |
+
]
|
391 |
+
},
|
392 |
+
{
|
393 |
+
"cell_type": "code",
|
394 |
+
"execution_count": null,
|
395 |
+
"metadata": {
|
396 |
+
"trusted": true
|
397 |
+
},
|
398 |
+
"outputs": [],
|
399 |
+
"source": [
|
400 |
+
"# Command to kill the background job in an interactive session\n",
|
401 |
+
"# !pkill -P `ps -ef|grep -- '-m alphageometry'|grep -v grep|awk '{printf \"%d,%d\", $2, $3}'`\n",
|
402 |
+
"\n",
|
403 |
+
"# Command to check processes\n",
|
404 |
+
"### |cat to show full commandline\n",
|
405 |
+
"# !ps -eo pid,ppid,pgid,%cpu,cmd |cat\n",
|
406 |
+
"# !ps -ef|cat"
|
407 |
+
]
|
408 |
+
},
|
409 |
+
{
|
410 |
+
"cell_type": "code",
|
411 |
+
"execution_count": null,
|
412 |
+
"metadata": {
|
413 |
+
"trusted": true
|
414 |
+
},
|
415 |
+
"outputs": [],
|
416 |
+
"source": [
|
417 |
+
"# Command to check progress of a running job in an interactive session\n",
|
418 |
+
"# !bash {AG4MDIR}/utils/checkprog.sh {TESTDIR}/{PROB}.log"
|
419 |
+
]
|
420 |
+
},
|
421 |
+
{
|
422 |
+
"cell_type": "code",
|
423 |
+
"execution_count": null,
|
424 |
+
"metadata": {
|
425 |
+
"trusted": true
|
426 |
+
},
|
427 |
+
"outputs": [],
|
428 |
+
"source": [
|
429 |
+
"# In Batch run, after the job completes, list output files\n",
|
430 |
+
"!ls -ltr {TESTDIR}"
|
431 |
+
]
|
432 |
+
}
|
433 |
+
],
|
434 |
+
"metadata": {
|
435 |
+
"accelerator": "GPU",
|
436 |
+
"colab": {
|
437 |
+
"authorship_tag": "ABX9TyOcsgkfOgCk5oTpUiS6zrgo",
|
438 |
+
"collapsed_sections": [
|
439 |
+
"pW2KIijZBAdh"
|
440 |
+
],
|
441 |
+
"gpuType": "T4",
|
442 |
+
"provenance": []
|
443 |
+
},
|
444 |
+
"kaggle": {
|
445 |
+
"accelerator": "nvidiaTeslaT4",
|
446 |
+
"dataSources": [],
|
447 |
+
"dockerImageVersionId": 30823,
|
448 |
+
"isGpuEnabled": true,
|
449 |
+
"isInternetEnabled": true,
|
450 |
+
"language": "python",
|
451 |
+
"sourceType": "notebook"
|
452 |
+
},
|
453 |
+
"kernelspec": {
|
454 |
+
"display_name": "Python 3",
|
455 |
+
"language": "python",
|
456 |
+
"name": "python3"
|
457 |
+
},
|
458 |
+
"language_info": {
|
459 |
+
"codemirror_mode": {
|
460 |
+
"name": "ipython",
|
461 |
+
"version": 3
|
462 |
+
},
|
463 |
+
"file_extension": ".py",
|
464 |
+
"mimetype": "text/x-python",
|
465 |
+
"name": "python",
|
466 |
+
"nbconvert_exporter": "python",
|
467 |
+
"pygments_lexer": "ipython3",
|
468 |
+
"version": "3.10.12"
|
469 |
+
}
|
470 |
+
},
|
471 |
+
"nbformat": 4,
|
472 |
+
"nbformat_minor": 4
|
473 |
+
}
|
alphageometry.py
ADDED
@@ -0,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 DeepMind Technologies Limited
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
# ==============================================================================
|
15 |
+
|
16 |
+
"""Run DD+AR or AlphaGeometry solver.
|
17 |
+
|
18 |
+
Please refer to README.md for detailed instructions.
|
19 |
+
"""
|
20 |
+
|
21 |
+
import time
|
22 |
+
import traceback
|
23 |
+
|
24 |
+
from absl import app
|
25 |
+
from absl import flags
|
26 |
+
from absl import logging
|
27 |
+
import ddar
|
28 |
+
import graph as gh
|
29 |
+
import lm_inference as lm
|
30 |
+
import pretty as pt
|
31 |
+
import problem as pr
|
32 |
+
|
33 |
+
#=============
|
34 |
+
import sys, os, math, re
|
35 |
+
import multiprocessing
|
36 |
+
model = None # global variable used in multi-processing workers
|
37 |
+
|
38 |
+
_GIN_SEARCH_PATHS = flags.DEFINE_list(
|
39 |
+
'gin_search_paths',
|
40 |
+
['third_party/py/meliad/transformer/configs'],
|
41 |
+
'List of paths where the Gin config files are located.',
|
42 |
+
)
|
43 |
+
_GIN_FILE = flags.DEFINE_multi_string(
|
44 |
+
'gin_file', ['base_htrans.gin'], 'List of Gin config files.'
|
45 |
+
)
|
46 |
+
_GIN_PARAM = flags.DEFINE_multi_string(
|
47 |
+
'gin_param', None, 'Newline separated list of Gin parameter bindings.'
|
48 |
+
)
|
49 |
+
|
50 |
+
_PROBLEMS_FILE = flags.DEFINE_string(
|
51 |
+
'problems_file',
|
52 |
+
'imo_ag_30.txt',
|
53 |
+
'text file contains the problem strings. See imo_ag_30.txt for example.',
|
54 |
+
)
|
55 |
+
_PROBLEM_NAME = flags.DEFINE_string(
|
56 |
+
'problem_name',
|
57 |
+
'imo_2000_p1',
|
58 |
+
'name of the problem to solve, must be in the problem_file.',
|
59 |
+
)
|
60 |
+
_MODE = flags.DEFINE_string(
|
61 |
+
'mode', 'ddar', 'either `ddar` (DD+AR) or `alphageometry`')
|
62 |
+
_DEFS_FILE = flags.DEFINE_string(
|
63 |
+
'defs_file',
|
64 |
+
'defs.txt',
|
65 |
+
'definitions of available constructions to state a problem.',
|
66 |
+
)
|
67 |
+
_RULES_FILE = flags.DEFINE_string(
|
68 |
+
'rules_file', 'rules.txt', 'list of deduction rules used by DD.'
|
69 |
+
)
|
70 |
+
_CKPT_PATH = flags.DEFINE_string('ckpt_path', '', 'checkpoint of the LM model.')
|
71 |
+
_VOCAB_PATH = flags.DEFINE_string(
|
72 |
+
'vocab_path', '', 'path to the LM vocab file.'
|
73 |
+
)
|
74 |
+
_OUT_FILE = flags.DEFINE_string(
|
75 |
+
'out_file', '', 'path to the solution output file.'
|
76 |
+
) # pylint: disable=line-too-long
|
77 |
+
_BEAM_SIZE = flags.DEFINE_integer(
|
78 |
+
'beam_size', 1, 'beam size of the proof search.'
|
79 |
+
) # pylint: disable=line-too-long
|
80 |
+
_SEARCH_DEPTH = flags.DEFINE_integer(
|
81 |
+
'search_depth', 1, 'search depth of the proof search.'
|
82 |
+
) # pylint: disable=line-too-long
|
83 |
+
|
84 |
+
#===================================
|
85 |
+
_N_WORKSERS = flags.DEFINE_integer(
|
86 |
+
'n_workers', 1, 'number of workers'
|
87 |
+
)# pylint: disable=line-too-long
|
88 |
+
|
89 |
+
DEFINITIONS = None # contains definitions of construction actions
|
90 |
+
RULES = None # contains rules of deductions
|
91 |
+
|
92 |
+
|
93 |
+
def natural_language_statement(logical_statement: pr.Dependency) -> str:
|
94 |
+
"""Convert logical_statement to natural language.
|
95 |
+
|
96 |
+
Args:
|
97 |
+
logical_statement: pr.Dependency with .name and .args
|
98 |
+
|
99 |
+
Returns:
|
100 |
+
a string of (pseudo) natural language of the predicate for human reader.
|
101 |
+
"""
|
102 |
+
names = [a.name.upper() for a in logical_statement.args]
|
103 |
+
names = [(n[0] + '_' + n[1:]) if len(n) > 1 else n for n in names]
|
104 |
+
return pt.pretty_nl(logical_statement.name, names)
|
105 |
+
|
106 |
+
|
107 |
+
def proof_step_string(
|
108 |
+
proof_step: pr.Dependency, refs: dict[tuple[str, ...], int], last_step: bool
|
109 |
+
) -> str:
|
110 |
+
"""Translate proof to natural language.
|
111 |
+
|
112 |
+
Args:
|
113 |
+
proof_step: pr.Dependency with .name and .args
|
114 |
+
refs: dict(hash: int) to keep track of derived predicates
|
115 |
+
last_step: boolean to keep track whether this is the last step.
|
116 |
+
|
117 |
+
Returns:
|
118 |
+
a string of (pseudo) natural language of the proof step for human reader.
|
119 |
+
"""
|
120 |
+
premises, [conclusion] = proof_step
|
121 |
+
|
122 |
+
premises_nl = ' & '.join(
|
123 |
+
[
|
124 |
+
natural_language_statement(p) + ' [{:02}]'.format(refs[p.hashed()])
|
125 |
+
for p in premises
|
126 |
+
]
|
127 |
+
)
|
128 |
+
|
129 |
+
if not premises:
|
130 |
+
premises_nl = 'similarly'
|
131 |
+
|
132 |
+
refs[conclusion.hashed()] = len(refs)
|
133 |
+
|
134 |
+
conclusion_nl = natural_language_statement(conclusion)
|
135 |
+
if not last_step:
|
136 |
+
conclusion_nl += ' [{:02}]'.format(refs[conclusion.hashed()])
|
137 |
+
|
138 |
+
return f'{premises_nl} \u21d2 {conclusion_nl}'
|
139 |
+
|
140 |
+
|
141 |
+
def write_solution(g: gh.Graph, p: pr.Problem, out_file: str) -> None:
|
142 |
+
"""Output the solution to out_file.
|
143 |
+
|
144 |
+
Args:
|
145 |
+
g: gh.Graph object, containing the proof state.
|
146 |
+
p: pr.Problem object, containing the theorem.
|
147 |
+
out_file: file to write to, empty string to skip writing to file.
|
148 |
+
"""
|
149 |
+
setup, aux, proof_steps, refs = ddar.get_proof_steps(
|
150 |
+
g, p.goal, merge_trivials=False
|
151 |
+
)
|
152 |
+
|
153 |
+
solution = '\n=========================='
|
154 |
+
solution += '\n * From theorem premises:\n'
|
155 |
+
premises_nl = []
|
156 |
+
for premises, [points] in setup:
|
157 |
+
solution += ' '.join([p.name.upper() for p in points]) + ' '
|
158 |
+
if not premises:
|
159 |
+
continue
|
160 |
+
premises_nl += [
|
161 |
+
natural_language_statement(p) + ' [{:02}]'.format(refs[p.hashed()])
|
162 |
+
for p in premises
|
163 |
+
]
|
164 |
+
solution += ': Points\n' + '\n'.join(premises_nl)
|
165 |
+
|
166 |
+
solution += '\n\n * Auxiliary Constructions:\n'
|
167 |
+
aux_premises_nl = []
|
168 |
+
for premises, [points] in aux:
|
169 |
+
solution += ' '.join([p.name.upper() for p in points]) + ' '
|
170 |
+
aux_premises_nl += [
|
171 |
+
natural_language_statement(p) + ' [{:02}]'.format(refs[p.hashed()])
|
172 |
+
for p in premises
|
173 |
+
]
|
174 |
+
solution += ': Points\n' + '\n'.join(aux_premises_nl)
|
175 |
+
|
176 |
+
# some special case where the deduction rule has a well known name.
|
177 |
+
r2name = {
|
178 |
+
'r32': '(SSS)',
|
179 |
+
'r33': '(SAS)',
|
180 |
+
'r34': '(Similar Triangles)',
|
181 |
+
'r35': '(Similar Triangles)',
|
182 |
+
'r36': '(ASA)',
|
183 |
+
'r37': '(ASA)',
|
184 |
+
'r38': '(Similar Triangles)',
|
185 |
+
'r39': '(Similar Triangles)',
|
186 |
+
'r40': '(Congruent Triangles)',
|
187 |
+
'a00': '(Distance chase)',
|
188 |
+
'a01': '(Ratio chase)',
|
189 |
+
'a02': '(Angle chase)',
|
190 |
+
}
|
191 |
+
|
192 |
+
solution += '\n\n * Proof steps:\n'
|
193 |
+
for i, step in enumerate(proof_steps):
|
194 |
+
_, [con] = step
|
195 |
+
nl = proof_step_string(step, refs, last_step=i == len(proof_steps) - 1)
|
196 |
+
rule_name = r2name.get(con.rule_name, '')
|
197 |
+
nl = nl.replace('\u21d2', f'{rule_name}\u21d2 ')
|
198 |
+
solution += '{:03}. '.format(i + 1) + nl + '\n'
|
199 |
+
|
200 |
+
solution += '==========================\n'
|
201 |
+
logging.info(solution)
|
202 |
+
if out_file:
|
203 |
+
with open(out_file, 'w') as f:
|
204 |
+
f.write(solution)
|
205 |
+
logging.info('Solution written to %s.', out_file)
|
206 |
+
|
207 |
+
|
208 |
+
def get_lm(ckpt_init: str, vocab_path: str) -> lm.LanguageModelInference:
|
209 |
+
lm.parse_gin_configuration(
|
210 |
+
_GIN_FILE.value, _GIN_PARAM.value, gin_paths=_GIN_SEARCH_PATHS.value
|
211 |
+
)
|
212 |
+
|
213 |
+
return lm.LanguageModelInference(vocab_path, ckpt_init, mode='beam_search')
|
214 |
+
|
215 |
+
|
216 |
+
def run_ddar(g: gh.Graph, p: pr.Problem, out_file: str) -> bool:
|
217 |
+
"""Run DD+AR.
|
218 |
+
|
219 |
+
Args:
|
220 |
+
g: gh.Graph object, containing the proof state.
|
221 |
+
p: pr.Problem object, containing the problem statement.
|
222 |
+
out_file: path to output file if solution is found.
|
223 |
+
|
224 |
+
Returns:
|
225 |
+
Boolean, whether DD+AR finishes successfully.
|
226 |
+
"""
|
227 |
+
ddar.solve(g, RULES, p, max_level=1000)
|
228 |
+
|
229 |
+
goal_args = g.names2nodes(p.goal.args)
|
230 |
+
if not g.check(p.goal.name, goal_args):
|
231 |
+
logging.info('DD+AR failed to solve the problem.')
|
232 |
+
return False
|
233 |
+
|
234 |
+
write_solution(g, p, out_file)
|
235 |
+
|
236 |
+
gh.nm.draw(
|
237 |
+
g.type2nodes[gh.Point],
|
238 |
+
g.type2nodes[gh.Line],
|
239 |
+
g.type2nodes[gh.Circle],
|
240 |
+
g.type2nodes[gh.Segment])
|
241 |
+
return True
|
242 |
+
|
243 |
+
|
244 |
+
def translate_constrained_to_constructive(
|
245 |
+
point: str, name: str, args: list[str]
|
246 |
+
) -> tuple[str, list[str]]:
|
247 |
+
"""Translate a predicate from constraint-based to construction-based.
|
248 |
+
|
249 |
+
Args:
|
250 |
+
point: str: name of the new point
|
251 |
+
name: str: name of the predicate, e.g., perp, para, etc.
|
252 |
+
args: list[str]: list of predicate args.
|
253 |
+
|
254 |
+
Returns:
|
255 |
+
(name, args): translated to constructive predicate.
|
256 |
+
"""
|
257 |
+
if name in ['T', 'perp']:
|
258 |
+
a, b, c, d = args
|
259 |
+
if point in [c, d]:
|
260 |
+
a, b, c, d = c, d, a, b
|
261 |
+
if point == b:
|
262 |
+
a, b = b, a
|
263 |
+
if point == d:
|
264 |
+
c, d = d, c
|
265 |
+
if a == c and a == point:
|
266 |
+
return 'on_dia', [a, b, d]
|
267 |
+
return 'on_tline', [a, b, c, d]
|
268 |
+
|
269 |
+
elif name in ['P', 'para']:
|
270 |
+
a, b, c, d = args
|
271 |
+
if point in [c, d]:
|
272 |
+
a, b, c, d = c, d, a, b
|
273 |
+
if point == b:
|
274 |
+
a, b = b, a
|
275 |
+
return 'on_pline', [a, b, c, d]
|
276 |
+
|
277 |
+
elif name in ['D', 'cong']:
|
278 |
+
a, b, c, d = args
|
279 |
+
if point in [c, d]:
|
280 |
+
a, b, c, d = c, d, a, b
|
281 |
+
if point == b:
|
282 |
+
a, b = b, a
|
283 |
+
if point == d:
|
284 |
+
c, d = d, c
|
285 |
+
if a == c and a == point:
|
286 |
+
return 'on_bline', [a, b, d]
|
287 |
+
if b in [c, d]:
|
288 |
+
if b == d:
|
289 |
+
c, d = d, c # pylint: disable=unused-variable
|
290 |
+
return 'on_circle', [a, b, d]
|
291 |
+
return 'eqdistance', [a, b, c, d]
|
292 |
+
|
293 |
+
elif name in ['C', 'coll']:
|
294 |
+
a, b, c = args
|
295 |
+
if point == b:
|
296 |
+
a, b = b, a
|
297 |
+
if point == c:
|
298 |
+
a, b, c = c, a, b
|
299 |
+
return 'on_line', [a, b, c]
|
300 |
+
|
301 |
+
elif name in ['^', 'eqangle']:
|
302 |
+
a, b, c, d, e, f = args
|
303 |
+
|
304 |
+
if point in [d, e, f]:
|
305 |
+
a, b, c, d, e, f = d, e, f, a, b, c
|
306 |
+
|
307 |
+
x, b, y, c, d = b, c, e, d, f
|
308 |
+
if point == b:
|
309 |
+
a, b, c, d = b, a, d, c
|
310 |
+
|
311 |
+
if point == d and x == y: # x p x b = x c x p
|
312 |
+
return 'angle_bisector', [point, b, x, c]
|
313 |
+
|
314 |
+
if point == x:
|
315 |
+
return 'eqangle3', [x, a, b, y, c, d]
|
316 |
+
|
317 |
+
return 'on_aline', [a, x, b, c, y, d]
|
318 |
+
|
319 |
+
elif name in ['cyclic', 'O']:
|
320 |
+
a, b, c = [x for x in args if x != point]
|
321 |
+
return 'on_circum', [point, a, b, c]
|
322 |
+
|
323 |
+
return name, args
|
324 |
+
|
325 |
+
|
326 |
+
def check_valid_args(name: str, args: list[str]) -> bool:
|
327 |
+
"""Check whether a predicate is grammarically correct.
|
328 |
+
|
329 |
+
Args:
|
330 |
+
name: str: name of the predicate
|
331 |
+
args: list[str]: args of the predicate
|
332 |
+
|
333 |
+
Returns:
|
334 |
+
bool: whether the predicate arg count is valid.
|
335 |
+
"""
|
336 |
+
if name == 'perp':
|
337 |
+
if len(args) != 4:
|
338 |
+
return False
|
339 |
+
a, b, c, d = args
|
340 |
+
if len({a, b}) < 2:
|
341 |
+
return False
|
342 |
+
if len({c, d}) < 2:
|
343 |
+
return False
|
344 |
+
elif name == 'para':
|
345 |
+
if len(args) != 4:
|
346 |
+
return False
|
347 |
+
a, b, c, d = args
|
348 |
+
if len({a, b, c, d}) < 4:
|
349 |
+
return False
|
350 |
+
elif name == 'cong':
|
351 |
+
if len(args) != 4:
|
352 |
+
return False
|
353 |
+
a, b, c, d = args
|
354 |
+
if len({a, b}) < 2:
|
355 |
+
return False
|
356 |
+
if len({c, d}) < 2:
|
357 |
+
return False
|
358 |
+
elif name == 'coll':
|
359 |
+
if len(args) != 3:
|
360 |
+
return False
|
361 |
+
a, b, c = args
|
362 |
+
if len({a, b, c}) < 3:
|
363 |
+
return False
|
364 |
+
elif name == 'cyclic':
|
365 |
+
if len(args) != 4:
|
366 |
+
return False
|
367 |
+
a, b, c, d = args
|
368 |
+
if len({a, b, c, d}) < 4:
|
369 |
+
return False
|
370 |
+
elif name == 'eqangle':
|
371 |
+
if len(args) != 8:
|
372 |
+
return False
|
373 |
+
a, b, c, d, e, f, g, h = args
|
374 |
+
if len({a, b, c, d}) < 3:
|
375 |
+
return False
|
376 |
+
if len({e, f, g, h}) < 3:
|
377 |
+
return False
|
378 |
+
return True
|
379 |
+
|
380 |
+
|
381 |
+
def try_translate_constrained_to_construct(string: str, g: gh.Graph) -> str:
|
382 |
+
"""Whether a string of aux construction can be constructed.
|
383 |
+
|
384 |
+
Args:
|
385 |
+
string: str: the string describing aux construction.
|
386 |
+
g: gh.Graph: the current proof state.
|
387 |
+
|
388 |
+
Returns:
|
389 |
+
str: whether this construction is valid. If not, starts with "ERROR:".
|
390 |
+
"""
|
391 |
+
if string[-1] != ';':
|
392 |
+
return 'ERROR: must end with ;'
|
393 |
+
|
394 |
+
logging.info(f'PID={os.getpid()}: !! try_translate_constrained_to_construct: string=%s', string)
|
395 |
+
|
396 |
+
# sometimes the LM may return ill-formed result with multiple colons.
|
397 |
+
# example:
|
398 |
+
#
|
399 |
+
# napoleon2
|
400 |
+
# a1 a2 a3 = triangle; c3 = s_angle a1 a2 c3 30, s_angle a2 a1 c3 150; c1 = s_angle a2 a3 c1 30, s_angle a3 a2 c1 150; c2 = s_angle a3 a1 c2 30, s_angle a1 a3 c2 150 ? cong c1 c2 c1 c3
|
401 |
+
#
|
402 |
+
# in the process,
|
403 |
+
# I0210 17:58:01.513668 140016515833856 alphageometry.py:550] Decoding from {S} a : ; b : ; c : ; d : ^ a d a b 5. pi / 6. 00 ^ b d b a 1. pi / 6. 01 ; e : ^ b e b c 5. pi / 6. 02 ^ c e c b 1. pi / 6. 03 ; f : ^ a f a c 1. pi / 6. 04 ^ c f c a 5. pi / 6. 05 ? D e f e d {F1} x00 g : C a b g 06 D a g b g 07 ; x00 h : C c b h 08 D c h b h 09 ; x00
|
404 |
+
# I0210 18:01:38.182158 140016515833856 alphageometry.py:384] !! try_translate_constrained_to_construct: string=i : C a c i 10 D a i c i 11 ? V d f {F1} x00 j : D g j h j 12 D h j i j 13 ;
|
405 |
+
|
406 |
+
#XXX
|
407 |
+
# str_parts = string.split(' : ')
|
408 |
+
# if len(str_parts) != 2:
|
409 |
+
# return f'ERROR: string has multiple colons: |{string}|'
|
410 |
+
mch = re.match('(.*?)( \? | \. \{)', string)
|
411 |
+
if mch :
|
412 |
+
strFixed = mch.group(1) + ';'
|
413 |
+
logging.info(f'ID={os.getpid()}: Bad LM output: {string}. Changed to {strFixed}')
|
414 |
+
string = strFixed
|
415 |
+
|
416 |
+
# sometimes the constraint in string is empty:
|
417 |
+
# 0407 17:11:35.470240 126383800963072 alphageometry.py:394] !! try_translate_constrained_to_construct: string=j : ;
|
418 |
+
hdprem = string.split(' : ')
|
419 |
+
if len(hdprem) !=2 or hdprem[1].strip()==';' :
|
420 |
+
logging.info(f'ID={os.getpid()}: Bad LM output: {string}. ERROR')
|
421 |
+
return f'ERROR: Bad LM output: {string}'
|
422 |
+
head, prem_str = hdprem
|
423 |
+
point = head.strip()
|
424 |
+
|
425 |
+
if len(point) != 1 or point == ' ':
|
426 |
+
return f'ERROR: invalid point name {point}'
|
427 |
+
|
428 |
+
existing_points = [p.name for p in g.all_points()]
|
429 |
+
if point in existing_points:
|
430 |
+
return f'ERROR: point {point} already exists.'
|
431 |
+
|
432 |
+
prem_toks = prem_str.split()[:-1] # remove the EOS ' ;'
|
433 |
+
prems = [[]]
|
434 |
+
|
435 |
+
for i, tok in enumerate(prem_toks):
|
436 |
+
if tok.isdigit():
|
437 |
+
if i < len(prem_toks) - 1:
|
438 |
+
prems.append([])
|
439 |
+
else:
|
440 |
+
prems[-1].append(tok)
|
441 |
+
|
442 |
+
if len(prems) > 2:
|
443 |
+
return 'ERROR: there cannot be more than two predicates.'
|
444 |
+
|
445 |
+
clause_txt = point + ' = '
|
446 |
+
constructions = []
|
447 |
+
|
448 |
+
for prem in prems:
|
449 |
+
name, *args = prem
|
450 |
+
|
451 |
+
if point not in args:
|
452 |
+
return f'ERROR: {point} not found in predicate args.'
|
453 |
+
|
454 |
+
if not check_valid_args(pt.map_symbol(name), args):
|
455 |
+
return 'ERROR: Invalid predicate ' + name + ' ' + ' '.join(args)
|
456 |
+
|
457 |
+
for a in args:
|
458 |
+
if a != point and a not in existing_points:
|
459 |
+
return f'ERROR: point {a} does not exist.'
|
460 |
+
|
461 |
+
try:
|
462 |
+
name, args = translate_constrained_to_constructive(point, name, args)
|
463 |
+
except: # pylint: disable=bare-except
|
464 |
+
return 'ERROR: Invalid predicate ' + name + ' ' + ' '.join(args)
|
465 |
+
|
466 |
+
if name == 'on_aline':
|
467 |
+
if args.count(point) > 1:
|
468 |
+
return f'ERROR: on_aline involves twice {point}'
|
469 |
+
|
470 |
+
constructions += [name + ' ' + ' '.join(args)]
|
471 |
+
|
472 |
+
clause_txt += ', '.join(constructions)
|
473 |
+
clause = pr.Clause.from_txt(clause_txt)
|
474 |
+
|
475 |
+
try:
|
476 |
+
g.copy().add_clause(clause, 0, DEFINITIONS)
|
477 |
+
except: # pylint: disable=bare-except
|
478 |
+
return 'ERROR: ' + traceback.format_exc()
|
479 |
+
|
480 |
+
return clause_txt
|
481 |
+
|
482 |
+
|
483 |
+
def insert_aux_to_premise(pstring: str, auxstring: str) -> str:
|
484 |
+
"""Insert auxiliary constructs from proof to premise.
|
485 |
+
|
486 |
+
Args:
|
487 |
+
pstring: str: describing the problem to solve.
|
488 |
+
auxstring: str: describing the auxiliar construction.
|
489 |
+
|
490 |
+
Returns:
|
491 |
+
str: new pstring with auxstring inserted before the conclusion.
|
492 |
+
"""
|
493 |
+
setup, goal = pstring.split(' ? ')
|
494 |
+
return setup + '; ' + auxstring + ' ? ' + goal
|
495 |
+
|
496 |
+
|
497 |
+
class BeamQueue:
|
498 |
+
"""Keep only the top k objects according to their values."""
|
499 |
+
|
500 |
+
def __init__(self, max_size: int = 512):
|
501 |
+
self.queue = []
|
502 |
+
self.max_size = max_size
|
503 |
+
|
504 |
+
def add(self, node: object, val: float) -> None:
|
505 |
+
"""Add a new node to this queue."""
|
506 |
+
|
507 |
+
if len(self.queue) < self.max_size:
|
508 |
+
self.queue.append((val, node))
|
509 |
+
return
|
510 |
+
|
511 |
+
# Find the minimum node:
|
512 |
+
min_idx, (min_val, _) = min(enumerate(self.queue), key=lambda x: x[1])
|
513 |
+
|
514 |
+
# replace it if the new node has higher value.
|
515 |
+
if val > min_val:
|
516 |
+
self.queue[min_idx] = (val, node)
|
517 |
+
|
518 |
+
def __iter__(self):
|
519 |
+
for val, node in self.queue:
|
520 |
+
yield val, node
|
521 |
+
|
522 |
+
def __len__(self) -> int:
|
523 |
+
return len(self.queue)
|
524 |
+
|
525 |
+
def bqsearch_init(worker_id):
|
526 |
+
# When using spawn or forkserver start method for multiprocessing.Pool, need to re-initialize
|
527 |
+
flags.FLAGS(sys.argv)
|
528 |
+
logging.use_absl_handler()
|
529 |
+
logging.set_verbosity(logging.INFO)
|
530 |
+
sys.setrecursionlimit(10000)
|
531 |
+
|
532 |
+
# Global variables initialized in main(). Need to re-initialize
|
533 |
+
#
|
534 |
+
# definitions of terms used in our domain-specific language.
|
535 |
+
global DEFINITIONS, RULES
|
536 |
+
DEFINITIONS = pr.Definition.from_txt_file(_DEFS_FILE.value, to_dict=True)
|
537 |
+
# load inference rules used in DD.
|
538 |
+
RULES = pr.Theorem.from_txt_file(_RULES_FILE.value, to_dict=True)
|
539 |
+
|
540 |
+
wkrpid = os.getpid()
|
541 |
+
logging.info('Worker %d initializing. PID=%d', worker_id, wkrpid)
|
542 |
+
|
543 |
+
if 'CUDA_VISIBLE_DEVICES' in os.environ and os.environ['CUDA_VISIBLE_DEVICES'].strip():
|
544 |
+
os.environ['CUDA_VISIBLE_DEVICES']=f"{worker_id}"
|
545 |
+
logging.info('Worker %d: CUDA_VISIBLE_DEVICES=%s', worker_id, os.environ['CUDA_VISIBLE_DEVICES'])
|
546 |
+
|
547 |
+
global model
|
548 |
+
model = get_lm(_CKPT_PATH.value, _VOCAB_PATH.value)
|
549 |
+
return wkrpid
|
550 |
+
|
551 |
+
def bqsearch(i_nd, srch_inputs, out_file) -> tuple[int, bool, list]: # ( iNode, solved, [ (node, score) ] )
|
552 |
+
pid = os.getpid()
|
553 |
+
logging.info(f'Worker PID={pid} called for beam search node {i_nd}')
|
554 |
+
|
555 |
+
prev_score, (g, string, pstring) = srch_inputs
|
556 |
+
logging.info(f'Worker PID={pid}: Beam-searching and Decoding from {string}')
|
557 |
+
outputs = model.beam_decode(string, eos_tokens=[';'])
|
558 |
+
|
559 |
+
# translate lm output to the constructive language.
|
560 |
+
# so that we can update the graph representing proof states:
|
561 |
+
translations = [
|
562 |
+
try_translate_constrained_to_construct(o, g)
|
563 |
+
for o in outputs['seqs_str']
|
564 |
+
]
|
565 |
+
|
566 |
+
# couple the lm outputs with its translations
|
567 |
+
candidates = zip(outputs['seqs_str'], translations, outputs['scores'])
|
568 |
+
|
569 |
+
# bring the highest scoring candidate first
|
570 |
+
candidates = reversed(list(candidates))
|
571 |
+
|
572 |
+
ret = []
|
573 |
+
for lm_out, translation, score in candidates:
|
574 |
+
logging.info(f'Worker PID={pid}: LM output (score={score}): "{lm_out}"')
|
575 |
+
logging.info(f'Worker PID={pid}: Translation: "{translation}"')
|
576 |
+
|
577 |
+
if translation.startswith('ERROR:'):
|
578 |
+
# the construction is invalid.
|
579 |
+
continue
|
580 |
+
|
581 |
+
# Update the constructive statement of the problem with the aux point:
|
582 |
+
candidate_pstring = insert_aux_to_premise(pstring, translation)
|
583 |
+
|
584 |
+
#XXX
|
585 |
+
logging.info(f'Worker PID={pid}: string=|{string}| lm_out=|{lm_out}|')
|
586 |
+
logging.info(f'Worker PID={pid}: Solving: "{candidate_pstring}"')
|
587 |
+
p_new = pr.Problem.from_txt(candidate_pstring)
|
588 |
+
|
589 |
+
# This is the new proof state graph representation:
|
590 |
+
g_new, _ = gh.Graph.build_problem(p_new, DEFINITIONS)
|
591 |
+
|
592 |
+
try:
|
593 |
+
if run_ddar(g_new, p_new, out_file):
|
594 |
+
logging.info(f'Worker PID={pid}: Solved.')
|
595 |
+
return (i_nd, True, None)
|
596 |
+
except Exception as e:
|
597 |
+
logging.info(f'Worker PID={pid}: Error in run_ddar: {e}')
|
598 |
+
|
599 |
+
# Add the candidate to the beam queue.
|
600 |
+
ret.append( [
|
601 |
+
# The string for the new node is old_string + lm output +
|
602 |
+
# the special token asking for a new auxiliary point ' x00':
|
603 |
+
# node
|
604 |
+
(g_new, string + ' ' + lm_out + ' x00', candidate_pstring),
|
605 |
+
# the score of each node is sum of score of all nodes
|
606 |
+
# on the path to itself. For beam search, there is no need to
|
607 |
+
# normalize according to path length because all nodes in beam
|
608 |
+
# is of the same path length.
|
609 |
+
# val
|
610 |
+
prev_score + score ]
|
611 |
+
)
|
612 |
+
|
613 |
+
logging.info(f'Worker PID={pid} beam search node {i_nd}: returning')
|
614 |
+
return (i_nd, False, ret)
|
615 |
+
|
616 |
+
def run_alphageometry(
|
617 |
+
#XX model: lm.LanguageModelInference,
|
618 |
+
p: pr.Problem,
|
619 |
+
search_depth: int,
|
620 |
+
beam_size: int,
|
621 |
+
out_file: str,
|
622 |
+
) -> bool:
|
623 |
+
"""Simplified code to run AlphaGeometry proof search.
|
624 |
+
|
625 |
+
We removed all optimizations that are infrastructure-dependent, e.g.
|
626 |
+
parallelized model inference on multi GPUs,
|
627 |
+
parallelized DD+AR on multiple CPUs,
|
628 |
+
parallel execution of LM and DD+AR,
|
629 |
+
shared pool of CPU workers across different problems, etc.
|
630 |
+
|
631 |
+
Many other speed optimizations and abstractions are also removed to
|
632 |
+
better present the core structure of the proof search.
|
633 |
+
|
634 |
+
Args:
|
635 |
+
model: Interface with inference-related endpoints to JAX's model.
|
636 |
+
p: pr.Problem object describing the problem to solve.
|
637 |
+
search_depth: max proof search depth.
|
638 |
+
beam_size: beam size of the proof search.
|
639 |
+
out_file: path to output file if solution is found.
|
640 |
+
|
641 |
+
Returns:
|
642 |
+
boolean of whether this is solved.
|
643 |
+
"""
|
644 |
+
# translate the problem to a string of grammar that the LM is trained on.
|
645 |
+
string = p.setup_str_from_problem(DEFINITIONS)
|
646 |
+
# special tokens prompting the LM to generate auxiliary points.
|
647 |
+
string += ' {F1} x00'
|
648 |
+
# the graph to represent the proof state.
|
649 |
+
g, _ = gh.Graph.build_problem(p, DEFINITIONS)
|
650 |
+
|
651 |
+
# First we run the symbolic engine DD+AR:
|
652 |
+
if run_ddar(g, p, out_file):
|
653 |
+
return True
|
654 |
+
|
655 |
+
# ?? when pickling graph for some problems, the default recursion limit 1000 is not enough,
|
656 |
+
# got 'maximum recursion depth exceeded while pickling an object' error
|
657 |
+
sys.setrecursionlimit(10000)
|
658 |
+
|
659 |
+
# beam search for the proof
|
660 |
+
# each node in the search tree is a 3-tuple:
|
661 |
+
# (<graph representation of proof state>,
|
662 |
+
# <string for LM to decode from>,
|
663 |
+
# <original problem string>)
|
664 |
+
beam_queue = BeamQueue(max_size=beam_size)
|
665 |
+
# originally the beam search tree starts with a single node (a 3-tuple):
|
666 |
+
beam_queue.add(
|
667 |
+
node=(g, string, p.txt()), val=0.0 # value of the root node is simply 0.
|
668 |
+
)
|
669 |
+
|
670 |
+
pool = None
|
671 |
+
if _N_WORKSERS.value == 1:
|
672 |
+
bqsearch_init(0)
|
673 |
+
else:
|
674 |
+
# Default is 'fork' on Linux, does not work with CUDA. Need to use 'spawn' or 'forkserver'
|
675 |
+
multiprocessing.set_start_method('spawn')
|
676 |
+
pool = multiprocessing.Pool(_N_WORKSERS.value)
|
677 |
+
|
678 |
+
logging.info("Initializing workers")
|
679 |
+
wkrpids = pool.map(bqsearch_init, range(_N_WORKSERS.value))
|
680 |
+
logging.info("Worker PIDs: " + str(wkrpids))
|
681 |
+
|
682 |
+
for depth in range(search_depth):
|
683 |
+
logging.info(
|
684 |
+
'Depth %s. There are %i nodes to expand:', depth, len(beam_queue)
|
685 |
+
)
|
686 |
+
for _, (_, string, _) in beam_queue:
|
687 |
+
logging.info(string)
|
688 |
+
|
689 |
+
new_queue = BeamQueue(max_size=beam_size) # to replace beam_queue.
|
690 |
+
if _N_WORKSERS.value==1:
|
691 |
+
for i, srch_inputs in enumerate(beam_queue):
|
692 |
+
_, solved, res = bqsearch(i, srch_inputs, out_file)
|
693 |
+
if solved:
|
694 |
+
return True
|
695 |
+
for node, val in res:
|
696 |
+
# Add the candidate to the beam queue.
|
697 |
+
new_queue.add(node, val)
|
698 |
+
# Note that the queue only maintain at most beam_size nodes
|
699 |
+
# so this new node might possibly be dropped depending on its value.
|
700 |
+
else:
|
701 |
+
jobs = [pool.apply_async(bqsearch, (i, srch_inputs, out_file)) for i, srch_inputs in enumerate(beam_queue)]
|
702 |
+
|
703 |
+
n_done = 0
|
704 |
+
while n_done < len(beam_queue):
|
705 |
+
for i, jobres in enumerate(jobs):
|
706 |
+
if jobres and jobres.ready():
|
707 |
+
n_done += 1
|
708 |
+
jobs[i] = None
|
709 |
+
_, solved, res = jobres.get()
|
710 |
+
if solved:
|
711 |
+
# Clean up resources
|
712 |
+
pool.terminate()
|
713 |
+
pool.join()
|
714 |
+
return True
|
715 |
+
for node, val in res:
|
716 |
+
# Add the candidate to the beam queue.
|
717 |
+
new_queue.add(node, val)
|
718 |
+
# Note that the queue only maintain at most beam_size nodes
|
719 |
+
# so this new node might possibly be dropped depending on its value.
|
720 |
+
time.sleep(1) # Adjust wait time as needed
|
721 |
+
|
722 |
+
# replace the old queue with new queue before the new proof search depth.
|
723 |
+
beam_queue = new_queue
|
724 |
+
|
725 |
+
# Clean up resources
|
726 |
+
if pool:
|
727 |
+
pool.terminate()
|
728 |
+
pool.join()
|
729 |
+
return False
|
730 |
+
|
731 |
+
def main(_):
|
732 |
+
global DEFINITIONS
|
733 |
+
global RULES
|
734 |
+
|
735 |
+
# definitions of terms used in our domain-specific language.
|
736 |
+
DEFINITIONS = pr.Definition.from_txt_file(_DEFS_FILE.value, to_dict=True)
|
737 |
+
# load inference rules used in DD.
|
738 |
+
RULES = pr.Theorem.from_txt_file(_RULES_FILE.value, to_dict=True)
|
739 |
+
|
740 |
+
# when using the language model,
|
741 |
+
# point names will be renamed to alphabetical a, b, c, d, e, ...
|
742 |
+
# instead of staying with their original names,
|
743 |
+
# in order to match the synthetic training data generation.
|
744 |
+
need_rename = _MODE.value != 'ddar'
|
745 |
+
|
746 |
+
# load problems from the problems_file,
|
747 |
+
problems = pr.Problem.from_txt_file(
|
748 |
+
_PROBLEMS_FILE.value, to_dict=True, translate=need_rename
|
749 |
+
)
|
750 |
+
|
751 |
+
if _PROBLEM_NAME.value not in problems:
|
752 |
+
raise ValueError(
|
753 |
+
f'Problem name `{_PROBLEM_NAME.value}` '
|
754 |
+
+ f'not found in `{_PROBLEMS_FILE.value}`'
|
755 |
+
)
|
756 |
+
|
757 |
+
this_problem = problems[_PROBLEM_NAME.value]
|
758 |
+
|
759 |
+
if _MODE.value == 'ddar':
|
760 |
+
g, _ = gh.Graph.build_problem(this_problem, DEFINITIONS)
|
761 |
+
run_ddar(g, this_problem, _OUT_FILE.value)
|
762 |
+
|
763 |
+
elif _MODE.value == 'alphageometry':
|
764 |
+
#XX model = get_lm(_CKPT_PATH.value, _VOCAB_PATH.value)
|
765 |
+
run_alphageometry(
|
766 |
+
#XX model,
|
767 |
+
this_problem,
|
768 |
+
_SEARCH_DEPTH.value,
|
769 |
+
_BEAM_SIZE.value,
|
770 |
+
_OUT_FILE.value,
|
771 |
+
)
|
772 |
+
|
773 |
+
else:
|
774 |
+
raise ValueError(f'Unknown FLAGS.mode: {_MODE.value}')
|
775 |
+
|
776 |
+
|
777 |
+
if __name__ == '__main__':
|
778 |
+
app.run(main)
|
download.sh
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
HOME=/home/user
|
2 |
+
AG4MDIR=$HOME/ag4masses
|
3 |
+
# Directory containing external libraries including ag_ckpt_vocab and meliad
|
4 |
+
AGLIB=$HOME/aglib
|
5 |
+
|
6 |
+
AGDIR=$AG4MDIR/alphageometry
|
7 |
+
|
8 |
+
DATA=$AGLIB/ag_ckpt_vocab
|
9 |
+
MELIAD_PATH=$AGLIB/meliad
|
10 |
+
|
11 |
+
cd /home/user
|
12 |
+
mkdir aglib
|
13 |
+
cd aglib
|
14 |
+
git clone https://github.com/tpgh24/ag4masses.git
|
15 |
+
cd alphageometry
|
16 |
+
git clone https://github.com/google-research/meliad.git
|
17 |
+
|
18 |
+
cd ..
|
19 |
+
# mkdir aglib
|
20 |
+
gdown --folder https://bit.ly/alphageometry
|
21 |
+
export DATA=ag_ckpt_vocab
|
22 |
+
|
23 |
+
pip cache purge
|
24 |
+
pip install --upgrade pip
|
25 |
+
pip install --upgrade packaging setuptools setuptools_scm wheel
|
26 |
+
pip install --require-hashes --no-deps -r /home/user/ag4masses/alphageometry/requirements.txt
|
27 |
+
|
28 |
+
# some patch for cpu
|
29 |
+
cp models.py /home/user/ag4masses/alphageometry/models.py
|
30 |
+
cp alphageometry.py /home/user/ag4masses/alphageometry/alphageometry.py
|
31 |
+
cp ag4masses-public.ipynb /data/ag4masses-public.ipynb
|
models.py
ADDED
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2023 DeepMind Technologies Limited
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
# ==============================================================================
|
15 |
+
|
16 |
+
"""Transformer language model generate mode."""
|
17 |
+
|
18 |
+
from typing import Any, Tuple
|
19 |
+
import beam_search
|
20 |
+
import decoder_stack
|
21 |
+
import gin
|
22 |
+
import jax
|
23 |
+
import jax.numpy as jnp
|
24 |
+
from transformer import models
|
25 |
+
|
26 |
+
|
27 |
+
@gin.configurable
|
28 |
+
class DecoderOnlyLanguageModelGenerate(models.DecoderOnlyLanguageModel):
|
29 |
+
"""Decoder only language modeling in inference mode."""
|
30 |
+
|
31 |
+
decoder_factory = decoder_stack.DecoderStackGenerate
|
32 |
+
|
33 |
+
num_heads: int = gin.REQUIRED
|
34 |
+
head_size: int = gin.REQUIRED
|
35 |
+
|
36 |
+
def get_fake_input(self) -> dict[str, Any]:
|
37 |
+
fake_input_dict = super().get_fake_input()
|
38 |
+
b = self.task_config.batch_size
|
39 |
+
n = self.num_heads
|
40 |
+
h = self.head_size
|
41 |
+
fake_input_dict.update({
|
42 |
+
'dstate': tuple(
|
43 |
+
[{
|
44 |
+
'current_index': jnp.array([0] * b, dtype=jnp.int32),
|
45 |
+
'keys': jnp.zeros((b, 2048, n, h), dtype=jnp.float32),
|
46 |
+
'values': jnp.zeros((b, 2048, n, h), dtype=jnp.float32),
|
47 |
+
'recurrent_kvq': None,
|
48 |
+
'relative_position_bias': jnp.zeros(
|
49 |
+
(b, n, 1, 1024), dtype=jnp.float32
|
50 |
+
),
|
51 |
+
}]
|
52 |
+
* 12
|
53 |
+
),
|
54 |
+
'eos': jnp.zeros([1024], dtype=jnp.float32),
|
55 |
+
'mask': jnp.ones([1024], dtype=jnp.float32),
|
56 |
+
'length': 1,
|
57 |
+
'temperature': 1.0,
|
58 |
+
})
|
59 |
+
return fake_input_dict
|
60 |
+
|
61 |
+
def __call__(self, inputs: ...) -> tuple[Any, dict[str, Any]]:
|
62 |
+
# Make sure this code is not used on untested cases.
|
63 |
+
if self.mode not in ['init', 'beam_search']:
|
64 |
+
raise ValueError(f'{type(self)} cannot do mode {self.mode}')
|
65 |
+
if self.decoder.supports_generate():
|
66 |
+
raise ValueError(f'{type(self)}.decoder cannot supports_generate()')
|
67 |
+
|
68 |
+
self.decoder(
|
69 |
+
input_tokens=inputs['targets'][:, 0:1],
|
70 |
+
target_tokens=None,
|
71 |
+
start_of_sequence=inputs['start_of_sequence'],
|
72 |
+
)
|
73 |
+
|
74 |
+
b = inputs['targets'].shape[0]
|
75 |
+
no_start_of_seq = jnp.array([False] * b, dtype=jnp.bool_)
|
76 |
+
|
77 |
+
# This fn is used in both beam_search or topk_sampling.
|
78 |
+
def tokens_to_logits_fn(
|
79 |
+
input_token: jnp.ndarray, dstate: tuple[dict[str, jnp.ndarray], ...]
|
80 |
+
) -> tuple[jnp.ndarray, tuple[dict[str, jnp.ndarray], ...]]:
|
81 |
+
(logits, dstate, _) = self.decoder(
|
82 |
+
input_tokens=input_token,
|
83 |
+
target_tokens=None,
|
84 |
+
start_of_sequence=no_start_of_seq,
|
85 |
+
decoder_state=dstate,
|
86 |
+
)
|
87 |
+
return logits[:, -1, :], dstate
|
88 |
+
|
89 |
+
last_token = jax.lax.dynamic_slice_in_dim(
|
90 |
+
inputs['targets'], inputs['length'] - 1, 1, axis=1
|
91 |
+
)
|
92 |
+
|
93 |
+
# last token is used to seed beam_search
|
94 |
+
inputs['targets'] = inputs['targets'][:, 0:-1]
|
95 |
+
dstate = jax.lax.cond(
|
96 |
+
inputs['start_of_sequence'][0],
|
97 |
+
lambda: self.generate(inputs)[0],
|
98 |
+
lambda: inputs['dstate'],
|
99 |
+
)
|
100 |
+
|
101 |
+
# Then we run beam search, init with last_token & dstate.
|
102 |
+
finished_seqs, finished_scores, dstate = beam_search.beam_search_flat(
|
103 |
+
last_token,
|
104 |
+
dstate,
|
105 |
+
tokens_to_logits_fn,
|
106 |
+
max_decode_len=512,
|
107 |
+
eos=inputs['eos'].reshape((1, 1, -1)),
|
108 |
+
mask=inputs['mask'].reshape((1, 1, -1)),
|
109 |
+
)
|
110 |
+
|
111 |
+
return 0.0, {
|
112 |
+
'finished_seqs': finished_seqs,
|
113 |
+
'finished_scores': finished_scores,
|
114 |
+
'dstate': dstate,
|
115 |
+
}
|
116 |
+
|
117 |
+
def generate(
|
118 |
+
self, inputs: ...
|
119 |
+
) -> tuple[tuple[dict[str, jnp.ndarray, ...], ...], jnp.ndarray]:
|
120 |
+
"""Generate an output sequence.
|
121 |
+
|
122 |
+
Args:
|
123 |
+
inputs: the same as argument to _call_.
|
124 |
+
|
125 |
+
Returns:
|
126 |
+
An array of generated tokens of shape (batch_size, sequence_length).
|
127 |
+
"""
|
128 |
+
input_tokens = inputs['targets'] # [b,seq_len]
|
129 |
+
start_of_sequence = inputs['start_of_sequence'] # [b]
|
130 |
+
target_tokens = jnp.pad(input_tokens[:, 1:], [(0, 0), (0, 1)])
|
131 |
+
batch_size = target_tokens.shape[0]
|
132 |
+
|
133 |
+
# Assuming all sequences start at the same time.
|
134 |
+
start0 = inputs['start_of_sequence'][0]
|
135 |
+
dstate = jax.lax.cond(
|
136 |
+
start0,
|
137 |
+
lambda: self.decoder.init_decoder_state_vanilla( # pylint: disable=g-long-lambda
|
138 |
+
1024, start_of_sequence
|
139 |
+
),
|
140 |
+
lambda: inputs['dstate'],
|
141 |
+
)
|
142 |
+
|
143 |
+
first_token = input_tokens[:, 0:1]
|
144 |
+
no_start_of_seq = jnp.array([False] * batch_size, dtype=jnp.bool_)
|
145 |
+
temperature = 1
|
146 |
+
if 'temperature' in inputs:
|
147 |
+
temperature = inputs['temperature']
|
148 |
+
|
149 |
+
num_steps = inputs['length']
|
150 |
+
if self.mode == 'beam_search':
|
151 |
+
num_steps -= 1
|
152 |
+
|
153 |
+
def cond_fn(scan_state) -> jnp.bool_:
|
154 |
+
_, _, i, _ = scan_state
|
155 |
+
return i < num_steps
|
156 |
+
|
157 |
+
def loop_fn(scan_state: Any) -> Tuple[Any, Any, Any, Any]:
|
158 |
+
(dstate, input_token, i, _) = scan_state
|
159 |
+
|
160 |
+
(logits, dstate, _) = self.decoder(
|
161 |
+
input_tokens=input_token,
|
162 |
+
target_tokens=None,
|
163 |
+
start_of_sequence=no_start_of_seq,
|
164 |
+
decoder_state=dstate,
|
165 |
+
)
|
166 |
+
|
167 |
+
logits = logits / temperature
|
168 |
+
output_token = jax.lax.dynamic_slice_in_dim(target_tokens, i, 1, axis=1)
|
169 |
+
|
170 |
+
return (dstate, output_token, i + 1, logits)
|
171 |
+
|
172 |
+
# Scan over the sequence length.
|
173 |
+
dummy_logits = jnp.zeros((batch_size, 1, 1024))
|
174 |
+
initial_scan_state = (dstate, first_token, 0, dummy_logits)
|
175 |
+
dstate, _, _, logits = jax.lax.while_loop(
|
176 |
+
cond_fn, loop_fn, initial_scan_state
|
177 |
+
)
|
178 |
+
return dstate, logits
|