commit e0feabec8f7fb63c5bb73afb7fef5481137787cd Author: GloamXun Date: Thu Nov 12 23:32:33 2026 +0800 Initialize optimizer research workspace with official baselines and history-free coverage Vendor pinned MeZO, AGZO, LOZO and LoREN sources with independent environments. Add direct in-place fix/adjust/node training, derived history-free basis gradients, development-best checkpoints and experiment tooling. Keep models, datasets, caches and credentials outside Git. Validation: 93 project tests passed; 521 vendored author files verified. diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..6952f0f --- /dev/null +++ b/.env.example @@ -0,0 +1,8 @@ +# WSL paths. Windows equivalent: E:\Experiments\Assets +EXPERIMENT_ASSETS=/mnt/e/Experiments/Assets +EXPERIMENT_MODELS=/mnt/e/Experiments/Assets/models +EXPERIMENT_DATA=/mnt/e/Experiments/Assets/data +EXPERIMENT_RESULTS=/mnt/e/Experiments/Assets/results +# Optional network setup belongs only in your untracked .env: +# http_proxy=http://127.0.0.1:7890 +# https_proxy=http://127.0.0.1:7890 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ee60d5d --- /dev/null +++ b/.gitignore @@ -0,0 +1,27 @@ +.venv/ +.venv-*/ +**/.upstream-git/ +__pycache__/ +*.py[cod] +.pytest_cache/ +.ruff_cache/ +.env +.env.* +!.env.example +*.log +*.pt +*.pth +*.bin +*.safetensors +*.ckpt +*.arrow +*.parquet +/models/ +/data/ +/results/ +**/wandb/ +**/cache/ +**/cached_datasets/ +**/saved_models/ +.DS_Store +# Keep source locks, templates, reports and small test fixtures versionable. diff --git a/.python-version b/.python-version new file mode 100644 index 0000000..0cf960d --- /dev/null +++ b/.python-version @@ -0,0 +1 @@ +3.13.14 diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..ee17a79 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,23 @@ +# Project instructions + +- User instruction (2026-11-12): align checkpoint selection with MeZO: save by minimum post-update development loss, restore development-best weights before final official-validation evaluation, retain earlier checkpoint on ties. Short-run learning-rate selection also uses development-best loss. Existing final-iterate experiments and source snapshots must remain recoverable; restarted best-checkpoint studies use new output directories. HF exports remain inference-only, not exact training-resume checkpoints. + +- User authorization (2026-11-12): implement and train history_free_coverage_gradient_v1 via --node_update history_free. Use the derived current-batch gradient 2 Pi r n v, one joint node forward plus the two reused training forwards; apply old-basis SGD before installing normalize(d+rho*gradient). No historical gradient, sign/fixed-angle replacement, curvature term or gate. All untied Linear bases; refresh every 128 updates; short learning-rate search then fresh long run, with complete query/source/data records. Default original node remains recoverable. + +- User clarification (2026-11-12): engineering experiments may use explicitly documented local-curvature approximations without a global upper-bound certificate. Keep magnitude-based basis gradients, validate the estimator, record the exact variant and query costs, and use theory to interpret observations without claiming certified descent. This authorizes local_curvature_gradient_v1; historical sign/fixed-angle proxy results remain ineligible. + +- Do not commit or push until explicitly requested by the user. +- Preserve vendored official files. Put device/API adapters outside author files and document every numerical change as a distinct variant. +- Each baseline owns pyproject.toml, uv.lock and .venv. Our methods use the root environment. Never mix site-packages across environments. +- Shared assets default to /mnt/e/Experiments/Assets/{models,data,results}. Check the live E mount before writes; no model/data/result output on C or NAS by default. +- Fix/adjust/node use direct_weights_inplace_v2: apply rank-1 Gaussian SGD updates directly to Linear weights W, with dense auxiliary updates. Keep algorithms and basis construction in trainer.py; no separate subspace state or B/C/warm decomposition. Preserve tied weights once; switching bases must not change W. Internal historical reference modules remain in src/experiments_codebase. +- Keep the experimental flows minimal: fix uses a fixed basis; adjust_single_probe_v1 compares one old/new virtual update. User rollback (2026-11-12): default node restores node_unconditional_refresh_control_v1, using the historical EMA/node proposal every 128 updates without old/new gating. Its ideal node sketch estimates G^T p, not the scalar s; reassess stale proposal directions and update costs before new experiments. Retain the explicitly selected local_curvature variant for review. Do not add interpolation search, repeated trials, SEM gates, or independent confirmation unless requested. Default refresh-event costs are adjust=6 and node<=7 main forwards, plus the normal 2-forward training step. +- All basis construction and detection forwards count against the main budget. Evaluation counts are separate. Do not use diagnostic gradients in training updates. +- Perturb weights in place and regenerate per-parameter noise from the same seed for inverse restoration, as in AGZO. Do not snapshot the full model or retain full-model noise. Restoration allows FP32 rounding error; do not claim bitwise equality. Three-point monitoring of an existing direction costs one extra forward; candidate construction/comparison/confirmation costs must be reported separately. +- Save effective hyperparameters, source/data fingerprints, query counts, loss/accuracy curves, timing and memory. Progress updates must identify actual evaluation query counts. +- Native author Trainer results and common task-adapter results are different protocols. Do not claim paper reproduction from smoke checks or reuse mismatched cache/data hashes. +- Follow the Karpathy Guidelines; keep changes scoped and verify the affected behavior. +- No proxy implementations: map research code to the agreed derivation, or finish a complete implementation-and-test plan first. Never silently replace gradient magnitudes with sign/fixed-angle steps, normalize sampling directions without the derived scaling, or substitute measured local curvature for a required quadratic upper bound. Derive and validate stochastic estimators and assumptions before formal experiments. If required theory or quantities are unavailable, document the gap instead of running a substitute. Historical proxy results do not validate or refute the intended theory. + +- Own methods use methods/large_models (MeZO-style Framework/OurTrainer), with one run.py entry and --trainer fix|adjust|node. Keep method documentation in methods/README.md; do not reintroduce separate method wrapper or provenance directories. Default all three methods to data_protocol=mezo, using author sampling/templates/objectives and HF RandomSampler with tail batches retained. Explicit legacy selects the historical data protocol, not the historical coefficient parameterization. Never mix caches across protocols or parameterizations. +- Current checkpoints are standard HF model directories. Removed legacy entries and their dedicated regression helpers must not be used for current validation; old .pt checkpoints are unsupported. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f3ca544 --- /dev/null +++ b/README.md @@ -0,0 +1,104 @@ +# Forward-only optimizer experiments + +## 当前自己的方案采用MeZO项目结构 + +fix/adjust/node统一使用 `methods/large_models/run.py`,通过 `--trainer fix|adjust|node` 选择算法。 +参见 [算法、参数、预算与排障](methods/README.md)。三种方案默认统一使用 `--data_protocol mezo`:作者抽样、模板、目标函数与HF随机采样器,默认保留尾批。`--data_protocol legacy` 只切换数据协议。 +官方基线继续使用各自的独立环境。旧参考实现的内部模块保留在src/experiments_codebase,但不再提供旧方案目录和run_legacy.py入口。 +当前入口导出标准HF的 `model/`,不支持旧的 `.pt` 检查点。`reports/` 中早期系数实现和packaging验证属于历史记录。 + + +四个官方基线、固定/自适应刷新和节点基方案的独立实验代码。源码、依赖锁和验证记录由 Git 管理;模型、数据及实验缓存保存在共享资产目录。 + +## 布局 + +```text +baselines/{mezo,agzo,lozo,loren}/ 官方源码 + 各自 pyproject.toml/uv.lock/.venv +methods/large_models/ 统一run.py、Trainer、任务/模板,--trainer选择算法 +methods/README.md 三种方法的算法、运行与预算说明 +src/experiments_codebase/ 共享资源、基线兼容层与旧方案回归实现 +scripts/ 环境和资源准备 +reports/ 安装/验证结果(不含模型大文件) +upstream.lock.json 官方仓库提交与来源 +``` + +根环境只运行我们的方法和资产工具;每个基线用自己的 uv 环境。锁文件是正式依赖依据。 +原生入口保留官方训练流程;run_compatible.py 是明确标记的现代模型/统一任务适配,二者结果不能混用。 + +## 首次配置 + +```bash +cd ~/experiments_codebase +# 安装uv(若未装):按 https://docs.astral.sh/uv/getting-started/installation/ 操作 +cp .env.example .env # 可选;默认路径已可直接使用 +source scripts/env.sh +uv sync --locked +uv run --locked python scripts/prepare_assets.py --download-missing +bash scripts/sync_all.sh +``` + +WSL需安装 git/curl/ca-certificates/libgomp/libstdc++,Windows NVIDIA 驱动正常,`nvidia-smi` 可用。 +不需要在WSL安装另一套Linux NVIDIA内核驱动。torch wheel自带CUDA运行时;没有自编译需求就无需nvcc。 +RTX 5070Ti需要现代CUDA/PyTorch,因此保留作者数值代码但使用支持显卡的torch版本。 +如代理环境使用内部证书,可设置 `UV_SYSTEM_CERTS=true`,不要关闭TLS验证。 + +## 统一资源 + +| 类型 | WSL默认 | Windows | +|---|---|---| +| 模型 | /mnt/e/Experiments/Assets/models | E:\Experiments\Assets\models | +| 数据 | /mnt/e/Experiments/Assets/data | E:\Experiments\Assets\data | +| 输出 | /mnt/e/Experiments/Assets/results | E:\Experiments\Assets\results | + +根 `.env` 可覆盖 EXPERIMENT_ASSETS 或三个分目录;`.env` 不跟踪。 +`scripts/env.sh` 同时设置 HF_HOME/HF_HUB_CACHE/HF_DATASETS_CACHE/HF_XET_CACHE/WANDB_DIR。 +Python入口即使没有source也有同样默认值,且写入前检查E盘挂载。历史项目的配置和缓存不改动。 +模型按本地目录 `opt-1.3b`、`qwen3-0.6b` 保存;数据为 save_to_disk 的 `sst2`、`drop`。 +`asset_manifest.json`(位于Assets根)记录模型文件SHA256和数据指纹。 +旧OPT/SST2固定子集另存 `data/historical_opt13_sst2`,不会把新采样冒充旧cache等价实验。 + +## 快速运行 + +```bash +uv run --locked python methods/large_models/run.py --trainer fix --budget 21 --train-samples 16 --dev-samples 4 --eval-samples 4 --batch-size 2 --calibration-samples 2 --no-save-checkpoint +uv run --locked python methods/large_models/run.py --trainer adjust --budget 21 --refresh-every 1 --train-samples 16 --dev-samples 4 --eval-samples 4 --batch-size 2 --calibration-samples 2 --no-save-checkpoint +uv run --locked python methods/large_models/run.py --trainer node --budget 21 --refresh-every 1 --train-samples 16 --dev-samples 4 --eval-samples 4 --batch-size 2 --calibration-samples 2 --no-save-checkpoint +``` + +上述仅冒烟,不是正式比较。全部CLI参数以 `--help` 为准。默认训练1000、开发500,从训练集无放回且互不重叠采样;验证集独立。 +新统一采样不保证与旧cache哈希相同,不能直接宣称复用旧成绩。 +methods/README.md与各基线TROUBLESHOOTING说明了入口、调参和已知限制。 + +## 输出、推理与可追溯性 + +每次在共享results建立新目录,不覆盖旧实验:hyperparameters/environment/data_manifest/parameter_inventory、records.jsonl、refresh.jsonl、curve.json、query_ledger、summary、progress.json/md、run.log、loss_curve.png、SST2的acc_curve.png。 +统一入口采用direct_weights_inplace_v2,直接更新模型权重W,按种子重建噪声并原地加减扰动,保存标准HF模型model/;可用 --no-save-checkpoint 只留日志。检查点支持推理,尚不支持断点续训。 +DROP记录teacher-forced loss,MeZO协议默认还运行作者的生成/文本F1评估;该文本F1不等于DROP官方数字/多跨度评分。可用 --no_eval 跳过作者预测评分,单独生成使用 --action generate。 +所有检测前向计入 --budget;评估独立计数。无多seed阴影,无n=图例后缀。 + +```bash +uv run --locked python methods/large_models/run.py --trainer node --action evaluate --checkpoint /mnt/e/Experiments/Assets/results/RUN/model +uv run --locked python methods/large_models/run.py --trainer node --action generate --checkpoint /mnt/e/Experiments/Assets/results/RUN/model --prompt 'Hello' +uv run --locked pytest tests +``` + +源码和uv锁可提交;.venv、凭据、模型、数据、结果、上游Git对象均被.gitignore排除。本次没有使用提供的access token。 + +## 环境检查和重新验证 + +```bash +uv run --locked python scripts/doctor.py +python3 scripts/validate.py --stage all +``` + +验证脚本会顺序运行小型检查,并在每个基线验证后切回native依赖组。若需要联网安装,先source scripts/env.sh并在.env设置已有代理。不会启动完整benchmark。 + +## 自选比较图 + +编辑 scripts/plot_config.example.json 中的运行目录、label和enabled,再运行: + +```bash +uv run --locked python scripts/plot_compare.py --config scripts/plot_config.example.json --out /mnt/e/Experiments/Assets/results/comparison +``` + +该脚本比较兼容入口生成的curve.json;原生Trainer结果需要先核对目标函数、采样和计账协议,不能直接当作统一实验曲线。 diff --git a/baselines/agzo/.gitignore b/baselines/agzo/.gitignore new file mode 100644 index 0000000..78cf920 --- /dev/null +++ b/baselines/agzo/.gitignore @@ -0,0 +1,74 @@ +# Python +__pycache__/ +*.py[cod] + +# Logs +*.log +*.out + +# Virtual environment +venv/ + +# Jupyter Notebook +.ipynb_checkpoints + +# System Files +.DS_Store + +# Machine-specific files +.idea +*.iml +.vscode + +# Temporary files +*.tmp +*.temp + +# Build artifacts +build/ +dist/ +*.egg-info/ + +# Python caches and test caches +.cache/ +.pytest_cache/ + +# Experiment/ML outputs +log/ +logs/ +result/ +results/ +checkpoints/ +outputs/ +runs/ +wandb/ +*.wandb + +# Model weights/artifacts +*.pt +*.pth +*.ckpt +*.bin +*.safetensors + +# Environment files +.env +.env.* +.venv/ +env/ + +# Jupyter checkpoints (ensure directory form) +.ipynb_checkpoints/ + +# OS specific +Thumbs.db + +# Shell outputs +nohup.out + +# profiler +export_only_prof_dir/ +train_profile.json +kernel_meta/ +.modelscope_cache/ + diff --git a/baselines/agzo/.python-version b/baselines/agzo/.python-version new file mode 100644 index 0000000..ed7d51a --- /dev/null +++ b/baselines/agzo/.python-version @@ -0,0 +1 @@ +3.11.15 diff --git a/baselines/agzo/LICENSE b/baselines/agzo/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/baselines/agzo/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/baselines/agzo/README.md b/baselines/agzo/README.md new file mode 100644 index 0000000..77cb8ae --- /dev/null +++ b/baselines/agzo/README.md @@ -0,0 +1,73 @@ +ActivationGuidedZO-NPU: Activation-Guided Zeroth-Order Optimization for LLM Fine-Tuning(NPU) +================================================= + +[License: GPL v3](https://www.gnu.org/licenses/gpl-3.0) \ +[License: OPENPANGU MODEL LICENSE AGREEMENT VERSION 1.0](/openPangu%20LICENSE) + +This repository is built to benchmark ActivationGuidedZO/ZO-LLM performance on openPangu-embedeb-1B. It extends the ZO-LLM benchmark with Activation-Guided Zeroth-Order optimization (ActivationGuidedZO). It remains under GPLv3: any distribution or modification must keep GPLv3 terms and notices. The training loop and README were forked from ZO-LLM (https://github.com/ZO-Bench/ZO-LLM); ActivationGuidedZO logic was added in [zo-bench/trainer.py](zo-bench/trainer.py), and this README was rewritten accordingly. + +Table of Contents +----------------- +1. Overview +2. ActivationGuidedZO at a Glance +3. What's New in This Fork +4. Repository Layout +5. Setup +6. Root Scripts +7. Licenses and Attribution +8. Citation + +## 1) Overview +This fork builds on the "Revisiting Zeroth-Order Optimization for Memory-Efficient LLM Fine-Tuning: A Benchmark" codebase to deliver Activation-Guided Zeroth-Order Optimization (ActivationGuidedZO). ZO-LLM benchmarks backpropagation-free, memory-efficient fine-tuning across OPT, LLaMA/Vicuna, Mistral, and RoBERTa families on classification and reasoning tasks. ActivationGuidedZO aligns perturbations with activation subspaces via lightweight power iteration, improving gradient direction quality without increasing memory beyond near-inference levels. + +## 2) ActivationGuidedZO at a Glance +- Guided basis: For each linear layer, a forward hook captures activations, reshapes to (batch*seq, hidden), and runs a few power-iteration steps to approximate the top activation direction. +- Rank-1 perturbation: Builds $P_l = r_l u_l^T$ with a regenerated random vector $r_l$ and stored direction $u_l$, keeping storage minimal. +- Two-point estimate: Evaluates $L_+$ and $L_-$ with $\pm \epsilon P$ and forms the projected gradient $(L_+ - L_-)/(2\epsilon)$. +- Memory-saving tricks: Uses a single random seed to reconstruct $r_l$ in-place and discards activations after the basis is computed; only $u_l$ vectors are kept. + +## 3) What's New in This Fork +- ActivationGuidedZO trainer with configurable `agzo_power_iter_steps` and activation hooks that store only principal directions. +- Rank-1 perturbation path integrated into the training loop with the same LR scheduling as other ZO optimizers. +- Experiment tagging that records ActivationGuidedZO settings for sweeps. +- Scripts targeting NPU runs (see run_*_pangu-1b.sh) plus updated documentation. + +## 4) Repository Layout +- [zo-bench/run.py](zo-bench/run.py): Entry point for training and evaluation. +- [zo-bench/trainer.py](zo-bench/trainer.py): Optimizers and training loop; ActivationGuidedZO implementation lives here. +- [zo-bench/tasks.py](zo-bench/tasks.py) and [zo-bench/templates.py](zo-bench/templates.py): Task definitions and prompt templates. +- [zo-bench/sweeps](zo-bench/sweeps): Hyperparameter sweeps organized by task, model, optimizer, and tuning scheme. + +## 5) Setup +```bash +conda create -n zollm python=3.10 +conda activate zollm +pip install -r requirements.txt +``` + +## 6) Root Scripts +- `run_agzo_pangu-1b.sh`: ActivationGuidedZO training/eval entry tailored for Pangu-1B NPUs. +- `run_fo_pangu-1b.sh`: Forward-gradient baseline on Pangu-1B. +- `run_lozo_pangu-1b.sh`: Low-Rank ZO (LOZO) baseline on Pangu-1B. +- `run_zo_sgd_pangu-1b.sh`: ZO-SGD baseline on Pangu-1B. +- `run_icl_pangu-1b.sh`: In-context learning routines on Pangu-1B. +- `run_zeroshot_pangu-1b.sh`: Zero-shot pipeline that can also be used for direct inference without fine-tuning. + +## 7) Licenses and Attribution +- Code license: GPLv3 (see LICENSE). Redistributions and derivatives must retain GPLv3 terms and notices. +- Model license: OPENPANGU MODEL LICENSE AGREEMENT VERSION 1.0 applies to model assets (see link above). +- Upstream origin: Forked from ZO-LLM (https://github.com/ZO-Bench/ZO-LLM). The baseline training loop in [zo-bench/trainer.py](zo-bench/trainer.py) and this README were derived from the upstream project and modified here to add ActivationGuidedZO. + +## 8) Citation +If you use this work, please cite the original ActivationGuidedZO paper: +``` +@misc{lin2026agzoactivationguidedzerothorderoptimization, + title={AGZO: Activation-Guided Zeroth-Order Optimization for LLM Fine-Tuning}, + author={Wei Lin and Yining Jiang and Qingyu Song and Qiao Xiang and Hong Xu}, + year={2026}, + eprint={2601.17261}, + archivePrefix={arXiv}, + primaryClass={cs.LG}, + url={https://arxiv.org/abs/2601.17261}, +} +``` diff --git a/baselines/agzo/TROUBLESHOOTING.md b/baselines/agzo/TROUBLESHOOTING.md new file mode 100644 index 0000000..021aff6 --- /dev/null +++ b/baselines/agzo/TROUBLESHOOTING.md @@ -0,0 +1,81 @@ +# AGZO:独立环境、入口与排障 + +官方来源:https://github.com/Yining-Jiang/ActivationGuidedZO-NPU.git;锁定提交:`623e09a5a7dfdee697a603ec1e7aa01e3f5e6290`。 +官方文件保留原样;此目录新增 pyproject.toml、uv.lock、native.py、run_compatible.py 和本文。 +原仓库 Git 历史存放在被忽略的 `.upstream-git/`,防止主项目意外把整个目录当成 gitlink。 +查看上游版本:`git --git-dir=.upstream-git --work-tree=. rev-parse HEAD`。 +不要在这个目录执行普通 git commit/push;主项目尚未提交。 + +## 安装与版本 + +在 WSL 中执行(不需要激活根目录环境): + +```bash +cd ~/experiments_codebase +source scripts/env.sh +cd baselines/agzo +uv sync --locked +uv run --locked python native.py --help +``` + +此目录 `.venv` 独立,Python 3.11,torch 2.13.0,原生 Transformers 4.53.2。 +直接依赖精确版本写在 pyproject.toml,全部间接依赖和 wheel 哈希写在 uv.lock。 +`uv sync --locked` 默认 native;`uv sync --locked --no-default-groups --group modern` 切换到 Transformers 4.57.1。 +两组互斥,使用同一个本库 `.venv`,不会激活其他方法的环境。不要使用 `uv pip install -U` 绕开锁。 + +## 官方入口及命令 + +原入口 `zo-bench/run.py`。本地资源包装入口 `native.py` 仅设置共享路径、提供本地 Dataset 和启动参数,然后运行原始程序。 +`--asset-model`、`--asset-task`、`--asset-out` 是包装参数,其余参数透传官方入口;以 `--help` 为准。 +MeZO/LOZO/AGZO包装器默认固定 train_set_seed=42,并将result_file显式指向共享输出;否则原版会因num_dev配合空采样seed触发断言,或因相对result目录缺失在训练完成后报错。用户后置同名参数可覆盖这些默认值。 + +```bash +uv run --locked python native.py --asset-model facebook/opt-1.3b --asset-task sst2 --max_steps 2 --num_train 16 --num_dev 4 --num_eval 4 --per_device_train_batch_size 2 --learning_rate 2e-6 --zo_eps 1e-3 --agzo_rank 1 --agzo_power_iter_steps 5 --eval_strategy no --save_strategy no --logging_steps 1 +``` + +调参请使用官方参数:学习率 `--learning_rate`,差分半径 `--zo_eps`,batch `--per_device_train_batch_size`。 +参数覆盖:MeZO/LOZO/AGZO 默认 full(不传 LoRA/prefix/head-only 开关);LOREN 包装器显式传 `--full_parameter`。 +全参数覆盖不等于无结构全维搜索;LOZO/AGZO 仍使用结构化扰动。 + +## Qwen3 / DROP 与统一比较入口 + +```bash +uv run --locked --no-default-groups --group modern python run_compatible.py --model Qwen/Qwen3-0.6B --task sst2 --budget 12 --train-samples 16 --dev-samples 4 --eval-samples 4 --batch-size 2 --eval-batch-size 2 --calibration-samples 2 --no-save-checkpoint +# DROP:将 --task 改为 drop,并合理增加 --max-length(短冒烟可以先用128)。 +``` + +兼容层 `../../src/experiments_codebase/official.py` 从本库源码编译官方数值函数;不导入旧 Trainer,也不另写一套公式。 +通用数据协议和计账在 `../../src/experiments_codebase/task.py`、`runner.py`。 +此入口统一 SST2 为两 verbalizer 的交叉熵、DROP 为答案 token 的 teacher-forced CE;它与部分官方任务目标不同,日志会标记 task adapter。 +预算为总 main forward,而非更新步数;检测和基提取前向不免费。评估前向另列。 +不支持从兼容检查点续训;可用 `--action evaluate --checkpoint ...` 或 `--action generate --checkpoint ... --prompt ...` 推理。 + +## 核心位置 + +- 核心算法:`zo-bench/trainer.py: agzo_collect_basis / _agzo_power_iteration / agzo_step`。 +- 模型/数据:`zo-bench/run.py: Framework; zo-bench/tasks.py / templates.py; npu_compat.py`。 +- 官方超参数原型:入口中的参数 dataclass/parser 与原始 shell 脚本;与本站兼容入口参数不是同一命名空间。 + +## 系统组件与常见问题 + +官方仓库针对昇腾 NPU/Pangu,其 npu_compat.py 的 CUDA 回退不完整,run.py 还直接调用 torch.npu.manual_seed_all。native.py 在内存中将种子/设备计数改为CUDA,并为设备信息、显存、设备选择提供CUDA回调;不更改磁盘上的官方文件或优化器公式。每次运行保存 compatibility_changes.json。本环境不装 torch_npu。原脚本有 Pangu 路径,不能直接当 OPT/Qwen 的实验配置。agzo_collect_basis 是额外一次前向,统一计账时每更新通常为 3 次而非 2 次。原生Trainer的默认optim可能为adamw,若要AGZO+SGD需显式传 --optim sgd;实际启动参数以日志为准。 + +WSL 必须能看到 NVIDIA 驱动:先运行 `nvidia-smi`。RTX 5070 Ti 是 Blackwell;原论文旧版 torch/CUDA wheel 不支持其架构。 +本机选用支持当前显卡的 torch 2.13.0,不声称完全复刻论文年代的二进制环境。 +CUDA runtime 随 wheel 安装,普通运行无需 nvcc;自编译第三方扩展才需要 CUDA toolkit、gcc/g++、make、Python headers。 +Fedora 常见系统依赖:`git curl ca-certificates libgomp libstdc++`;缺库先用 `ldd` 核查,不要盲目替换驱动。 +uv 会下载 Python 3.11,不依赖系统 Python 3.14;保持 `.python-version`。 +如果 WSL 解析到 198.18.* 且直连超时,可在未跟踪的根 `.env` 配置你现有代理,再 `source ../../scripts/env.sh`;不要把代理/token 写入源码。 +本次用临时 HTTP(S)_PROXY 沿用主机代理;未修改系统网络配置。 +`huggingface-hub` 不能随意升到2.x:Transformers 4.x 需要 <1.0。已锁0.36.0。 +新版setuptools移除了pkg_resources,旧Trainer/accelerate仍导入它;锁80.9.0同时满足torch要求的>=77.0.3。LOREN官方requirements漏列loguru,本环境已补0.7.3。 +旧 datasets/pyarrow/numpy 有 ABI 约束,三者必须遵守 uv.lock;不能拿现代 `.venv` 的 site-packages 混入原生环境。 +共享DROP不能用datasets5.x的List元数据序列化后直接给2.x/3.x读;请在根锁定环境datasets3.6执行prepare_assets,工具可从原始parquet重建不兼容资产。 +E盘必须真实挂载。Assets默认位于 `/mnt/e/Experiments/Assets`,包装器在写入前检查 mountpoint。 +模型和数据只从本地共享目录读取;资产缺失先在根环境运行 `scripts/prepare_assets.py --download-missing`。 +Qwen的词表较大,长序列或大 batch 会增显存;先减batch/长度,不要把OOM归因于优化算法。 + +## 验证状态 + +以根目录 `reports/validation_report.json` 和 `reports/validation.log` 为准,区分安装、导入、短步训练、模型任务矩阵。 +`--help` 通过不代表训练通过,短步通过也不代表论文精度复现。未完成项目会明确记录。 diff --git a/baselines/agzo/native.py b/baselines/agzo/native.py new file mode 100644 index 0000000..89c3939 --- /dev/null +++ b/baselines/agzo/native.py @@ -0,0 +1,71 @@ +"""Run the original entry point with shared local assets. No optimizer rewrite.""" +import argparse +from datetime import datetime,timezone +import json +import os +from pathlib import Path +import runpy +import sys + +HERE=Path(__file__).resolve().parent +ROOT=HERE.parents[1] +sys.path.insert(0,str(ROOT/'src')) +from experiments_codebase.paths import paths,model_path,save + +def main(): + p=argparse.ArgumentParser(description=__doc__,add_help=False) + p.add_argument('--asset-model',default='facebook/opt-1.3b') + p.add_argument('--asset-task',choices=['sst2','drop'],default='sst2') + p.add_argument('--asset-out',type=Path) + args,rest=p.parse_known_args();method=HERE.name + roots=paths();os.environ.setdefault('WANDB_MODE','disabled');os.environ['WANDB_DIR']=str(roots['results']/'wandb') + out=(args.asset_out or roots['results']/f'native_{method}_{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}').resolve() + if not out.is_relative_to(roots['results'].resolve()):raise ValueError('Output must be under shared results') + # Both local datasets are supplied through the HF Dataset API expected by authors. + import datasets + original=datasets.load_dataset + def local_dataset(name,*pos,**kw): + config=pos[0] if pos else kw.get('name') + alias='sst2' if (name in ('glue','nyu-mll/glue') and config=='sst2') or name=='sst2' else ('drop' if name in ('drop','ucinlp/drop') else None) + if alias: + ds=datasets.load_from_disk(str(roots['data']/alias)) + split=kw.get('split');return ds[split] if split else ds + return original(name,*pos,**kw) + datasets.load_dataset=local_dataset + model=str(model_path(args.asset_model)) + if method=='loren': + if args.asset_task=='drop':raise ValueError('Official LOREN has no DROP task; use run_compatible.py with the modern group for a labeled task extension') + if 'Qwen' in args.asset_model:raise ValueError('Official LOREN has no Qwen model branch; use the modern compatibility entry') + entry=HERE/'main.py' + defaults=['--model_name',model,'--task',args.asset_task,'--algorithm','LOREN','--results',str(out),'--full_parameter'] + else: + work=HERE/('zo-bench' if method=='agzo' else 'large_models') + entry=work/('run_lozo.py' if method=='lozo' else 'run.py') + task='SST2' if args.asset_task=='sst2' else 'DROP' + defaults=['--model_name',model,'--task_name',task,'--output_dir',str(out),'--trainer',{'mezo':'zo','lozo':'LOZO','agzo':'agzo'}[method], + '--report_to','none','--train_set_seed','42','--train_as_classification',str(task=='SST2'),'--lr_scheduler_type','constant'] + defaults+=['--result_file',str(out/'result.json')] + # User's original HF/author flags appear last and override wrapper defaults. + if '--help' not in rest: + out.mkdir(parents=True,exist_ok=False) + save(out/'launch.json',dict(method=method,entry=str(entry),argv=defaults+rest,executable=sys.executable,adapter='Local assets and paths only; original Trainer/optimizer',pid=os.getpid())) + sys.path.insert(0,str(entry.parent));os.chdir(out if out.exists() else HERE) + sys.argv=[str(entry),*defaults,*rest] + if method=='agzo': + import torch + if torch.cuda.is_available() and not hasattr(torch,'npu'): + # The author's NPU helper has incomplete CUDA branches. Only device + # plumbing is adapted; trainer.py and AGZO numerical methods are intact. + import npu_compat as devices + devices.device_count=torch.cuda.device_count + devices.mem_get_info=torch.cuda.mem_get_info + devices.get_active_device_info=lambda:('cuda',torch.cuda.current_device(),torch.cuda.get_device_properties(0).total_memory/2**30,torch.cuda.get_device_name()) + devices.safe_set_device=lambda index:(torch.cuda.set_device(int(index or 0)) or int(index or 0),torch.cuda.device_count()) + devices.to_device=lambda tensor:tensor.cuda() + source=entry.read_text().replace('torch.npu.manual_seed_all(seed)','torch.cuda.manual_seed_all(seed)').replace('torch.npu.device_count()','torch.cuda.device_count()') + if out.exists():save(out/'compatibility_changes.json',{'scope':'CUDA device plumbing only','source_modified_on_disk':False,'numerical_optimizer_modified':False,'changes':['NPU seed -> CUDA seed','NPU device count -> CUDA count','device helper memory/info/count/set/to_device CUDA callbacks']}) + exec(compile(source,str(entry),'exec'),dict(__name__='__main__',__file__=str(entry))) + return + runpy.run_path(str(entry),run_name='__main__') + +if __name__=='__main__':main() diff --git a/baselines/agzo/openPangu LICENSE b/baselines/agzo/openPangu LICENSE new file mode 100644 index 0000000..4079035 --- /dev/null +++ b/baselines/agzo/openPangu LICENSE @@ -0,0 +1,34 @@ +OPENPANGU MODEL LICENSE AGREEMENT VERSION 1.0 + +This OPENPANGU MODEL LICENSE AGREEMENT VERSION 1.0 (the "Agreement") is a legal agreement between You and Huawei Technologies Co., Ltd. ("Huawei", "We" or "Us"), and it governs Your reproducing, use, modification, and distribution of openPangu as made available by Huawei under this Agreement. + +By using, reproducing, modifying, distributing, performing or displaying any portion or element of openPangu, or otherwise accepting the terms of this Agreement, You agree to be bound by this Agreement. + +1. Definitions. +1.1. “openPangu” or “Model” means openPangu large language models and software, including trained model weights, parameters (including optimizer states), accompanying source code and scripts released under this Agreement. +1.2. “Derivative Model” means all (1) modifications to the Model, (2) works based on the Model, and (3) any other derivative works of the Model. For clarity, information or content results from operating or otherwise using the Model is not a Derivative Model. +1.3. “You” or “Your” means an individual or Legal Entity exercising permissions granted by this Agreement and/or using the Model for any purpose. +1.4. “Third Party” or “Third Parties” means individuals or legal entities that are not under common control with Us or You. + +2. License Grant. Subject to Your full compliance with the terms and conditions of this Agreement, We hereby grant to You a perpetual, worldwide, non-exclusive, non-transferable, no-charge, royalty-free license (except as stated in Section 3) to use, reproduce, modify, and distribute the Model. + +3. Conditions for License Grant. You represent and warrant that You will not, access, download, install, run, deploy, integrate, modify, or otherwise use the Model, directly or indirectly, within the European Union. + + +4. Redistribution. +4.1. If You distribute the Model or Derivative Model, You shall retain in Your distribution (1) a copy of this agreement, and (2) all copyright notices and other notices of origin included in the Model that are applicable to Your distribution. +4.2. Further, if You distribute or make available to Third Parties a product or service (including another AI model) based on the Model, You are required to (1) display the acknowledgement “Powered by openPangu” and (2) include a trademark notice “openPangu is a trademark of Huawei Technologies Co., Ltd.” on related webpages, user manuals, product documentations or other advertising materials mentioning features of the Model. +4.3. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for Derivative Model made by You as a whole, provided Your use, reproduction, and distribution of the Model otherwise complies with the terms and conditions of this Agreement. + +5. Ownership. We do not claim ownership to any information or content generated using the Model or Derivative Model that are made by You. You are solely responsible for evaluating the accuracy and appropriateness of such information or content for Your use case. + +6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of Huawei, except as required for complying with Section 4.2. + +7. Indemnity. You will indemnify and hold harmless Huawei from and against any claim by any third party arising out of or related to Your use or distribution of the Model or Derivative Model made by You (e.g. a violation against Section 3). For avoidance of doubt, “third party” in this clause include supervisory authorities. + +8. THE MODEL IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE, NONINFRINGEMENT, ACCURACY, OR THE ABSENCE OF LATENT OR OTHER DEFECTS OR ERRORS, WHETHER OR NOT DISCOVERABLE, ALL TO THE GREATEST EXTENT PERMISSIBLE UNDER APPLICABLE LAW. + +9. IN NO EVENT SHALL WE BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING, BUT NOT LIMITED TO ANY DIRECT, OR INDIRECT, SPECIAL OR CONSEQUENTIAL DAMAGES ARISING FROM YOUR USE OR INABILITY TO USE THE MODEL, IN WHOLE OR IN PART, NO MATTER HOW IT’S CAUSED OR THE LEGAL THEORY IT IS BASED ON, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + + +END OF THE TERMS AND CONDITIONS \ No newline at end of file diff --git a/baselines/agzo/pyproject.toml b/baselines/agzo/pyproject.toml new file mode 100644 index 0000000..7a739c7 --- /dev/null +++ b/baselines/agzo/pyproject.toml @@ -0,0 +1,14 @@ +[project] +name = "official-agzo-experiment" +version = "0.1.0" +requires-python = ">=3.11,<3.12" +dependencies = ["torch==2.13.0", "setuptools==80.9.0", "numpy==1.26.4", "matplotlib==3.10.7", "psutil==7.1.3", "scikit-learn==1.7.2", "sentencepiece==0.2.1", "wandb==0.23.1", "rouge==1.0.1", "nltk==3.9.2", "einops==0.8.1"] + +[dependency-groups] +native = ["transformers==4.53.2", "datasets==2.21.0", "pyarrow==17.0.0", "accelerate==1.12.0", "huggingface-hub==0.36.0"] +modern = ["transformers==4.57.1", "datasets==3.6.0", "pyarrow==20.0.0", "accelerate==1.12.0", "huggingface-hub==0.36.0"] + +[tool.uv] +package = false +default-groups = ["native"] +conflicts = [[{group="native"}, {group="modern"}]] diff --git a/baselines/agzo/requirements.txt b/baselines/agzo/requirements.txt new file mode 100644 index 0000000..05c57ec --- /dev/null +++ b/baselines/agzo/requirements.txt @@ -0,0 +1,71 @@ +absl-py==2.3.1 +accelerate==1.12.0 +aiohttp==3.9.1 +aiosignal==1.3.1 +appdirs==1.4.4 +async-timeout==4.0.3 +attrs==23.1.0 +certifi==2023.11.17 +cffi==2.0.0 +charset-normalizer==3.3.2 +click==8.1.7 +Cython==3.2.2 +datasets==2.16.0 +decorator==5.2.1 +dill==0.3.7 +docker-pycreds==0.4.0 +einops==0.8.1 +filelock==3.13.1 +frozenlist==1.8.0 +fsspec==2023.10.0 +gitdb==4.0.11 +GitPython==3.1.40 +gmpy2==2.1.2 +hf-xet==1.2.0 +huggingface-hub==0.36.0 +idna==3.6 +Jinja2==3.1.2 +joblib==1.3.2 +llvmlite==0.41.1 +MarkupSafe==2.1.3 +modelscope==1.32.0 +mpmath==1.3.0 +multidict==6.0.4 +multiprocess==0.70.15 +networkx==3.4.2 +numba==0.58.1 +numpy==1.24.0 +packaging==23.2 +pandas==2.3.3 +pathlib2==2.3.7.post1 +protobuf==3.20.0 +psutil==5.9.7 +pyarrow==14.0.2 +pyarrow-hotfix==0.6 +pycparser==2.23 +python-dateutil==2.8.2 +pytz==2023.3.post1 +PyYAML==6.0.1 +regex==2023.12.25 +requests==2.31.0 +safetensors==0.7.0 +scikit-learn==1.3.2 +scipy==1.15.3 +sentencepiece==0.2.1 +sentry-sdk==1.39.1 +setproctitle==1.3.3 +six==1.16.0 +smmap==5.0.1 +sympy==1.13.1 +threadpoolctl==3.2.0 +tokenizers==0.21.4 +torch==2.6.0 +torch_npu==2.6.0 +tqdm==4.66.1 +transformers==4.53.2 +typing_extensions==4.15.0 +tzdata==2023.3 +urllib3==2.1.0 +wandb==0.23.1 +xxhash==3.4.1 +yarl==1.9.4 diff --git a/baselines/agzo/run_agzo_pangu-1b.sh b/baselines/agzo/run_agzo_pangu-1b.sh new file mode 100755 index 0000000..dff6b02 --- /dev/null +++ b/baselines/agzo/run_agzo_pangu-1b.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +source /usr/local/Ascend/ascend-toolkit/set_env.sh +set -euo pipefail + +TASK_NAME="SST2" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE. +SCRIPT_DIR="" # where the ZOLLM-npu repo is located +LOG_DIR="${SCRIPT_DIR}/log" +TIMESTAMP="$(date +%Y%m%d_%H%M%S)" +LOG_FILE="${LOG_DIR}/${TIMESTAMP}_agzo_${TASK_NAME}_pangu-1b.log" +export NPU_ID=0 # the NPU ID to use +export ASCEND_DEVICE_ID=${NPU_ID} +export ASCEND_VISIBLE_DEVICES=${NPU_ID} +export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID} +export NPU_VISIBLE_DEVICES=${NPU_ID} + +mkdir -p "${LOG_DIR}" + +source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path +conda activate zollm + +cd "${SCRIPT_DIR}" + +nohup python zo-bench/run.py \ + --trainer=agzo \ + --model_name=FreedomIntelligence/openPangu-Embedded-1B \ + --task_name=${TASK_NAME} \ + --train_as_classification \ + --perturbation_mode=two_side \ + --zo_eps=1e-7 \ + --learning_rate=1e-7 \ + --num_train_epochs=5 \ + --per_device_train_batch_size=16 \ + --eval_strategy=steps \ + --eval_steps=500 \ + --save_steps=500 \ + --max_steps=20000 \ + --logging_steps=10 \ + --num_eval=1000 \ + --num_train=1000 \ + --num_dev=500 \ + --train_set_seed=0 \ + --lr_scheduler_type=constant \ + --output_dir=result/${TASK_NAME}-agzo-pangu-1b \ + > "${LOG_FILE}" 2>&1 & + +echo "已启动agzo训练,日志存储于: ${LOG_FILE}" + diff --git a/baselines/agzo/run_compatible.py b/baselines/agzo/run_compatible.py new file mode 100644 index 0000000..6c24713 --- /dev/null +++ b/baselines/agzo/run_compatible.py @@ -0,0 +1,7 @@ +"""Modern task adapter calling pinned official numerical methods; not the original Trainer.""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'src')) +from experiments_codebase.runner import main +if __name__ == '__main__': + main(forced_method='agzo') diff --git a/baselines/agzo/run_fo_pangu-1b.sh b/baselines/agzo/run_fo_pangu-1b.sh new file mode 100644 index 0000000..cd23c5f --- /dev/null +++ b/baselines/agzo/run_fo_pangu-1b.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +source /usr/local/Ascend/ascend-toolkit/set_env.sh +set -euo pipefail + +TASK_NAME="WIC" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE. +SCRIPT_DIR="" # where the ZOLLM-npu repo is located +LOG_DIR="${SCRIPT_DIR}/log" +TIMESTAMP="$(date +%Y%m%d_%H%M%S)" +LOG_FILE="${LOG_DIR}/${TIMESTAMP}_fo_${TASK_NAME}_pangu-1b.log" +export NPU_ID=0 # the NPU ID to use +export ASCEND_DEVICE_ID=${NPU_ID} +export ASCEND_VISIBLE_DEVICES=${NPU_ID} +export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID} +export NPU_VISIBLE_DEVICES=${NPU_ID} + +mkdir -p "${LOG_DIR}" + +source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path +conda activate zollm + +cd "${SCRIPT_DIR}" + +nohup python zo-bench/run.py \ + --trainer=sgd \ + --model_name=FreedomIntelligence/openPangu-Embedded-1B \ + --task_name=${TASK_NAME} \ + --train_as_classification \ + --num_train_epochs=5 \ + --per_device_train_batch_size=8 \ + --learning_rate=5e-6 \ + --weight_decay=0 \ + --lr_scheduler_type=constant \ + --eval_strategy=steps \ + --eval_steps=25 \ + --max_steps=1000 \ + --logging_steps=10 \ + --num_eval=638 \ + --num_train=1000 \ + --num_dev=500 \ + --train_set_seed=0 \ + --output_dir=result/${TASK_NAME}-fo-sgd-pangu-1b \ + > "${LOG_FILE}" 2>&1 & + +echo "已启动fo训练,日志存储于: ${LOG_FILE}" \ No newline at end of file diff --git a/baselines/agzo/run_icl_pangu-1b.sh b/baselines/agzo/run_icl_pangu-1b.sh new file mode 100644 index 0000000..ac57603 --- /dev/null +++ b/baselines/agzo/run_icl_pangu-1b.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +source /usr/local/Ascend/ascend-toolkit/set_env.sh +set -euo pipefail + +TASK_NAME="Copa" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE. +SCRIPT_DIR="" # where the ZOLLM-npu repo is located +LOG_DIR="${SCRIPT_DIR}/log" +TIMESTAMP="$(date +%Y%m%d_%H%M%S)" +LOG_FILE="${LOG_DIR}/${TIMESTAMP}_icl5_${TASK_NAME}_pangu-1b.log" +export NPU_ID=1 # the NPU ID to use +export ASCEND_DEVICE_ID=${NPU_ID} +export ASCEND_VISIBLE_DEVICES=${NPU_ID} +export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID} +export NPU_VISIBLE_DEVICES=${NPU_ID} + +mkdir -p "${LOG_DIR}" + +source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path +conda activate zollm + +cd "${SCRIPT_DIR}" + +nohup python zo-bench/run.py \ + --trainer=none \ + --model_name=FreedomIntelligence/openPangu-Embedded-1B \ + --task_name=${TASK_NAME} \ + --train_as_classification \ + --num_train=5 \ + --num_eval=1000 \ + --train_set_seed=0 \ + --output_dir=result/${TASK_NAME}-icl5-pangu-1b \ + > "${LOG_FILE}" 2>&1 & + +echo "已启动 5-shot ICL 评测,日志存储于: ${LOG_FILE}" + + diff --git a/baselines/agzo/run_lozo_pangu-1b.sh b/baselines/agzo/run_lozo_pangu-1b.sh new file mode 100755 index 0000000..bafc4c3 --- /dev/null +++ b/baselines/agzo/run_lozo_pangu-1b.sh @@ -0,0 +1,47 @@ +#!/usr/bin/env bash +source /usr/local/Ascend/ascend-toolkit/set_env.sh +set -euo pipefail + +TASK_NAME="SST2" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE. +SCRIPT_DIR="" # where the ZOLLM-npu repo is located +LOG_DIR="${SCRIPT_DIR}/log" +TIMESTAMP="$(date +%Y%m%d_%H%M%S)" +LOG_FILE="${LOG_DIR}/${TIMESTAMP}_lozo_${TASK_NAME}_pangu-1b.log" +export NPU_ID=0 # the NPU ID to use +export ASCEND_DEVICE_ID=${NPU_ID} +export ASCEND_VISIBLE_DEVICES=${NPU_ID} +export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID} +export NPU_VISIBLE_DEVICES=${NPU_ID} + +mkdir -p "${LOG_DIR}" + +source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path +conda activate zollm + +cd "${SCRIPT_DIR}" + +nohup python zo-bench/run.py \ + --trainer=lozo \ + --lozo_rank=1 \ + --model_name=FreedomIntelligence/openPangu-Embedded-1B \ + --task_name=${TASK_NAME} \ + --train_as_classification \ + --perturbation_mode=two_side \ + --zo_eps=1e-7 \ + --learning_rate=5e-7 \ + --num_train_epochs=5 \ + --per_device_train_batch_size=16 \ + --max_steps=20000 \ + --logging_steps=10 \ + --eval_strategy=steps \ + --eval_steps=500 \ + --num_eval=1000 \ + --num_train=1000 \ + --num_dev=500 \ + --train_set_seed=0 \ + --lr_scheduler_type=constant \ + --output_dir=result/${TASK_NAME}-lozo-pangu-1b \ + > "${LOG_FILE}" 2>&1 & + +echo "已启动lozo训练,日志存储于: ${LOG_FILE}" + diff --git a/baselines/agzo/run_zeroshot_pangu-1b.sh b/baselines/agzo/run_zeroshot_pangu-1b.sh new file mode 100644 index 0000000..85b56f3 --- /dev/null +++ b/baselines/agzo/run_zeroshot_pangu-1b.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +source /usr/local/Ascend/ascend-toolkit/set_env.sh +set -euo pipefail + +TASK_NAME="Copa" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE. +SCRIPT_DIR="" # where the ZOLLM-npu repo is located +LOG_DIR="${SCRIPT_DIR}/log" +TIMESTAMP="$(date +%Y%m%d_%H%M%S)" +LOG_FILE="${LOG_DIR}/${TIMESTAMP}_zeroshot_${TASK_NAME}_pangu-1b.log" +export NPU_ID=0 # the NPU ID to use +export ASCEND_DEVICE_ID=${NPU_ID} +export ASCEND_VISIBLE_DEVICES=${NPU_ID} +export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID} +export NPU_VISIBLE_DEVICES=${NPU_ID} + +mkdir -p "${LOG_DIR}" + +source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path +conda activate zollm + +cd "${SCRIPT_DIR}" + +nohup python zo-bench/run.py \ + --trainer=none \ + --model_name=FreedomIntelligence/openPangu-Embedded-1B \ + --task_name=${TASK_NAME} \ + --train_as_classification \ + --num_train=0 \ + --num_eval=1000 \ + --train_set_seed=0 \ + --output_dir=result/${TASK_NAME}-zeroshot-pangu-1b \ + > "${LOG_FILE}" 2>&1 & + +echo "已启动 zero-shot 评测,日志存储于: ${LOG_FILE}" + + diff --git a/baselines/agzo/run_zo_sgd_pangu-1b.sh b/baselines/agzo/run_zo_sgd_pangu-1b.sh new file mode 100644 index 0000000..30b594a --- /dev/null +++ b/baselines/agzo/run_zo_sgd_pangu-1b.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +source /usr/local/Ascend/ascend-toolkit/set_env.sh +set -euo pipefail + +TASK_NAME="Copa" # can be changed to other tasks, e.g., BoolQ, RTE, SST2, Copa, CB, RTE. +SCRIPT_DIR="" # where the ZOLLM-npu repo is located +LOG_DIR="${SCRIPT_DIR}/log" +TIMESTAMP="$(date +%Y%m%d_%H%M%S)" +LOG_FILE="${LOG_DIR}/${TIMESTAMP}_zosgd_${TASK_NAME}_pangu-1b.log" +export NPU_ID=0 # the NPU ID to use +export ASCEND_DEVICE_ID=${NPU_ID} +export ASCEND_VISIBLE_DEVICES=${NPU_ID} +export ASCEND_RT_VISIBLE_DEVICES=${NPU_ID} +export NPU_VISIBLE_DEVICES=${NPU_ID} + +mkdir -p "${LOG_DIR}" + +source /home/xxx/anaconda3/etc/profile.d/conda.sh # change to your anaconda path or miniconda path +conda activate zollm + +cd "${SCRIPT_DIR}" + +nohup python zo-bench/run.py \ + --trainer=zo_sgd \ + --model_name=FreedomIntelligence/openPangu-Embedded-1B \ + --task_name=${TASK_NAME} \ + --train_as_classification \ + --perturbation_mode=two_side \ + --zo_eps=1e-7 \ + --learning_rate=1e-7 \ + --num_train_epochs=5 \ + --per_device_train_batch_size=16 \ + --max_steps=20000 \ + --logging_steps=10 \ + --eval_strategy=steps \ + --eval_steps=500 \ + --num_eval=1000 \ + --num_train=300 \ + --num_dev=100 \ + --train_set_seed=0 \ + --lr_scheduler_type=constant \ + --output_dir=result/${TASK_NAME}-zo-sgd-pangu-1b \ + > "${LOG_FILE}" 2>&1 & + +echo "已启动zo_sgd训练,日志存储于: ${LOG_FILE}" + diff --git a/baselines/agzo/uv.lock b/baselines/agzo/uv.lock new file mode 100644 index 0000000..8ae14cc --- /dev/null +++ b/baselines/agzo/uv.lock @@ -0,0 +1,1682 @@ +version = 1 +revision = 3 +requires-python = "==3.11.*" +resolution-markers = [ + "sys_platform == 'linux' and extra != 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native'", + "sys_platform == 'win32' and extra != 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native'", + "sys_platform == 'emscripten' and extra != 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32' and extra != 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native'", + "sys_platform == 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra != 'group-24-official-agzo-experiment-native'", + "sys_platform == 'win32' and extra == 'group-24-official-agzo-experiment-modern' and extra != 'group-24-official-agzo-experiment-native'", + "sys_platform == 'emscripten' and extra == 'group-24-official-agzo-experiment-modern' and extra != 'group-24-official-agzo-experiment-native'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32' and extra == 'group-24-official-agzo-experiment-modern' and extra != 'group-24-official-agzo-experiment-native'", + "sys_platform == 'linux' and extra != 'group-24-official-agzo-experiment-modern' and extra != 'group-24-official-agzo-experiment-native'", + "sys_platform != 'linux' and extra != 'group-24-official-agzo-experiment-modern' and extra != 'group-24-official-agzo-experiment-native'", +] +conflicts = [[ + { package = "official-agzo-experiment", group = "modern" }, + { package = "official-agzo-experiment", group = "native" }, +]] + +[[package]] +name = "accelerate" +version = "1.12.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyyaml" }, + { name = "safetensors" }, + { name = "torch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4a/8e/ac2a9566747a93f8be36ee08532eb0160558b07630a081a6056a9f89bf1d/accelerate-1.12.0.tar.gz", hash = "sha256:70988c352feb481887077d2ab845125024b2a137a5090d6d7a32b57d03a45df6", size = 398399, upload-time = "2025-11-21T11:27:46.973Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/d2/c581486aa6c4fbd7394c23c47b83fa1a919d34194e16944241daf9e762dd/accelerate-1.12.0-py3-none-any.whl", hash = "sha256:3e2091cd341423207e2f084a6654b1efcd250dc326f2a37d6dde446e07cabb11", size = 380935, upload-time = "2025-11-21T11:27:44.522Z" }, +] + +[[package]] +name = "aiohappyeyeballs" +version = "2.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/f4/eec0465c2f67b2664688d0240b3212d5196fd89e741df67ddb81f8d35658/aiohappyeyeballs-2.7.1.tar.gz", hash = "sha256:065665c041c42a5938ed220bdcd7230f22527fbec085e1853d2402c8a3615d9d", size = 24757, upload-time = "2026-07-01T17:11:55.501Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/43/1947f06babed6b3f1d7f38b0c767f52df66bfb2bc10b468c4a7de9eceff2/aiohappyeyeballs-2.7.1-py3-none-any.whl", hash = "sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472", size = 15038, upload-time = "2026-07-01T17:11:54.055Z" }, +] + +[[package]] +name = "aiohttp" +version = "3.14.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohappyeyeballs" }, + { name = "aiosignal" }, + { name = "attrs" }, + { name = "frozenlist" }, + { name = "multidict" }, + { name = "propcache" }, + { name = "typing-extensions" }, + { name = "yarl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6c/4c/bdccd81e9ee225b69c60e7766c9a5b05364f118f4d383713b89a682d772d/aiohttp-3.14.5.tar.gz", hash = "sha256:5558a7f5a05af9ecf744af91e5baefc436f93c9333e656c27ec253f9a6bbe178", size = 8078052, upload-time = "2026-10-11T01:05:12.408Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d8/f3/8997f18890a92c79f77fcfbb4f78ca17c2d4ab109e9eb6d31b4e9de194a0/aiohttp-3.14.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d51db97c96384fbfcaf8f4c65922183a68b94f891c3c10c862ef5f6df2adbb1f", size = 832358, upload-time = "2026-10-11T00:59:42.195Z" }, + { url = "https://files.pythonhosted.org/packages/8e/42/084651e9efb5cadb99265f786df60f2a7b353cead7bfd2c87003cb4867ad/aiohttp-3.14.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ae53924aa853a7a2ca20ed4142c7c6b56338e4d4cd999e2980075b9efc2e257a", size = 559636, upload-time = "2026-10-11T00:59:43.677Z" }, + { url = "https://files.pythonhosted.org/packages/3d/fe/92838944e601f0fe195fd3f3ada37e29fbee3d19bfd323fe15937ec79d36/aiohttp-3.14.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a2c473a355f9239efcb72c92d5abfd8fcdb0cc78c8e9af607e72ca12dbb36593", size = 552588, upload-time = "2026-10-11T00:59:45.592Z" }, + { url = "https://files.pythonhosted.org/packages/8f/b8/dd9b95c5c20ceae1b47738e656bd79e9883e3117a9cc8b143901eb604e9a/aiohttp-3.14.5-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:32e8fa6644e541fcd7e02430588c7fc93b602c1778ea0bc345505db76b61cfb4", size = 1928224, upload-time = "2026-10-11T00:59:47.294Z" }, + { url = "https://files.pythonhosted.org/packages/c6/47/70010cd2ba8746968d53d433ff328c33f06a66c99da5f3de759c64a6b2eb/aiohttp-3.14.5-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:579f97d5120f2971876d2ddca2968135f6944d00c44c3a6590ad7d86ca9b403f", size = 1877674, upload-time = "2026-10-11T00:59:49.472Z" }, + { url = "https://files.pythonhosted.org/packages/c5/a1/b026f071dbd87f0bdba86b92d47e46f3899e3ad7143b6e0fe7e7887090b4/aiohttp-3.14.5-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:24409db442e2fb6e766bc7f3943851a8381dec3098140e43bb2e843b79e31b12", size = 1985850, upload-time = "2026-10-11T00:59:51.296Z" }, + { url = "https://files.pythonhosted.org/packages/36/d1/f7b6f6f8c3cb5a71b53baeddc2e70c224c28b12a23a55c42994c504019b7/aiohttp-3.14.5-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5e8f97c0488ffda3082766ac0f2c8150a9a58c4d05788330e479cfd449b37939", size = 2105471, upload-time = "2026-10-11T00:59:53.191Z" }, + { url = "https://files.pythonhosted.org/packages/42/74/2a2b22953de15c6c8a80debf26db3047e4e8a5a5db6dd7c2c6c01eec0605/aiohttp-3.14.5-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50a195903119008fe9cc68710535eb37f556ffffd6a7759afe70a2c145587045", size = 1929915, upload-time = "2026-10-11T00:59:55.609Z" }, + { url = "https://files.pythonhosted.org/packages/33/ad/f80e8d33933d0eacd0217efa3b7fb32c9f48ed480ed0db53cf9948bf474f/aiohttp-3.14.5-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0133c3c3b54a0bf1e71fa5c1ad95c93f07fd54e24ef1fe182f5122e1573d2bf1", size = 1773832, upload-time = "2026-10-11T00:59:57.611Z" }, + { url = "https://files.pythonhosted.org/packages/04/a4/0273d239f3e3bb69438f209c64c82e1f98dc60d5db264795e41f7dd05dcb/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c172db893e516e1358e65a95ee20b7ce7173963eefe318b6ab2a2220688b999e", size = 1901001, upload-time = "2026-10-11T01:00:00.605Z" }, + { url = "https://files.pythonhosted.org/packages/16/ed/7dd439d26c654645bc34ca3c9a822fc11c1c51801fed1cefdfe1cc41c1f6/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:f2a7966bda23dd85051f1661ce0ace38d6890e05ec6c357ecae9d2479cba377e", size = 1907218, upload-time = "2026-10-11T01:00:02.699Z" }, + { url = "https://files.pythonhosted.org/packages/32/dd/86249c3b8248562a17fd3e22ee0c164378d65766f01aceef62cf52783710/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:4887d130a7bbfed3a85493bb5a25e5b5b558d40c1d986dd16970d2bb26d63793", size = 1958650, upload-time = "2026-10-11T01:00:04.851Z" }, + { url = "https://files.pythonhosted.org/packages/bc/0b/ca4d53d68f683ce195807fd0aeb063bf6d1c6b39343fff234c9524e8d5a9/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:225c579c23b68b343cccea27a7e06e3bd8ec23a09c30b427eb3f1e4ca6239b20", size = 1760057, upload-time = "2026-10-11T01:00:06.978Z" }, + { url = "https://files.pythonhosted.org/packages/6b/42/005437ffd7fa56c2ce3347add40404b654a32754ce91f2e2a14b9e5ab2bc/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:ab52d8f1fc1b64821c1fbad64a647ed6203627004059a6d1ed4f0858a1499703", size = 1978081, upload-time = "2026-10-11T01:00:08.868Z" }, + { url = "https://files.pythonhosted.org/packages/03/71/3a5b66fe1b7b23d3c6524350817ed55de5feb7fbb4cccba7cbe044d118dd/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:cb131d775a1573c1aee66656bd78b023577bbdb6cb8349a07773bd4f73e68a6e", size = 1922954, upload-time = "2026-10-11T01:00:11.035Z" }, + { url = "https://files.pythonhosted.org/packages/69/84/d08a554f281d42fd7c6b2b6dd7738f3e3a7a9f657ddd87e11ca2091cdfe3/aiohttp-3.14.5-cp311-cp311-win32.whl", hash = "sha256:e87046c8ff77a8decdb6a41d8ab25824b47531b2da933aeab0c1e21c7acff329", size = 488101, upload-time = "2026-10-11T01:00:12.933Z" }, + { url = "https://files.pythonhosted.org/packages/0f/15/52b5e65f02b33686ae49f1518548ae4f5a7adaf31d9d3c54fa12a143137b/aiohttp-3.14.5-cp311-cp311-win_amd64.whl", hash = "sha256:6f275c11d1aa6d4c458e05a68be084efe3c55a113d99e3f46a318098e52948fc", size = 512575, upload-time = "2026-10-11T01:00:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/b0/b9/bb75012635f3defb0f7cbb7c4ae391e36bb9cb3fbdca3b9944e2ebebf743/aiohttp-3.14.5-cp311-cp311-win_arm64.whl", hash = "sha256:b032a0023eb41d768ce77d83210ab2a3c389bc0b09313273c7e1eca48c10a755", size = 493179, upload-time = "2026-10-11T01:00:16.961Z" }, + { url = "https://files.pythonhosted.org/packages/68/30/173960c42b05a6c59f7558e4b12a4b0d9ba376cf6aa9bde7f9e08a30ca8d/aiohttp-3.14.5-py3-none-any.whl", hash = "sha256:efc21a454892828368b11c2c780de0ff8bc991f73f6b99c6b66e56205470929b", size = 279517, upload-time = "2026-10-11T01:05:08.523Z" }, +] + +[[package]] +name = "aiosignal" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "frozenlist" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, +] + +[[package]] +name = "annotated-types" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "certifi" +version = "2026.10.23" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/67/6a0b94a7960d5e1b5eacd2fb529f3fccc47db4644f7f0a7cfdcfc3be578a/charset_normalizer-3.5.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6", size = 370642, upload-time = "2026-09-30T04:35:06.91Z" }, + { url = "https://files.pythonhosted.org/packages/fb/94/01009e13b94041599004edf32e56e382c24e570f60f79bab8efe45cfe1eb/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5", size = 259280, upload-time = "2026-09-30T04:35:08.448Z" }, + { url = "https://files.pythonhosted.org/packages/66/85/3b5358f60a13210f0b67d3755c168ef758701b021e655d88d4da28554467/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74", size = 245335, upload-time = "2026-09-30T04:35:10.104Z" }, + { url = "https://files.pythonhosted.org/packages/74/75/77c1c479b09ecd751d1e767b251ea5c14d4d50ff757bf404afab2692f600/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab", size = 291707, upload-time = "2026-09-30T04:35:11.575Z" }, + { url = "https://files.pythonhosted.org/packages/0b/0d/363f78cacb70f58f15f4b083961bbd9d292f335d3f5c66fc4f1cfe69cb90/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c", size = 286747, upload-time = "2026-09-30T04:35:13.022Z" }, + { url = "https://files.pythonhosted.org/packages/e4/ed/cf505d3011ffceb12c2067a7a5d3cfe92b875d4d44bb0ff0d69375e2c184/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f", size = 269972, upload-time = "2026-09-30T04:35:14.606Z" }, + { url = "https://files.pythonhosted.org/packages/15/d8/f0a93a431d170e7ca681d4f6650fee3de934d18560e474e7267eb4b0f987/charset_normalizer-3.5.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288", size = 269339, upload-time = "2026-09-30T04:35:16.087Z" }, + { url = "https://files.pythonhosted.org/packages/86/bd/9b2bd1c5b7af02462c9752d33994834ff972a96b4c483eefde9e594488e2/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400", size = 261683, upload-time = "2026-09-30T04:35:17.488Z" }, + { url = "https://files.pythonhosted.org/packages/76/a5/cac540ab0fd61f3fec88ad3dbb64509e71424593d73cfdfff5ab3e4db279/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd", size = 248143, upload-time = "2026-09-30T04:35:18.849Z" }, + { url = "https://files.pythonhosted.org/packages/71/7a/ff467301deef2089fad87f72df9e000a26a78fec7acbb18e1999371b8369/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37", size = 292358, upload-time = "2026-09-30T04:35:20.326Z" }, + { url = "https://files.pythonhosted.org/packages/ad/77/22d7e785d1e210afc2e2f58600dd1799d17a35665faf84383f002826c5f8/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac", size = 268766, upload-time = "2026-09-30T04:35:21.72Z" }, + { url = "https://files.pythonhosted.org/packages/ae/91/e8e946267f1c2d9e2bd651726e2fbd2addf02c4d36cea5069e32ca9d7bb5/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a", size = 287432, upload-time = "2026-09-30T04:35:23.273Z" }, + { url = "https://files.pythonhosted.org/packages/4e/88/7561d8a88d555e7df6623abe7c0070b4baf47549b9408783a2ae0a1a6cf7/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640", size = 272470, upload-time = "2026-09-30T04:35:24.655Z" }, + { url = "https://files.pythonhosted.org/packages/35/7e/578c702301ec036f01455f30744a08d2b42f6ab35b9b2d4bf8cae0ef2a80/charset_normalizer-3.5.2-cp311-cp311-win32.whl", hash = "sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d", size = 186688, upload-time = "2026-09-30T04:35:26.225Z" }, + { url = "https://files.pythonhosted.org/packages/e8/fc/fdf8cf52ff21cd5bf158f20978991cf985325842f74283eb6df26c8a39d8/charset_normalizer-3.5.2-cp311-cp311-win_amd64.whl", hash = "sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96", size = 214932, upload-time = "2026-09-30T04:35:27.796Z" }, + { url = "https://files.pythonhosted.org/packages/97/66/3e45a506d8110b632541faf9a9470185aa9878f1ed44020f31346c1c5e5b/charset_normalizer-3.5.2-cp311-cp311-win_arm64.whl", hash = "sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1", size = 202828, upload-time = "2026-09-30T04:35:29.259Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" }, + { url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" }, + { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" }, + { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" }, + { url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" }, +] + +[[package]] +name = "click" +version = "8.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, +] + +[[package]] +name = "cloudpickle" +version = "3.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/27/fb/576f067976d320f5f0114a8d9fa1215425441bb35627b1993e5afd8111e5/cloudpickle-3.1.2.tar.gz", hash = "sha256:7fda9eb655c9c230dab534f1983763de5835249750e85fbcef43aaa30a9a2414", size = 22330, upload-time = "2025-11-03T09:25:26.604Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/39/799be3f2f0f38cc727ee3b4f1445fe6d5e4133064ec2e4115069418a5bb6/cloudpickle-3.1.2-py3-none-any.whl", hash = "sha256:9acb47f6afd73f60dc1df93bb801b472f05ff42fa6c84167d25cb206be1fbf4a", size = 22228, upload-time = "2025-11-03T09:25:25.534Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "contourpy" +version = "1.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/91/2e/c4390a31919d8a78b90e8ecf87cd4b4c4f05a5b48d05ec17db8e5404c6f4/contourpy-1.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:709a48ef9a690e1343202916450bc48b9e51c049b089c7f79a267b46cffcdaa1", size = 288773, upload-time = "2025-07-26T12:01:02.277Z" }, + { url = "https://files.pythonhosted.org/packages/0d/44/c4b0b6095fef4dc9c420e041799591e3b63e9619e3044f7f4f6c21c0ab24/contourpy-1.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:23416f38bfd74d5d28ab8429cc4d63fa67d5068bd711a85edb1c3fb0c3e2f381", size = 270149, upload-time = "2025-07-26T12:01:04.072Z" }, + { url = "https://files.pythonhosted.org/packages/30/2e/dd4ced42fefac8470661d7cb7e264808425e6c5d56d175291e93890cce09/contourpy-1.3.3-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:929ddf8c4c7f348e4c0a5a3a714b5c8542ffaa8c22954862a46ca1813b667ee7", size = 329222, upload-time = "2025-07-26T12:01:05.688Z" }, + { url = "https://files.pythonhosted.org/packages/f2/74/cc6ec2548e3d276c71389ea4802a774b7aa3558223b7bade3f25787fafc2/contourpy-1.3.3-cp311-cp311-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e999574eddae35f1312c2b4b717b7885d4edd6cb46700e04f7f02db454e67c1", size = 377234, upload-time = "2025-07-26T12:01:07.054Z" }, + { url = "https://files.pythonhosted.org/packages/03/b3/64ef723029f917410f75c09da54254c5f9ea90ef89b143ccadb09df14c15/contourpy-1.3.3-cp311-cp311-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0bf67e0e3f482cb69779dd3061b534eb35ac9b17f163d851e2a547d56dba0a3a", size = 380555, upload-time = "2025-07-26T12:01:08.801Z" }, + { url = "https://files.pythonhosted.org/packages/5f/4b/6157f24ca425b89fe2eb7e7be642375711ab671135be21e6faa100f7448c/contourpy-1.3.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e79c1f7470158e838808d4a996fa9bac72c498e93d8ebe5119bc1e6becb0db", size = 355238, upload-time = "2025-07-26T12:01:10.319Z" }, + { url = "https://files.pythonhosted.org/packages/98/56/f914f0dd678480708a04cfd2206e7c382533249bc5001eb9f58aa693e200/contourpy-1.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:598c3aaece21c503615fd59c92a3598b428b2f01bfb4b8ca9c4edeecc2438620", size = 1326218, upload-time = "2025-07-26T12:01:12.659Z" }, + { url = "https://files.pythonhosted.org/packages/fb/d7/4a972334a0c971acd5172389671113ae82aa7527073980c38d5868ff1161/contourpy-1.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:322ab1c99b008dad206d406bb61d014cf0174df491ae9d9d0fac6a6fda4f977f", size = 1392867, upload-time = "2025-07-26T12:01:15.533Z" }, + { url = "https://files.pythonhosted.org/packages/75/3e/f2cc6cd56dc8cff46b1a56232eabc6feea52720083ea71ab15523daab796/contourpy-1.3.3-cp311-cp311-win32.whl", hash = "sha256:fd907ae12cd483cd83e414b12941c632a969171bf90fc937d0c9f268a31cafff", size = 183677, upload-time = "2025-07-26T12:01:17.088Z" }, + { url = "https://files.pythonhosted.org/packages/98/4b/9bd370b004b5c9d8045c6c33cf65bae018b27aca550a3f657cdc99acdbd8/contourpy-1.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:3519428f6be58431c56581f1694ba8e50626f2dd550af225f82fb5f5814d2a42", size = 225234, upload-time = "2025-07-26T12:01:18.256Z" }, + { url = "https://files.pythonhosted.org/packages/d9/b6/71771e02c2e004450c12b1120a5f488cad2e4d5b590b1af8bad060360fe4/contourpy-1.3.3-cp311-cp311-win_arm64.whl", hash = "sha256:15ff10bfada4bf92ec8b31c62bf7c1834c244019b4a33095a68000d7075df470", size = 193123, upload-time = "2025-07-26T12:01:19.848Z" }, + { url = "https://files.pythonhosted.org/packages/a5/29/8dcfe16f0107943fa92388c23f6e05cff0ba58058c4c95b00280d4c75a14/contourpy-1.3.3-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:cd5dfcaeb10f7b7f9dc8941717c6c2ade08f587be2226222c12b25f0483ed497", size = 278809, upload-time = "2025-07-26T12:02:52.74Z" }, + { url = "https://files.pythonhosted.org/packages/85/a9/8b37ef4f7dafeb335daee3c8254645ef5725be4d9c6aa70b50ec46ef2f7e/contourpy-1.3.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:0c1fc238306b35f246d61a1d416a627348b5cf0648648a031e14bb8705fcdfe8", size = 261593, upload-time = "2025-07-26T12:02:54.037Z" }, + { url = "https://files.pythonhosted.org/packages/0a/59/ebfb8c677c75605cc27f7122c90313fd2f375ff3c8d19a1694bda74aaa63/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f9aad7de812d6541d29d2bbf8feb22ff7e1c299523db288004e3157ff4674e", size = 302202, upload-time = "2025-07-26T12:02:55.947Z" }, + { url = "https://files.pythonhosted.org/packages/3c/37/21972a15834d90bfbfb009b9d004779bd5a07a0ec0234e5ba8f64d5736f4/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5ed3657edf08512fc3fe81b510e35c2012fbd3081d2e26160f27ca28affec989", size = 329207, upload-time = "2025-07-26T12:02:57.468Z" }, + { url = "https://files.pythonhosted.org/packages/0c/58/bd257695f39d05594ca4ad60df5bcb7e32247f9951fd09a9b8edb82d1daa/contourpy-1.3.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:3d1a3799d62d45c18bafd41c5fa05120b96a28079f2393af559b843d1a966a77", size = 225315, upload-time = "2025-07-26T12:02:58.801Z" }, +] + +[[package]] +name = "cuda-bindings" +version = "13.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-pathfinder", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/09/74e159fbe67b081cca842871addce6d2b493f9bb48ce85124f023eb5f1c9/cuda_bindings-13.5.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71c15ed97099a8ef416515d80ddd10770e0f6339234e16855a526d2896516631", size = 7434875, upload-time = "2026-11-05T12:05:50.666Z" }, + { url = "https://files.pythonhosted.org/packages/f6/0d/ca24317a31118b90fd60126aec5c0a92a191a7fdd39524032d43328b49b5/cuda_bindings-13.5.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:08b7e8d674c3266facb00453a7e34ea7d3ea965c2f594bb728f269f45f39fbe2", size = 8390178, upload-time = "2026-11-05T12:05:52.653Z" }, + { url = "https://files.pythonhosted.org/packages/a6/7b/455b204f07dcbac810bc48b558d3febff8adb81b6036efac315bd5a4aa33/cuda_bindings-13.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:0d7a5d92be00b2a618fd7c62482f6c69584fd5ac498193b236600810d7ebaf74", size = 8097474, upload-time = "2026-11-05T12:05:59.207Z" }, + { url = "https://files.pythonhosted.org/packages/a0/70/9ab184a434f47dacedd47a49901c0be1a81080e8b57d1d3f0e5445bb1277/cuda_bindings-13.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:4d850299e6ba1ca9caec78b3d87b6b7590ed1d6c9a404272798f40b1e19e3f24", size = 7010633, upload-time = "2026-11-05T12:06:00.913Z" }, +] + +[[package]] +name = "cuda-pathfinder" +version = "1.8.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/9e/08555797c979322def080814686417ea93f66d38f5c48ebab6867a85a21e/cuda_pathfinder-1.8.6-py3-none-any.whl", hash = "sha256:bf6b3b06323cf95a11d671818392da5da23ddbbb4dfc4b77ca10622783c25980", size = 62603, upload-time = "2026-11-05T21:22:51.229Z" }, +] + +[[package]] +name = "cuda-toolkit" +version = "13.0.3.0" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/c7/a79086a62c98befcdb8349656c6f114e2db3b8b2422f6e25c97a7f2a9a3c/cuda_toolkit-13.0.3.0-py2.py3-none-any.whl", hash = "sha256:d693caaa261214ddd7dbb60d68e71cbed884e68c2be7509778f3051da0b91c3f", size = 2512, upload-time = "2026-04-14T00:50:08.173Z" }, +] + +[package.optional-dependencies] +cublas = [ + { name = "nvidia-cublas", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +cudart = [ + { name = "nvidia-cuda-runtime", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +cufft = [ + { name = "nvidia-cufft", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +cufile = [ + { name = "nvidia-cufile", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +cupti = [ + { name = "nvidia-cuda-cupti", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +curand = [ + { name = "nvidia-curand", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +cusolver = [ + { name = "nvidia-cublas", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-cusolver", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-cusparse", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +cusparse = [ + { name = "nvidia-cusparse", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +nvjitlink = [ + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +nvrtc = [ + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +nvtx = [ + { name = "nvidia-nvtx", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] + +[[package]] +name = "cycler" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, +] + +[[package]] +name = "datasets" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "aiohttp" }, + { name = "dill" }, + { name = "filelock" }, + { name = "fsspec", extra = ["http"], marker = "extra == 'group-24-official-agzo-experiment-native'" }, + { name = "huggingface-hub" }, + { name = "multiprocess" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pyarrow", version = "17.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "xxhash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e5/a5/38719e5cff7aa0537a6be37d21cc1fdd7096e9565e8fce2d46a822e10b5b/datasets-2.21.0.tar.gz", hash = "sha256:998f85a8460f1bd982e5bd058f8a0808eef424249e3df1e8cdd594ccd0dc8ba2", size = 2215317, upload-time = "2024-08-14T06:40:44.314Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/b3/33c4ad44fa020e3757e9b2fad8a5de53d9079b501e6bbc45bdd18f82f893/datasets-2.21.0-py3-none-any.whl", hash = "sha256:25e4e097110ce28824b746a107727ada94024cba11db8bc588d468414692b65a", size = 527251, upload-time = "2024-08-14T06:40:39.612Z" }, +] + +[[package]] +name = "datasets" +version = "3.6.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "dill" }, + { name = "filelock" }, + { name = "fsspec", extra = ["http"], marker = "extra == 'group-24-official-agzo-experiment-modern'" }, + { name = "huggingface-hub" }, + { name = "multiprocess" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pyarrow", version = "20.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "xxhash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1a/89/d3d6fef58a488f8569c82fd293ab7cbd4250244d67f425dcae64c63800ea/datasets-3.6.0.tar.gz", hash = "sha256:1b2bf43b19776e2787e181cfd329cb0ca1a358ea014780c3581e0f276375e041", size = 569336, upload-time = "2025-05-07T15:15:02.659Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/34/a08b0ee99715eaba118cbe19a71f7b5e2425c2718ef96007c325944a1152/datasets-3.6.0-py3-none-any.whl", hash = "sha256:25000c4a2c0873a710df127d08a202a06eab7bf42441a6bc278b499c2f72cd1b", size = 491546, upload-time = "2025-05-07T15:14:59.742Z" }, +] + +[[package]] +name = "dill" +version = "0.3.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/17/4d/ac7ffa80c69ea1df30a8aa11b3578692a5118e7cd1aa157e3ef73b092d15/dill-0.3.8.tar.gz", hash = "sha256:3ebe3c479ad625c4553aca177444d89b486b1d84982eeacded644afc0cf797ca", size = 184847, upload-time = "2024-01-27T23:42:16.145Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/7a/cef76fd8438a42f96db64ddaa85280485a9c395e7df3db8158cfec1eee34/dill-0.3.8-py3-none-any.whl", hash = "sha256:c36ca9ffb54365bdd2f8eb3eff7d2a21237f8452b57ace88b1ac615b7e815bd7", size = 116252, upload-time = "2024-01-27T23:42:14.239Z" }, +] + +[[package]] +name = "einops" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e5/81/df4fbe24dff8ba3934af99044188e20a98ed441ad17a274539b74e82e126/einops-0.8.1.tar.gz", hash = "sha256:de5d960a7a761225532e0f1959e5315ebeafc0cd43394732f103ca44b9837e84", size = 54805, upload-time = "2025-02-09T03:17:00.434Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/62/9773de14fe6c45c23649e98b83231fffd7b9892b6cf863251dc2afa73643/einops-0.8.1-py3-none-any.whl", hash = "sha256:919387eb55330f5757c6bea9165c5ff5cfe63a642682ea788a6d472576d81737", size = 64359, upload-time = "2025-02-09T03:17:01.998Z" }, +] + +[[package]] +name = "filelock" +version = "4.2.10" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/cf/05bcdacabdc0aec7dc8e19d76281bd82325df62dae3b6430e9ba57397689/filelock-4.2.10.tar.gz", hash = "sha256:fcc3c0cb8bfe7f4b3bb0e231c04b15dbad068cb3c2515f343d8fde4dce93bd5d", size = 670595, upload-time = "2026-11-09T18:58:00.54Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/90/5d0096a325aa0f83ba7a3968bfb485b67e32c947bdf9cd0fcb4b485be718/filelock-4.2.10-py3-none-any.whl", hash = "sha256:9479aaeb4db20b5a53e3da28493edd24720b66b8a0b84030aa56ccdf243d6857", size = 218040, upload-time = "2026-11-09T18:57:59.088Z" }, +] + +[[package]] +name = "fonttools" +version = "4.68.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0c/b5/672312ae80ce8b8eb9779c56052a24c8f36652aa7293a1a420553bcf03e5/fonttools-4.68.0.tar.gz", hash = "sha256:73294e233070f71e2b3653b6bd8564af676d57f26d075761fb06d1ab2e4a7a5d", size = 3848583, upload-time = "2026-10-27T16:30:26.451Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/21/51/7c725115425be01aa0fac87eb38f8e8c8c04de80d49a99b08a74898b25ee/fonttools-4.68.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:362443ab355701d6fd26b10d022cd6c8456e1e248f80103c44cbe5ef0228f87f", size = 3135538, upload-time = "2026-10-27T16:28:02.169Z" }, + { url = "https://files.pythonhosted.org/packages/2e/d5/0a04cbde3e3e997d7bda216f77566bea2eb79018e4ca2adb13ce3c9a7206/fonttools-4.68.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:664dfa7a4869b3c827dfc2c38dbbb7a58d53e97933d1bd51ee6729792ee73d50", size = 2632853, upload-time = "2026-10-27T16:28:04.962Z" }, + { url = "https://files.pythonhosted.org/packages/d8/8c/aa4c7b38f4814d6bcb3378276bff802c9610a1227f1d24965a9f23f0a48c/fonttools-4.68.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:53f2387d7e3816763f30e08d14263be18e28ead53d4dc20a82f9280d0c99d88a", size = 5530571, upload-time = "2026-10-27T16:28:06.952Z" }, + { url = "https://files.pythonhosted.org/packages/00/01/e0f5b3d648ddd2eae35c4bcddcc2cffc059279e9d2cdb325bed10458f606/fonttools-4.68.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4b9c89b5876f1a74b1341632dfaf4c4c2be565d76c060445df401ebe7a4ceefa", size = 5493829, upload-time = "2026-10-27T16:28:09.127Z" }, + { url = "https://files.pythonhosted.org/packages/ea/bb/9c5568659275c86e6eebb060d98e8ea77c56fb78ee77ea5654a057f72bde/fonttools-4.68.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:054a4d5de7e1f973ab9789e9ae3f20238774783ca9bf7ee0359aebae4de9400c", size = 5496373, upload-time = "2026-10-27T16:28:11.378Z" }, + { url = "https://files.pythonhosted.org/packages/b0/32/0a35ffd35bfc1b0a754563a45500e87d651e0f336cf006a25e0bc460ba2f/fonttools-4.68.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b5a015b322275d3d745b06d5e69cf74ef4b1ce2dae02afbe4826cb186d8527a3", size = 5634196, upload-time = "2026-10-27T16:28:13.783Z" }, + { url = "https://files.pythonhosted.org/packages/93/76/3454e20f07dbe4b308b7bc99117292109bb7775a1b595ead768110144553/fonttools-4.68.0-cp311-cp311-win32.whl", hash = "sha256:bd5b047ed8f16b83d0344fef053668712ab9c88e2e46d8612ec41df83c5222e1", size = 1624232, upload-time = "2026-10-27T16:28:16.001Z" }, + { url = "https://files.pythonhosted.org/packages/46/87/4ba592099172764aa56e66919b0c3ddaf944c775433e806e36e165062095/fonttools-4.68.0-cp311-cp311-win_amd64.whl", hash = "sha256:35425bba603cf9d72c9f3c173ea6c98632164f3bdfb1ce1a3dcc928979c6ec6d", size = 1681821, upload-time = "2026-10-27T16:28:17.757Z" }, + { url = "https://files.pythonhosted.org/packages/e1/54/004f12709b21a56bb944fdca6d165b0d90cf9366143675dbc7bb46784ddd/fonttools-4.68.0-cp311-cp311-win_arm64.whl", hash = "sha256:04365b897c9ee29a048b6d4db74c75c38b70aa6d1074726fbdd7ea1a23aa8ed2", size = 1649151, upload-time = "2026-10-27T16:28:19.502Z" }, + { url = "https://files.pythonhosted.org/packages/35/74/4ea331ecc65ba05a58b1e4e8ccd604c8a15565f876dfbf93fc2a2ea2e22b/fonttools-4.68.0-py3-none-any.whl", hash = "sha256:d76f8fdcb6936f5e1045a0c9dd721a4bf11112e60d1e243bfa1d39f06a8b3104", size = 1248357, upload-time = "2026-10-27T16:30:24.389Z" }, +] + +[[package]] +name = "frozenlist" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/03/077f869d540370db12165c0aa51640a873fb661d8b315d1d4d67b284d7ac/frozenlist-1.8.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:09474e9831bc2b2199fad6da3c14c7b0fbdd377cce9d3d77131be28906cb7d84", size = 86912, upload-time = "2025-10-06T05:35:45.98Z" }, + { url = "https://files.pythonhosted.org/packages/df/b5/7610b6bd13e4ae77b96ba85abea1c8cb249683217ef09ac9e0ae93f25a91/frozenlist-1.8.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:17c883ab0ab67200b5f964d2b9ed6b00971917d5d8a92df149dc2c9779208ee9", size = 50046, upload-time = "2025-10-06T05:35:47.009Z" }, + { url = "https://files.pythonhosted.org/packages/6e/ef/0e8f1fe32f8a53dd26bdd1f9347efe0778b0fddf62789ea683f4cc7d787d/frozenlist-1.8.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:fa47e444b8ba08fffd1c18e8cdb9a75db1b6a27f17507522834ad13ed5922b93", size = 50119, upload-time = "2025-10-06T05:35:48.38Z" }, + { url = "https://files.pythonhosted.org/packages/11/b1/71a477adc7c36e5fb628245dfbdea2166feae310757dea848d02bd0689fd/frozenlist-1.8.0-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2552f44204b744fba866e573be4c1f9048d6a324dfe14475103fd51613eb1d1f", size = 231067, upload-time = "2025-10-06T05:35:49.97Z" }, + { url = "https://files.pythonhosted.org/packages/45/7e/afe40eca3a2dc19b9904c0f5d7edfe82b5304cb831391edec0ac04af94c2/frozenlist-1.8.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:957e7c38f250991e48a9a73e6423db1bb9dd14e722a10f6b8bb8e16a0f55f695", size = 233160, upload-time = "2025-10-06T05:35:51.729Z" }, + { url = "https://files.pythonhosted.org/packages/a6/aa/7416eac95603ce428679d273255ffc7c998d4132cfae200103f164b108aa/frozenlist-1.8.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8585e3bb2cdea02fc88ffa245069c36555557ad3609e83be0ec71f54fd4abb52", size = 228544, upload-time = "2025-10-06T05:35:53.246Z" }, + { url = "https://files.pythonhosted.org/packages/8b/3d/2a2d1f683d55ac7e3875e4263d28410063e738384d3adc294f5ff3d7105e/frozenlist-1.8.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:edee74874ce20a373d62dc28b0b18b93f645633c2943fd90ee9d898550770581", size = 243797, upload-time = "2025-10-06T05:35:54.497Z" }, + { url = "https://files.pythonhosted.org/packages/78/1e/2d5565b589e580c296d3bb54da08d206e797d941a83a6fdea42af23be79c/frozenlist-1.8.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c9a63152fe95756b85f31186bddf42e4c02c6321207fd6601a1c89ebac4fe567", size = 247923, upload-time = "2025-10-06T05:35:55.861Z" }, + { url = "https://files.pythonhosted.org/packages/aa/c3/65872fcf1d326a7f101ad4d86285c403c87be7d832b7470b77f6d2ed5ddc/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b6db2185db9be0a04fecf2f241c70b63b1a242e2805be291855078f2b404dd6b", size = 230886, upload-time = "2025-10-06T05:35:57.399Z" }, + { url = "https://files.pythonhosted.org/packages/a0/76/ac9ced601d62f6956f03cc794f9e04c81719509f85255abf96e2510f4265/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:f4be2e3d8bc8aabd566f8d5b8ba7ecc09249d74ba3c9ed52e54dc23a293f0b92", size = 245731, upload-time = "2025-10-06T05:35:58.563Z" }, + { url = "https://files.pythonhosted.org/packages/b9/49/ecccb5f2598daf0b4a1415497eba4c33c1e8ce07495eb07d2860c731b8d5/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:c8d1634419f39ea6f5c427ea2f90ca85126b54b50837f31497f3bf38266e853d", size = 241544, upload-time = "2025-10-06T05:35:59.719Z" }, + { url = "https://files.pythonhosted.org/packages/53/4b/ddf24113323c0bbcc54cb38c8b8916f1da7165e07b8e24a717b4a12cbf10/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:1a7fa382a4a223773ed64242dbe1c9c326ec09457e6b8428efb4118c685c3dfd", size = 241806, upload-time = "2025-10-06T05:36:00.959Z" }, + { url = "https://files.pythonhosted.org/packages/a7/fb/9b9a084d73c67175484ba2789a59f8eebebd0827d186a8102005ce41e1ba/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:11847b53d722050808926e785df837353bd4d75f1d494377e59b23594d834967", size = 229382, upload-time = "2025-10-06T05:36:02.22Z" }, + { url = "https://files.pythonhosted.org/packages/95/a3/c8fb25aac55bf5e12dae5c5aa6a98f85d436c1dc658f21c3ac73f9fa95e5/frozenlist-1.8.0-cp311-cp311-win32.whl", hash = "sha256:27c6e8077956cf73eadd514be8fb04d77fc946a7fe9f7fe167648b0b9085cc25", size = 39647, upload-time = "2025-10-06T05:36:03.409Z" }, + { url = "https://files.pythonhosted.org/packages/0a/f5/603d0d6a02cfd4c8f2a095a54672b3cf967ad688a60fb9faf04fc4887f65/frozenlist-1.8.0-cp311-cp311-win_amd64.whl", hash = "sha256:ac913f8403b36a2c8610bbfd25b8013488533e71e62b4b4adce9c86c8cea905b", size = 44064, upload-time = "2025-10-06T05:36:04.368Z" }, + { url = "https://files.pythonhosted.org/packages/5d/16/c2c9ab44e181f043a86f9a8f84d5124b62dbcb3a02c0977ec72b9ac1d3e0/frozenlist-1.8.0-cp311-cp311-win_arm64.whl", hash = "sha256:d4d3214a0f8394edfa3e303136d0575eece0745ff2b47bd2cb2e66dd92d4351a", size = 39937, upload-time = "2025-10-06T05:36:05.669Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, +] + +[[package]] +name = "fsspec" +version = "2024.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/90/b6/eba5024a9889fcfff396db543a34bef0ab9d002278f163129f9f01005960/fsspec-2024.6.1.tar.gz", hash = "sha256:fad7d7e209dd4c1208e3bbfda706620e0da5142bebbd9c384afb95b07e798e49", size = 284584, upload-time = "2024-06-27T14:35:45.467Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5e/44/73bea497ac69bafde2ee4269292fa3b41f1198f4bb7bbaaabde30ad29d4a/fsspec-2024.6.1-py3-none-any.whl", hash = "sha256:3cb443f8bcd2efb31295a5b9fdb02aee81d8452c80d28f97a6d0959e6cee101e", size = 177561, upload-time = "2024-06-27T14:35:42.023Z" }, +] + +[package.optional-dependencies] +http = [ + { name = "aiohttp" }, +] + +[[package]] +name = "gitdb" +version = "4.0.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "smmap" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/94/63b0fc47eb32792c7ba1fe1b694daec9a63620db1e313033d18140c2320a/gitdb-4.0.12.tar.gz", hash = "sha256:5ef71f855d191a3326fcfbc0d5da835f26b13fbcba60c32c21091c349ffdb571", size = 394684, upload-time = "2025-01-02T07:20:46.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/61/5c78b91c3143ed5c14207f463aecfc8f9dbb5092fb2869baf37c273b2705/gitdb-4.0.12-py3-none-any.whl", hash = "sha256:67073e15955400952c6565cc3e707c554a4eea2e428946f7a4c162fab9bd9bcf", size = 62794, upload-time = "2025-01-02T07:20:43.624Z" }, +] + +[[package]] +name = "gitpython" +version = "3.2.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "gitdb" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/ff/fee293f1ec3e1b64db6eb270e00964f29c086d769201474cedb8d1608930/gitpython-3.2.1.tar.gz", hash = "sha256:0f1229ec5c057bdabdeeda8bda4f17bda679ab33dbccc00f24e6a480553c8613", size = 241688, upload-time = "2026-10-14T12:20:20.589Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6b/50/2a923c4dc02522ff9567f07c67ed1deca6d5fa9474f4708168b8088dfa37/gitpython-3.2.1-py3-none-any.whl", hash = "sha256:d66b0832aa8755c1a84892937282df0befb16c97e5a64aeebd68be9c5e323f53", size = 231548, upload-time = "2026-10-14T12:20:18.844Z" }, +] + +[[package]] +name = "hf-xet" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" }, + { url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" }, + { url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" }, + { url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" }, + { url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" }, +] + +[[package]] +name = "huggingface-hub" +version = "0.36.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "filelock" }, + { name = "fsspec" }, + { name = "hf-xet", marker = "platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/63/4910c5fa9128fdadf6a9c5ac138e8b1b6cee4ca44bf7915bbfbce4e355ee/huggingface_hub-0.36.0.tar.gz", hash = "sha256:47b3f0e2539c39bf5cde015d63b72ec49baff67b6931c3d97f3f84532e2b8d25", size = 463358, upload-time = "2025-10-23T12:12:01.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/bd/1a875e0d592d447cbc02805fd3fe0f497714d6a2583f59d14fa9ebad96eb/huggingface_hub-0.36.0-py3-none-any.whl", hash = "sha256:7bcc9ad17d5b3f07b57c78e79d527102d08313caa278a641993acddcb894548d", size = 566094, upload-time = "2025-10-23T12:11:59.557Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "joblib" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cloudpickle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d5/1d/537ab090f302b838943a1b56497dd53059b9a9b46a074936470173a2e207/joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03", size = 327903, upload-time = "2026-08-31T09:39:04.122Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115, upload-time = "2026-08-31T09:39:02.298Z" }, +] + +[[package]] +name = "kiwisolver" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea041ef5bba3ed21a003522fa088834b069b1909981f30/kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a", size = 104395, upload-time = "2026-08-28T10:28:27.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/7b/2de6908edc668427c149af5f93112e931f87e1fa4cab80bac32c5844dccc/kiwisolver-1.5.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b3d78f7bb2b9d9a30345be1474b9aaa8685430b54afb51ba3639b5c6c11e9ed6", size = 123364, upload-time = "2026-08-28T10:25:04.359Z" }, + { url = "https://files.pythonhosted.org/packages/8a/24/e70914415c77c97be7e22c80a0740869cb7428768cc380fdcdf6703e7084/kiwisolver-1.5.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5025e36fb4fb275cef0a4e30dbb11cb4ae61d1c83deb90189cb5d7e4cafd6b55", size = 66558, upload-time = "2026-08-28T10:25:05.506Z" }, + { url = "https://files.pythonhosted.org/packages/e8/2b/8b08b11833db4d475b8ef1f36174f8d8a7abd31bedd7e794be78e8814b48/kiwisolver-1.5.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dc1a26b8e53395a01c2c611e58602fa47461f136fba7cd5542e6db6d64be1839", size = 64071, upload-time = "2026-08-28T10:25:06.7Z" }, + { url = "https://files.pythonhosted.org/packages/89/00/05c2d0369ac322d22d5c05f84b5c4a6856fa6207fbae42869108a28f0383/kiwisolver-1.5.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:95a02752aa032eef4aed01cda6d9b687c669bd0396bf4519eef8bba22a286720", size = 1438206, upload-time = "2026-08-28T10:25:08.254Z" }, + { url = "https://files.pythonhosted.org/packages/c0/05/c941a139f27438c1910d630fdc3ccfdab7c8407c72052299ead12ece086e/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:719a35fa1156db3640555f95ebb94f60a444e64d1c69626b0edef5df78eba225", size = 1248975, upload-time = "2026-08-28T10:25:10.053Z" }, + { url = "https://files.pythonhosted.org/packages/58/a1/2669ee5512e39b9d4de25faacaedf788c957f93730c5f7c63993ec4f5933/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:febcce10f2bcdbb80b4ea919238a6a4ac13dbc4c7cadbe8d5d75c3682f8b5404", size = 1266301, upload-time = "2026-08-28T10:25:11.754Z" }, + { url = "https://files.pythonhosted.org/packages/28/b8/353f52f2c7f861a9e90cd2e8f90f85b3ad03060835f823e08298d094c463/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1d852545c4d0e35a72728d072cbaa59e2fa7dd84bdf01e068d670dd0ceb58eb6", size = 1319708, upload-time = "2026-08-28T10:25:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/21/0e/14b83200eadc2c1d63b76bac01c1813bf072aecf567429f303e00b70258e/kiwisolver-1.5.1-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:2e10ae1bba1899188b33557c10d73affcc12033edd18adddb57d209039976a4c", size = 971720, upload-time = "2026-08-28T10:25:14.934Z" }, + { url = "https://files.pythonhosted.org/packages/86/91/9d43d84d23b1cbff72a142d387ead1ea03db0cba8ff86ed5335addad3cc9/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b69602970994a2ed8bbfa78c2f0394a7435226c6040489702d9f0a0ad0c07052", size = 2200119, upload-time = "2026-08-28T10:25:16.636Z" }, + { url = "https://files.pythonhosted.org/packages/ff/7c/f2bd9616f27ffb5e17cecc0baa5d0bbcee7e55aeddc0ccc871d69e2fc3ee/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d50de98e8d807dc31822fff96f50293163a62418eb65487a21b42713d72ed0b7", size = 2295005, upload-time = "2026-08-28T10:25:18.374Z" }, + { url = "https://files.pythonhosted.org/packages/ba/17/ee671b72bf8f46a08379d4392c65582541759a542428197562f2898294ad/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3221f78211074f561c44ca42eac0619828171bec15a2c4cf6f7747d07df76e8e", size = 1960982, upload-time = "2026-08-28T10:25:19.893Z" }, + { url = "https://files.pythonhosted.org/packages/2e/f7/0e26b4c05bee3bdb0f048dfa305e4fe701999ea17b51e9c616ef91035bbe/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0ba9527afc80ae3d7814ed98b6572d02bf85eaf48065678342c5f0c6dab7a8c7", size = 2464918, upload-time = "2026-08-28T10:25:21.65Z" }, + { url = "https://files.pythonhosted.org/packages/ae/62/6eb431133d30ce656ac1e5ff72fac70dd34d54c3984f4011b9ac8bf77d54/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e12dfea7f5fc2a34a9080efbf79c4c44eb380ec5b9c6fea09407e08f0d1e941d", size = 2270967, upload-time = "2026-08-28T10:25:23.643Z" }, + { url = "https://files.pythonhosted.org/packages/bf/9f/6f9e489c188200e6fb3193935501894811e8c97577c8ffe9033589bf3521/kiwisolver-1.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:1a7587dc335f2c0f5bd577fd0540bd16c66006bdb60f759a1059f025e6c4f071", size = 70744, upload-time = "2026-08-28T10:25:25.061Z" }, + { url = "https://files.pythonhosted.org/packages/c6/6d/dfc430d1d43957061599adea3f08ea982bb6f4ab601a8c974bedcf2ba850/kiwisolver-1.5.1-cp311-cp311-win_arm64.whl", hash = "sha256:e4e4523d6f336708d732516e6cfca7796cf3d96c9474eb5aecf6165f2f1fefc3", size = 68404, upload-time = "2026-08-28T10:25:26.186Z" }, + { url = "https://files.pythonhosted.org/packages/b5/1d/59ba570b1774e95e97fde3a0981b2e22118a7a495f73bf74cedc538566a0/kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:416ba7ff9f233b7036689bb5a3783537e838ad483f63558d2a800f75afe738b1", size = 59450, upload-time = "2026-08-28T10:28:20.383Z" }, + { url = "https://files.pythonhosted.org/packages/22/98/a6849f04dc18b5400e8b98affa2cd8fd86ed583085f036e57b32e571f4fa/kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:8af9b142ad719ae3a911ebf616bc4b78b32bbab84d6a40d3ad2f129670509957", size = 57400, upload-time = "2026-08-28T10:28:21.632Z" }, + { url = "https://files.pythonhosted.org/packages/f4/ce/a7dc71353dd06a4cbe02222773f52d4a28c81e5a452a75797f8ed113dc99/kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5daa1f19e097050b9c4d9a78fcc9263cb96c9dfae08037ddc1b7c4ad1889f2a2", size = 79891, upload-time = "2026-08-28T10:28:22.936Z" }, + { url = "https://files.pythonhosted.org/packages/10/b1/d61c61a84ff85d1a36a99df2c152b59ffedb1d356c598902aba44abcdb60/kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cdaeeb6c350106df6bf9d873395973e5f066a9713200b72cd64f55d0a3eafab6", size = 77605, upload-time = "2026-08-28T10:28:24.322Z" }, + { url = "https://files.pythonhosted.org/packages/d3/52/5aef56f21a460a6e43ab3cdfc7697d59d7b87deb0ec97a0f7b91aa4a521b/kiwisolver-1.5.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:17851e5dad4484be0cbccbde3b15331deae036de9aebd45eed964487802b172f", size = 98465, upload-time = "2026-08-28T10:28:25.696Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/55/18dbb4778b30ada5ce071608503cc3edc9e14e13d868c17a6d178fc30f7a/markupsafe-3.0.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9e25feb9e330b63edb0278a0acdf85e50d0cb0fbf49c3084abbe4e24ae195346", size = 11520, upload-time = "2026-10-02T23:04:36.299Z" }, + { url = "https://files.pythonhosted.org/packages/6c/14/0b05f79b4733e264a18d08fe08fa1df7347630ff32a6cb82180d9dccec55/markupsafe-3.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7d3391b2188d18737cb2fa147028b1096236eaa7e156446c650a489fa2cadc91", size = 12063, upload-time = "2026-10-02T23:04:37.291Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3a/63ba10b6c1463216b3e4df669a9f0e5a3b0c3071557d2e8229e3968c79fb/markupsafe-3.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849dd2bb0e5e4ab2b71c7191726a4a8d5aa8a610daa584728cbee0b710ddc4ef", size = 24321, upload-time = "2026-10-02T23:04:38.262Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/5f015261b76ad633d187ef6f388b413aedd64a8773c4df59e530a0be5525/markupsafe-3.0.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:befb4158af32106b9a93db8d6d1d1cbbd418c0d5aca0cabb7b1780abf0c89169", size = 28845, upload-time = "2026-10-02T23:04:39.295Z" }, + { url = "https://files.pythonhosted.org/packages/33/cf/26e594b26be40c2f1fec63ccf8a8b99d0335a5b2cbe84835c7d82a994375/markupsafe-3.0.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:71f88e749ea29f67f21f3b36433c1dc54c7729ed2a6d9e2da2e0d9e0d7b224eb", size = 24701, upload-time = "2026-10-02T23:04:40.348Z" }, + { url = "https://files.pythonhosted.org/packages/81/a5/a513b76c139a3915b43404324e55c0b7979ae4f0d39eb6f075b0282e90a8/markupsafe-3.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6da83a088f8ef93b2d483a8232a4dbf4d69d3d8496b568a03c56becac43e1808", size = 22961, upload-time = "2026-10-02T23:04:41.372Z" }, + { url = "https://files.pythonhosted.org/packages/46/cf/4c66192c100b4542bcbe392ae06696b670f66927be3ac38a213234778ff9/markupsafe-3.0.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8f0fac8b13d14bb06c68195f849371924ae53dd7b1c00fed24650f704383b692", size = 21920, upload-time = "2026-10-02T23:04:42.429Z" }, + { url = "https://files.pythonhosted.org/packages/cb/17/ac3662678bfbad649893117ada2ba44dc30bf56884e84f13154a792b10f1/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4a7cdc2a420ca01058182da4253329764d4bfa055564d1eced90e6ba1e8b1d3d", size = 23726, upload-time = "2026-10-02T23:04:43.531Z" }, + { url = "https://files.pythonhosted.org/packages/f7/af/fe47cee339180a69ebca3c57fb3483d0f5cbd1e8337d1871fb1d9c1aebee/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:83b3944fea42a8400edf92fd1770fb8d0d4f7de651353bd2d8525a92dba69a21", size = 22539, upload-time = "2026-10-02T23:04:44.618Z" }, + { url = "https://files.pythonhosted.org/packages/12/32/d55440ba140442800e02d799c9cb5ab597bf6ebdb1177b5ea39a11f797bd/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8138eb83940ec7299024d92d4dee45f601b9e6c5ffde9d25f4e35e326203c707", size = 23963, upload-time = "2026-10-02T23:04:45.656Z" }, + { url = "https://files.pythonhosted.org/packages/50/9d/9c86042cb364c2ad4c971e6d1247929effd25f714cd7ee11b05e6316445b/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:811d02d5122171c1941357efd8f9bf4ffe907b7f0a1a4e729a880e4be3f46e3e", size = 21506, upload-time = "2026-10-02T23:04:46.671Z" }, + { url = "https://files.pythonhosted.org/packages/75/ef/5b824f03ba40c3b3652b6272d083d2fc4fcdd440de519a3a39ba2c3e7262/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:50b5bedc9ed8a94fc8857a42ef4f84a81ea88f8d4f05dc8705fb23ee6d8dcca7", size = 22955, upload-time = "2026-10-02T23:04:47.698Z" }, + { url = "https://files.pythonhosted.org/packages/1e/e8/44cfcb5ea40e5e43cec7793ef90704ed0c475280839076c4345757eb8e59/markupsafe-3.0.4-cp311-cp311-win32.whl", hash = "sha256:2e5a7cd7fdd14fcb1ae5d7d8bf23d24fbd1daefd1fbca2580132e1ea75f098b5", size = 14094, upload-time = "2026-10-02T23:04:48.788Z" }, + { url = "https://files.pythonhosted.org/packages/91/89/f2b509f7bf79352e40117824c1070dbeafd4df67031d3fa98165a3134228/markupsafe-3.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3", size = 14328, upload-time = "2026-10-02T23:04:49.801Z" }, + { url = "https://files.pythonhosted.org/packages/2b/5a/ccf22672a0f64dc682306e288f0dabcb06c7a201f3bb6e6cbf86d9e8ad03/markupsafe-3.0.4-cp311-cp311-win_arm64.whl", hash = "sha256:569d65055d367e3dcdf30c3f41119467b73d9ee9faf332bdf40402644f5ac08e", size = 14188, upload-time = "2026-10-02T23:04:50.847Z" }, +] + +[[package]] +name = "matplotlib" +version = "3.10.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "contourpy" }, + { name = "cycler" }, + { name = "fonttools" }, + { name = "kiwisolver" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "pyparsing" }, + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ae/e2/d2d5295be2f44c678ebaf3544ba32d20c1f9ef08c49fe47f496180e1db15/matplotlib-3.10.7.tar.gz", hash = "sha256:a06ba7e2a2ef9131c79c49e63dad355d2d878413a0376c1727c8b9335ff731c7", size = 34804865, upload-time = "2025-10-09T00:28:00.669Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/bc/0fb489005669127ec13f51be0c6adc074d7cf191075dab1da9fe3b7a3cfc/matplotlib-3.10.7-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:53b492410a6cd66c7a471de6c924f6ede976e963c0f3097a3b7abfadddc67d0a", size = 8257507, upload-time = "2025-10-09T00:26:19.073Z" }, + { url = "https://files.pythonhosted.org/packages/e2/6a/d42588ad895279ff6708924645b5d2ed54a7fb2dc045c8a804e955aeace1/matplotlib-3.10.7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d9749313deb729f08207718d29c86246beb2ea3fdba753595b55901dee5d2fd6", size = 8119565, upload-time = "2025-10-09T00:26:21.023Z" }, + { url = "https://files.pythonhosted.org/packages/10/b7/4aa196155b4d846bd749cf82aa5a4c300cf55a8b5e0dfa5b722a63c0f8a0/matplotlib-3.10.7-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2222c7ba2cbde7fe63032769f6eb7e83ab3227f47d997a8453377709b7fe3a5a", size = 8692668, upload-time = "2025-10-09T00:26:22.967Z" }, + { url = "https://files.pythonhosted.org/packages/e6/e7/664d2b97016f46683a02d854d730cfcf54ff92c1dafa424beebef50f831d/matplotlib-3.10.7-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e91f61a064c92c307c5a9dc8c05dc9f8a68f0a3be199d9a002a0622e13f874a1", size = 9521051, upload-time = "2025-10-09T00:26:25.041Z" }, + { url = "https://files.pythonhosted.org/packages/a8/a3/37aef1404efa615f49b5758a5e0261c16dd88f389bc1861e722620e4a754/matplotlib-3.10.7-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6f1851eab59ca082c95df5a500106bad73672645625e04538b3ad0f69471ffcc", size = 9576878, upload-time = "2025-10-09T00:26:27.478Z" }, + { url = "https://files.pythonhosted.org/packages/33/cd/b145f9797126f3f809d177ca378de57c45413c5099c5990de2658760594a/matplotlib-3.10.7-cp311-cp311-win_amd64.whl", hash = "sha256:6516ce375109c60ceec579e699524e9d504cd7578506f01150f7a6bc174a775e", size = 8115142, upload-time = "2025-10-09T00:26:29.774Z" }, + { url = "https://files.pythonhosted.org/packages/2e/39/63bca9d2b78455ed497fcf51a9c71df200a11048f48249038f06447fa947/matplotlib-3.10.7-cp311-cp311-win_arm64.whl", hash = "sha256:b172db79759f5f9bc13ef1c3ef8b9ee7b37b0247f987fbbbdaa15e4f87fd46a9", size = 7992439, upload-time = "2025-10-09T00:26:40.32Z" }, + { url = "https://files.pythonhosted.org/packages/58/8f/76d5dc21ac64a49e5498d7f0472c0781dae442dd266a67458baec38288ec/matplotlib-3.10.7-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:15112bcbaef211bd663fa935ec33313b948e214454d949b723998a43357b17b0", size = 8252283, upload-time = "2025-10-09T00:27:54.739Z" }, + { url = "https://files.pythonhosted.org/packages/27/0d/9c5d4c2317feb31d819e38c9f947c942f42ebd4eb935fc6fd3518a11eaa7/matplotlib-3.10.7-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d2a959c640cdeecdd2ec3136e8ea0441da59bcaf58d67e9c590740addba2cb68", size = 8116733, upload-time = "2025-10-09T00:27:56.406Z" }, + { url = "https://files.pythonhosted.org/packages/9a/cc/3fe688ff1355010937713164caacf9ed443675ac48a997bab6ed23b3f7c0/matplotlib-3.10.7-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3886e47f64611046bc1db523a09dd0a0a6bed6081e6f90e13806dd1d1d1b5e91", size = 8693919, upload-time = "2025-10-09T00:27:58.41Z" }, +] + +[[package]] +name = "mpmath" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, +] + +[[package]] +name = "multidict" +version = "7.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/6b/29ef8e752f5854dcc267ded0652c475bec99b86f255957a0d4fcad657b18/multidict-7.2.1.tar.gz", hash = "sha256:e8af3e6f1bdbc31fd762b094133b478b89988eaebc63cbe82b1d9e3bbd15cede", size = 369994, upload-time = "2026-10-24T20:41:35.457Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/24/4347a7502ad47cb05a1b8d4e219514b4f0b1e38d4e4734c053c20328949f/multidict-7.2.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:fd24c4425fdb8e822601335602375c6d0cb020f7a368e1d5842eb7925a9c8748", size = 173141, upload-time = "2026-10-24T20:40:02.481Z" }, + { url = "https://files.pythonhosted.org/packages/8d/f2/2a8fcfe4c2c435101f9227b7f7ea81d786ffef993cadd2394e6926020ca9/multidict-7.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cecb2c778f00a65c6ca01410dd194d0e797a9eebb7c6dea0db87718719f293c7", size = 97197, upload-time = "2026-10-24T20:40:06.534Z" }, + { url = "https://files.pythonhosted.org/packages/7a/57/39be4ac4fa9c20e3af7dd7e89adf7dd404b4547fb4453c5c96082e197b9c/multidict-7.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:0d852d3d9638f852158d7de7200dd77f7ff8d77fc8f3d396032f3d847883f631", size = 104843, upload-time = "2026-10-24T20:40:05.829Z" }, + { url = "https://files.pythonhosted.org/packages/63/da/6a5c78daa34e458ced17573b7527395c4c39ebb253220274382d361a1493/multidict-7.2.1-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:76a4f5132b8dc29eb3c768ee9b47e132a1d24fbc2e9259854c01af9beaff1d49", size = 490713, upload-time = "2026-10-24T20:40:41.715Z" }, + { url = "https://files.pythonhosted.org/packages/8a/75/b8252bc6411f7f4b9649b83e143789b7bc1dda44f656b09ce74f894ca027/multidict-7.2.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:295a15ccb8cfde9351dd6062b80af4e839460636b3c46813b4aa443905ded86a", size = 504189, upload-time = "2026-10-24T20:40:04.042Z" }, + { url = "https://files.pythonhosted.org/packages/c0/45/38e8191d0a7c7b56015dfc4c2910b731aa719c5ad3f369b2357567f03434/multidict-7.2.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:987f65f6c9321402bc7012f6c6d09ba501b88ddb1640f5b0b4a19f2caafe24a5", size = 465834, upload-time = "2026-10-24T20:40:08.058Z" }, + { url = "https://files.pythonhosted.org/packages/9f/55/378869573886f7efcac24d2c698938dadf973e0da40b812c8b0df847fc46/multidict-7.2.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:36b868758fb11cfa748c788b793994e73660abec90f83c780a678539c2c468bf", size = 522423, upload-time = "2026-10-24T20:40:07.427Z" }, + { url = "https://files.pythonhosted.org/packages/af/c5/8936fe02c11196994ac05c4876ad62336a66ef353ea2d1a2ca3adce71678/multidict-7.2.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5b944091cfa7da4f7a9bd2587569cd90c94b89ec4721f8e87fe62504f2432b67", size = 544512, upload-time = "2026-10-24T20:40:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/d0/38/b8403d97ae5273002fa664c3c440c5cc186082fa0ba20fcc93885d13a686/multidict-7.2.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3b7542fad2706595c1b1853b46f2c3c4ae5cc5a6252b7225f294d607a29e1bdf", size = 510054, upload-time = "2026-10-24T20:40:05.525Z" }, + { url = "https://files.pythonhosted.org/packages/18/5d/473e1436ea8577cdfb42371c0507a244d51f8d8ef08bea0f9e6e63906478/multidict-7.2.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:363e5db93fc3f65f3218a79fe108d217b9d264181a4e993c77552bfe275d0393", size = 452816, upload-time = "2026-10-24T20:40:09.49Z" }, + { url = "https://files.pythonhosted.org/packages/1e/b7/67376e6821fb28c21de1fb37731efd2e3a6a523bdefc4af6997bd043da7a/multidict-7.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5deadf03fb4a7842696d551f9f9a06dd4445bb43ca06b5f9736e4e1885561333", size = 490712, upload-time = "2026-10-24T20:40:09.097Z" }, + { url = "https://files.pythonhosted.org/packages/1a/89/5144d8b36f133109ff36408089a475b9a3a3c1840176a39a9a8fb67a0000/multidict-7.2.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:0ec95a02f9f08246cc7f1d85ac425e4d5c233fd3f098f5be1b2cca16aa690186", size = 462856, upload-time = "2026-10-24T20:40:44.771Z" }, + { url = "https://files.pythonhosted.org/packages/ff/7f/38310388c4c5e351dfc419a04e4c7a26cde14b0e1019bc72bbd1b0d95613/multidict-7.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:3d6fce7cc4ef63d9a7633cbae43e737798412805a4c3ba876cdf472dc6ff9c51", size = 490108, upload-time = "2026-10-24T20:40:06.965Z" }, + { url = "https://files.pythonhosted.org/packages/ce/0d/94162600e5bbf24bf33398f3b33ae2f78211375313dbdaaf1513b2554a66/multidict-7.2.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:37b161535e92776788957a165fcf38a80b33c1efde7b18cab287db4e4574df78", size = 508935, upload-time = "2026-10-24T20:40:10.882Z" }, + { url = "https://files.pythonhosted.org/packages/1d/40/a0cae932493346cb0d442ffa380e65491fdae8df338d8cdf2f39695c0947/multidict-7.2.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:e47d058c2db95010f5d2e1f6037acebdfb0e2fa4507650e1041437985c91db38", size = 447620, upload-time = "2026-10-24T20:40:10.548Z" }, + { url = "https://files.pythonhosted.org/packages/5e/a5/6ec5cd1c15574aca277ab08920f7e78a6a1e1c15912bfaf59b48683230f7/multidict-7.2.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:7238f7135481926d52a94c18a8cca633a9e72c1cbfccd5796548298a479b0656", size = 523896, upload-time = "2026-10-24T20:40:46.258Z" }, + { url = "https://files.pythonhosted.org/packages/ae/60/d164a2583548561f7e596f13bbd1c3492ea33a77d499d3ceaa2acf76d850/multidict-7.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:c10ac5e3e76837180656079008f71add8339b00c3c26314092bcd1e8e449049f", size = 502961, upload-time = "2026-10-24T20:40:08.732Z" }, + { url = "https://files.pythonhosted.org/packages/30/6b/474aee537e0c87210ce8f4fd21558b461e8a8e74c79440de036022a9eeda/multidict-7.2.1-cp311-cp311-win32.whl", hash = "sha256:2b4d0c4e13d329ffee73d46128e32dd3b4aeb2f9c6ac9c8a89eb28d3b82dcea8", size = 84159, upload-time = "2026-10-24T20:40:12.222Z" }, + { url = "https://files.pythonhosted.org/packages/1f/02/41d769148f32c9bd535fd0ddd946c4e42f38acaddf7899f3bf49d9e67703/multidict-7.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:a789e3d27fc5665cc0477f10a35a89383313e4c9cf8b5e6af7ea71f039cdcc0e", size = 94895, upload-time = "2026-10-24T20:40:12.036Z" }, + { url = "https://files.pythonhosted.org/packages/23/be/e04fcf29542d0db25cdec79acbe5662481c3ba6b760353c393f9c46156f2/multidict-7.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:2022bd3194968a027f64ed16f9779e62e71a823a9df3971a7328c1d45dfeb9ab", size = 92384, upload-time = "2026-10-24T20:40:47.827Z" }, + { url = "https://files.pythonhosted.org/packages/9d/96/1aaad0e5df33f1f5af21775c411349c0234a6edd581ea403bc81919a6eab/multidict-7.2.1-py3-none-any.whl", hash = "sha256:08ea94663d9e7c25d14d78222f7aee906c472d4837766bec62477c38f6e419dc", size = 28145, upload-time = "2026-10-24T20:40:59.159Z" }, +] + +[[package]] +name = "multiprocess" +version = "0.70.16" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dill" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b5/ae/04f39c5d0d0def03247c2893d6f2b83c136bf3320a2154d7b8858f2ba72d/multiprocess-0.70.16.tar.gz", hash = "sha256:161af703d4652a0e1410be6abccecde4a7ddffd19341be0a7011b94aeb171ac1", size = 1772603, upload-time = "2024-01-28T18:52:34.85Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/f7/7ec7fddc92e50714ea3745631f79bd9c96424cb2702632521028e57d3a36/multiprocess-0.70.16-py310-none-any.whl", hash = "sha256:c4a9944c67bd49f823687463660a2d6daae94c289adff97e0f9d696ba6371d02", size = 134824, upload-time = "2024-01-28T18:52:26.062Z" }, + { url = "https://files.pythonhosted.org/packages/50/15/b56e50e8debaf439f44befec5b2af11db85f6e0f344c3113ae0be0593a91/multiprocess-0.70.16-py311-none-any.whl", hash = "sha256:af4cabb0dac72abfb1e794fa7855c325fd2b55a10a44628a3c1ad3311c04127a", size = 143519, upload-time = "2024-01-28T18:52:28.115Z" }, + { url = "https://files.pythonhosted.org/packages/ea/89/38df130f2c799090c978b366cfdf5b96d08de5b29a4a293df7f7429fa50b/multiprocess-0.70.16-py38-none-any.whl", hash = "sha256:a71d82033454891091a226dfc319d0cfa8019a4e888ef9ca910372a446de4435", size = 132628, upload-time = "2024-01-28T18:52:30.853Z" }, + { url = "https://files.pythonhosted.org/packages/da/d9/f7f9379981e39b8c2511c9e0326d212accacb82f12fbfdc1aa2ce2a7b2b6/multiprocess-0.70.16-py39-none-any.whl", hash = "sha256:a0bafd3ae1b732eac64be2e72038231c1ba97724b60b09400d68f229fcc2fbf3", size = 133351, upload-time = "2024-01-28T18:52:31.981Z" }, +] + +[[package]] +name = "networkx" +version = "3.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c9/b2622292ea83fbb4ec318f5b9ab867d0a28ab43c5717bb85b0a5f6b3b0a4/networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762", size = 2068504, upload-time = "2025-12-08T17:02:38.159Z" }, +] + +[[package]] +name = "nltk" +version = "3.9.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "joblib" }, + { name = "regex" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f9/76/3a5e4312c19a028770f86fd7c058cf9f4ec4321c6cf7526bab998a5b683c/nltk-3.9.2.tar.gz", hash = "sha256:0f409e9b069ca4177c1903c3e843eef90c7e92992fa4931ae607da6de49e1419", size = 2887629, upload-time = "2025-10-01T07:19:23.764Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/90/81ac364ef94209c100e12579629dc92bf7a709a84af32f8c551b02c07e94/nltk-3.9.2-py3-none-any.whl", hash = "sha256:1e209d2b3009110635ed9709a67a1a3e33a10f799490fa71cf4bec218c11c88a", size = 1513404, upload-time = "2025-10-01T07:19:21.648Z" }, +] + +[[package]] +name = "numpy" +version = "1.26.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/65/6e/09db70a523a96d25e115e71cc56a6f9031e7b8cd166c1ac8438307c14058/numpy-1.26.4.tar.gz", hash = "sha256:2a02aba9ed12e4ac4eb3ea9421c420301a0c6460d9830d74a9df87efa4912010", size = 15786129, upload-time = "2024-02-06T00:26:44.495Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/57/baae43d14fe163fa0e4c47f307b6b2511ab8d7d30177c491960504252053/numpy-1.26.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4c66707fabe114439db9068ee468c26bbdf909cac0fb58686a42a24de1760c71", size = 20630554, upload-time = "2024-02-05T23:51:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/151484f49fd03944c4a3ad9c418ed193cfd02724e138ac8a9505d056c582/numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:edd8b5fe47dab091176d21bb6de568acdd906d1887a4584a15a9a96a1dca06ef", size = 13997127, upload-time = "2024-02-05T23:52:15.314Z" }, + { url = "https://files.pythonhosted.org/packages/79/ae/7e5b85136806f9dadf4878bf73cf223fe5c2636818ba3ab1c585d0403164/numpy-1.26.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7ab55401287bfec946ced39700c053796e7cc0e3acbef09993a9ad2adba6ca6e", size = 14222994, upload-time = "2024-02-05T23:52:47.569Z" }, + { url = "https://files.pythonhosted.org/packages/3a/d0/edc009c27b406c4f9cbc79274d6e46d634d139075492ad055e3d68445925/numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:666dbfb6ec68962c033a450943ded891bed2d54e6755e35e5835d63f4f6931d5", size = 18252005, upload-time = "2024-02-05T23:53:15.637Z" }, + { url = "https://files.pythonhosted.org/packages/09/bf/2b1aaf8f525f2923ff6cfcf134ae5e750e279ac65ebf386c75a0cf6da06a/numpy-1.26.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:96ff0b2ad353d8f990b63294c8986f1ec3cb19d749234014f4e7eb0112ceba5a", size = 13885297, upload-time = "2024-02-05T23:53:42.16Z" }, + { url = "https://files.pythonhosted.org/packages/df/a0/4e0f14d847cfc2a633a1c8621d00724f3206cfeddeb66d35698c4e2cf3d2/numpy-1.26.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:60dedbb91afcbfdc9bc0b1f3f402804070deed7392c23eb7a7f07fa857868e8a", size = 18093567, upload-time = "2024-02-05T23:54:11.696Z" }, + { url = "https://files.pythonhosted.org/packages/d2/b7/a734c733286e10a7f1a8ad1ae8c90f2d33bf604a96548e0a4a3a6739b468/numpy-1.26.4-cp311-cp311-win32.whl", hash = "sha256:1af303d6b2210eb850fcf03064d364652b7120803a0b872f5211f5234b399f20", size = 5968812, upload-time = "2024-02-05T23:54:26.453Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6b/5610004206cf7f8e7ad91c5a85a8c71b2f2f8051a0c0c4d5916b76d6cbb2/numpy-1.26.4-cp311-cp311-win_amd64.whl", hash = "sha256:cd25bcecc4974d09257ffcd1f098ee778f7834c3ad767fe5db785be9a4aa9cb2", size = 15811913, upload-time = "2024-02-05T23:54:53.933Z" }, +] + +[[package]] +name = "nvidia-cublas" +version = "13.1.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cuda-nvrtc", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" }, + { url = "https://files.pythonhosted.org/packages/3b/cd/154ca20c38269e05eff77c1464e6c1da89f50a6390b565e9d82e06bc11e1/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:37936a16db8fe4ac1f065c2139360608a543a09275cb1a1af612e08cfa065436", size = 423138758, upload-time = "2026-04-08T18:46:58.655Z" }, + { url = "https://files.pythonhosted.org/packages/45/9e/2f562daf80eb8f7a685fb7bea4fda71f6048e4f359d6fdd1b6e70206cb2f/nvidia_cublas-13.1.1.3-py3-none-win_amd64.whl", hash = "sha256:b6cdce694e47ff6aadf0a69df1cab6628d696f5ff56e8d16af50309d855fa20f", size = 404358158, upload-time = "2026-04-08T18:47:26.987Z" }, +] + +[[package]] +name = "nvidia-cuda-cupti" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/2a/80353b103fc20ce05ef51e928daed4b6015db4aaa9162ed0997090fe2250/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_aarch64.whl", hash = "sha256:796bd679890ee55fb14a94629b698b6db54bcfd833d391d5e94017dd9d7d3151", size = 10310827, upload-time = "2025-09-04T08:26:42.012Z" }, + { url = "https://files.pythonhosted.org/packages/33/6d/737d164b4837a9bbd202f5ae3078975f0525a55730fe871d8ed4e3b952b0/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_x86_64.whl", hash = "sha256:4eb01c08e859bf924d222250d2e8f8b8ff6d3db4721288cf35d14252a4d933c8", size = 10715597, upload-time = "2025-09-04T08:26:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/ad/df/b74b10025c1205695c5676373f2edd3e87a7202cc62ead0dfbc373b0f6ea/nvidia_cuda_cupti-13.0.85-py3-none-win_amd64.whl", hash = "sha256:683f58d301548deeefcb8f6fac1b8d907691b9d8b18eccab417f51e362102f00", size = 7736776, upload-time = "2025-09-04T08:38:08.38Z" }, +] + +[[package]] +name = "nvidia-cuda-nvrtc" +version = "13.0.88" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/68/483a78f5e8f31b08fb1bb671559968c0ca3a065ac7acabfc7cee55214fd6/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:ad9b6d2ead2435f11cbb6868809d2adeeee302e9bb94bcf0539c7a40d80e8575", size = 90215200, upload-time = "2025-09-04T08:28:44.204Z" }, + { url = "https://files.pythonhosted.org/packages/b7/dc/6bb80850e0b7edd6588d560758f17e0550893a1feaf436807d64d2da040f/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d27f20a0ca67a4bb34268a5e951033496c5b74870b868bacd046b1b8e0c3267b", size = 43015449, upload-time = "2025-09-04T08:28:20.239Z" }, + { url = "https://files.pythonhosted.org/packages/4a/af/345fedb9f4c76c84ab4fa445b36bd4048a4d9db60e6bc76b4f913ff4b852/nvidia_cuda_nvrtc-13.0.88-py3-none-win_amd64.whl", hash = "sha256:6bcd4e7f8e205cbe644f5a98f2f799bef9556fefc89dd786e79a16312ce49872", size = 76807835, upload-time = "2025-09-04T08:39:15.274Z" }, +] + +[[package]] +name = "nvidia-cuda-runtime" +version = "13.0.96" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/4f/17d7b9b8e285199c58ce28e31b5c5bbaa4d8271af06a89b6405258245de2/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ef9bcbe90493a2b9d810e43d249adb3d02e98dd30200d86607d8d02687c43f55", size = 2261060, upload-time = "2025-10-09T08:55:15.78Z" }, + { url = "https://files.pythonhosted.org/packages/2e/24/d1558f3b68b1d26e706813b1d10aa1d785e4698c425af8db8edc3dced472/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7f82250d7782aa23b6cfe765ecc7db554bd3c2870c43f3d1821f1d18aebf0548", size = 2243632, upload-time = "2025-10-09T08:55:36.117Z" }, + { url = "https://files.pythonhosted.org/packages/b7/94/6b867483bec07da24ffa32736c79fabb94ef3a7af4d787a9d4a974868576/nvidia_cuda_runtime-13.0.96-py3-none-win_amd64.whl", hash = "sha256:f79298c8a098cec150a597c8eba58ecdab96e3bdc4b9bc4f9983635031740492", size = 2927037, upload-time = "2025-10-09T09:04:23.782Z" }, +] + +[[package]] +name = "nvidia-cudnn-cu13" +version = "9.20.0.48" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cublas", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/c5/83384d846b2fd17c44bd499b36c75a45ed4f095fbbb2252294e89cea5c5c/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:e31454ae00094b0c55319d9d15b6fa2fc50a9e1c0f5c8c80fb75258234e731e1", size = 444574296, upload-time = "2026-03-09T19:28:27.751Z" }, + { url = "https://files.pythonhosted.org/packages/6e/5e/edb9c0ae051602c3ccaffe424256463636d639e27d7f302dde9975ef9e7a/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0c45dd8eeb50b603f07995b1b300c62ffe6a1980482b82b3bcf94a4ca9d49304", size = 366173588, upload-time = "2026-03-09T19:29:34.474Z" }, + { url = "https://files.pythonhosted.org/packages/78/39/21507455b1bca8b5702a9e9fc6ce73735f216f558dac2c9ede58e4d456b8/nvidia_cudnn_cu13-9.20.0.48-py3-none-win_amd64.whl", hash = "sha256:af8139732b99c0118be65ea5aac97f0d46018f8c552889e49d2fb0c6261a4a24", size = 350712614, upload-time = "2026-03-09T19:31:11.398Z" }, +] + +[[package]] +name = "nvidia-cufft" +version = "12.0.0.61" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, + { url = "https://files.pythonhosted.org/packages/a8/2f/7b57e29836ea8714f81e9898409196f47d772d5ddedddf1592eadb8ab743/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6c44f692dce8fd5ffd3e3df134b6cdb9c2f72d99cf40b62c32dde45eea9ddad3", size = 214085489, upload-time = "2025-09-04T08:31:56.044Z" }, + { url = "https://files.pythonhosted.org/packages/85/b2/f8af21a2ed1beed337a6a02c5a28aeb85441f4d578ec3d529543c775ea4b/nvidia_cufft-12.0.0.61-py3-none-win_amd64.whl", hash = "sha256:2abce5b39d2f5ae12730fb7e5db6696533e36c26e2d3e8fd1750bdd2853364eb", size = 213342123, upload-time = "2025-09-04T08:40:51.145Z" }, +] + +[[package]] +name = "nvidia-cufile" +version = "1.15.1.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/70/4f193de89a48b71714e74602ee14d04e4019ad36a5a9f20c425776e72cd6/nvidia_cufile-1.15.1.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:08a3ecefae5a01c7f5117351c64f17c7c62efa5fffdbe24fc7d298da19cd0b44", size = 1223672, upload-time = "2025-09-04T08:32:22.779Z" }, + { url = "https://files.pythonhosted.org/packages/ab/73/cc4a14c9813a8a0d509417cf5f4bdaba76e924d58beb9864f5a7baceefbf/nvidia_cufile-1.15.1.6-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:bdc0deedc61f548bddf7733bdc216456c2fdb101d020e1ab4b88d232d5e2f6d1", size = 1136992, upload-time = "2025-09-04T08:32:14.119Z" }, +] + +[[package]] +name = "nvidia-curand" +version = "10.4.0.35" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/72/7c2ae24fb6b63a32e6ae5d241cc65263ea18d08802aaae087d9f013335a2/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:133df5a7509c3e292aaa2b477afd0194f06ce4ea24d714d616ff36439cee349a", size = 61962106, upload-time = "2025-08-04T10:21:41.128Z" }, + { url = "https://files.pythonhosted.org/packages/a5/9f/be0a41ca4a4917abf5cb9ae0daff1a6060cc5de950aec0396de9f3b52bc5/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:1aee33a5da6e1db083fe2b90082def8915f30f3248d5896bcec36a579d941bfc", size = 59544258, upload-time = "2025-08-04T10:22:03.992Z" }, + { url = "https://files.pythonhosted.org/packages/99/27/72103153b1ffc00e09fdc40ac970235343dcd1ea8bd762e84d2d73219ffa/nvidia_curand-10.4.0.35-py3-none-win_amd64.whl", hash = "sha256:65b1710aa6961d326b411e314b374290904c5ddf41dc3f766ebc3f1d7d4ca69f", size = 55242481, upload-time = "2025-08-04T10:30:41.831Z" }, +] + +[[package]] +name = "nvidia-cusolver" +version = "12.0.4.66" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cublas", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-cusparse", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, + { url = "https://files.pythonhosted.org/packages/5f/67/cba3777620cdacb99102da4042883709c41c709f4b6323c10781a9c3aa34/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0a759da5dea5c0ea10fd307de75cdeb59e7ea4fcb8add0924859b944babf1112", size = 200941980, upload-time = "2025-09-04T08:33:22.767Z" }, + { url = "https://files.pythonhosted.org/packages/99/ef/332a0101260ca78a1daef046bf0b06199e8ed4dac1d2aa698289c358169c/nvidia_cusolver-12.0.4.66-py3-none-win_amd64.whl", hash = "sha256:16515bd33a8e76bb54d024cfa068fa68d30e80fc34b9e1090813ea9362e0cb65", size = 193551444, upload-time = "2025-09-04T08:41:46.813Z" }, +] + +[[package]] +name = "nvidia-cusparse" +version = "12.6.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, + { url = "https://files.pythonhosted.org/packages/fa/18/623c77619c31d62efd55302939756966f3ecc8d724a14dab2b75f1508850/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2b3c89c88d01ee0e477cb7f82ef60a11a4bcd57b6b87c33f789350b59759360b", size = 145942937, upload-time = "2025-09-04T08:33:58.029Z" }, + { url = "https://files.pythonhosted.org/packages/02/b0/b043d6f3480f102f885cf87fc3ffd3edcb5e23b855025a50e2ef4d059185/nvidia_cusparse-12.6.3.3-py3-none-win_amd64.whl", hash = "sha256:cbcf42feb737bd7ec15b4c0a63e62351886bd3f975027b8815d7f720a2b5ea79", size = 143783033, upload-time = "2025-09-04T08:42:12.391Z" }, +] + +[[package]] +name = "nvidia-cusparselt-cu13" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/e1/cdc1797eadf82d3a9a575a19b33fdc871a97edbec42c00b5b5e914f4aff4/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:4dca476c50bf4780d46cd0bfbd82e2bc10a08e4fef7950917ce8d7578d22a23f", size = 221051344, upload-time = "2025-09-05T18:49:51.289Z" }, + { url = "https://files.pythonhosted.org/packages/34/7d/2661f2fb3ac4302f3a246f5fc030213ac60c1fe0bce84f9783dbd831dbb7/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:786ce87568c303fadb5afcc7102d454cd3040d75f6f8626f5db460d1871f4dd0", size = 170148586, upload-time = "2025-09-05T18:50:50.248Z" }, + { url = "https://files.pythonhosted.org/packages/31/83/f3647ce26916c94a6ca4ff1810623e2c405cff2dea6e78d29516b2514df9/nvidia_cusparselt_cu13-0.8.1-py3-none-win_amd64.whl", hash = "sha256:dccbd362f91a7b9024d1f55ee9f548ac065027ff15d8c8b0db889ab3a8f31215", size = 156885108, upload-time = "2025-09-05T18:51:35.958Z" }, +] + +[[package]] +name = "nvidia-nccl-cu13" +version = "2.29.7" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/0d/daf50d44177ee0cbc7ff0a0c91eb5ff676c82be42f9a970bc7597f440c3a/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_aarch64.whl", hash = "sha256:674a12383e3c38a1bcccae7d4f3633b37852230b6047883cb2f4c2d1b36d9bf5", size = 206014712, upload-time = "2026-03-03T05:34:20.843Z" }, + { url = "https://files.pythonhosted.org/packages/67/f4/58e4e91b6919367c7aafb8e36fce9aad1a3047e536bf7e2fd560927d3a4c/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:edd81538446786ec3b73972543e53bb43bcaf0bfc8ef76cb679fcc390ffe136d", size = 205976000, upload-time = "2026-03-03T05:36:24.472Z" }, +] + +[[package]] +name = "nvidia-nvjitlink" +version = "13.5.37" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cc/1f/2321702b8d60b4b4dd18b957f61612dbac9cb1c07e940cf6582106b7c8b8/nvidia_nvjitlink-13.5.37-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:280d7cb9649704145f074b8dbde500de04ce02d0872e066e20a83c17bcaa93eb", size = 46642491, upload-time = "2026-11-04T23:33:31.696Z" }, + { url = "https://files.pythonhosted.org/packages/24/15/dd228f798cd01d7aeaf19d872b2b20f9aeafc1a7d8b6bfaa878b30b8d6f7/nvidia_nvjitlink-13.5.37-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:893f6f9a55b2720ed94913b5ba3332e972da8c78dfa2863d0244403dbd528ffc", size = 45253761, upload-time = "2026-11-04T23:33:22.854Z" }, + { url = "https://files.pythonhosted.org/packages/a7/53/c43398492e8374880d5e01c23c4dac33ba0c3bd03515d6ecc574254c0967/nvidia_nvjitlink-13.5.37-py3-none-win_amd64.whl", hash = "sha256:4465d4e8f2212118220b580c82523c5654f93a62906bd51d29d79bdfc12376c1", size = 41467665, upload-time = "2026-11-04T23:38:44.689Z" }, + { url = "https://files.pythonhosted.org/packages/d7/4a/1ff9ab7d0c961a1b5539f8291c881bea82adbbf8ba40a9e81f9c9b3a8d5d/nvidia_nvjitlink-13.5.37-py3-none-win_arm64.whl", hash = "sha256:eb30348ae64c525180a280025dd12a089c3e2e1dc4e19cdd58f68c6edc622404", size = 38552904, upload-time = "2026-11-04T23:43:27.658Z" }, +] + +[[package]] +name = "nvidia-nvshmem-cu13" +version = "3.4.5" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/0f/05cc9c720236dcd2db9c1ab97fff629e96821be2e63103569da0c9b72f19/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dc2a197f38e5d0376ad52cd1a2a3617d3cdc150fd5966f4aee9bcebb1d68fe9", size = 60215947, upload-time = "2025-09-06T00:32:20.022Z" }, + { url = "https://files.pythonhosted.org/packages/3c/35/a9bf80a609e74e3b000fef598933235c908fcefcef9026042b8e6dfde2a9/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:290f0a2ee94c9f3687a02502f3b9299a9f9fe826e6d0287ee18482e78d495b80", size = 60412546, upload-time = "2025-09-06T00:32:41.564Z" }, +] + +[[package]] +name = "nvidia-nvtx" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c2/f3/d86c845465a2723ad7e1e5c36dcd75ddb82898b3f53be47ebd429fb2fa5d/nvidia_nvtx-13.0.85-py3-none-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4936d1d6780fbe68db454f5e72a42ff64d1fd6397df9f363ae786930fd5c1cd4", size = 148047, upload-time = "2025-09-04T08:29:01.761Z" }, + { url = "https://files.pythonhosted.org/packages/a8/64/3708a90d1ebe202ffdeb7185f878a3c84d15c2b2c31858da2ce0583e2def/nvidia_nvtx-13.0.85-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb7780edb6b14107373c835bf8b72e7a178bac7367e23da7acb108f973f157a6", size = 148878, upload-time = "2025-09-04T08:28:53.627Z" }, + { url = "https://files.pythonhosted.org/packages/d2/50/0e2220f8620a177de994211186ffc5bfa9f2ce1e1282797f8f90096f9f88/nvidia_nvtx-13.0.85-py3-none-win_amd64.whl", hash = "sha256:d66ea44254dd3c6eacc300047af6e1288d2269dd072b417e0adffbf479e18519", size = 137066, upload-time = "2025-09-04T08:39:25.649Z" }, +] + +[[package]] +name = "official-agzo-experiment" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "einops" }, + { name = "matplotlib" }, + { name = "nltk" }, + { name = "numpy" }, + { name = "psutil" }, + { name = "rouge" }, + { name = "scikit-learn" }, + { name = "sentencepiece" }, + { name = "setuptools" }, + { name = "torch" }, + { name = "wandb" }, +] + +[package.dev-dependencies] +modern = [ + { name = "accelerate" }, + { name = "datasets", version = "3.6.0", source = { registry = "https://pypi.org/simple" } }, + { name = "huggingface-hub" }, + { name = "pyarrow", version = "20.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "transformers", version = "4.57.1", source = { registry = "https://pypi.org/simple" } }, +] +native = [ + { name = "accelerate" }, + { name = "datasets", version = "2.21.0", source = { registry = "https://pypi.org/simple" } }, + { name = "huggingface-hub" }, + { name = "pyarrow", version = "17.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "transformers", version = "4.53.2", source = { registry = "https://pypi.org/simple" } }, +] + +[package.metadata] +requires-dist = [ + { name = "einops", specifier = "==0.8.1" }, + { name = "matplotlib", specifier = "==3.10.7" }, + { name = "nltk", specifier = "==3.9.2" }, + { name = "numpy", specifier = "==1.26.4" }, + { name = "psutil", specifier = "==7.1.3" }, + { name = "rouge", specifier = "==1.0.1" }, + { name = "scikit-learn", specifier = "==1.7.2" }, + { name = "sentencepiece", specifier = "==0.2.1" }, + { name = "setuptools", specifier = "==80.9.0" }, + { name = "torch", specifier = "==2.13.0" }, + { name = "wandb", specifier = "==0.23.1" }, +] + +[package.metadata.requires-dev] +modern = [ + { name = "accelerate", specifier = "==1.12.0" }, + { name = "datasets", specifier = "==3.6.0" }, + { name = "huggingface-hub", specifier = "==0.36.0" }, + { name = "pyarrow", specifier = "==20.0.0" }, + { name = "transformers", specifier = "==4.57.1" }, +] +native = [ + { name = "accelerate", specifier = "==1.12.0" }, + { name = "datasets", specifier = "==2.21.0" }, + { name = "huggingface-hub", specifier = "==0.36.0" }, + { name = "pyarrow", specifier = "==17.0.0" }, + { name = "transformers", specifier = "==4.53.2" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pandas" +version = "3.0.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e2/17/d7b106e05bfa642e8694451e7d3d759c6a241c5386a5d962e4f66c047e06/pandas-3.0.6.tar.gz", hash = "sha256:66b07ef7315a31bfe1089cd3d71a7de781c9dca986762d0b4fe7c0ef17465d10", size = 4667686, upload-time = "2026-09-17T23:23:18.345Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7d/48/88e8d250d28efa8163294f6809a71683c7ee67f63ac7c33021c0503b3547/pandas-3.0.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:085e3786ae6b2e82b406266bce36690f72b9dc1421903ba9296b2981a9fcf586", size = 10391798, upload-time = "2026-09-17T23:20:20.96Z" }, + { url = "https://files.pythonhosted.org/packages/55/a6/39db5d41f3eb5d7846626312cb30e0cea48e988fc47a3725698bc931ad3c/pandas-3.0.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d7564d86a94c2eb8ab290b07f63ddaae5c032fa53897c29a2ff2197d43aee8af", size = 10023718, upload-time = "2026-09-17T23:20:25.094Z" }, + { url = "https://files.pythonhosted.org/packages/54/b7/707e966129f77ee8a39d41a41bbd989b790b3fef581c6e26b821315cba6b/pandas-3.0.6-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e7c0afdcaf6661d795fcefc2f647ddd1136f62cdc153fba177c685d97a87808", size = 10612800, upload-time = "2026-09-17T23:20:27.99Z" }, + { url = "https://files.pythonhosted.org/packages/63/be/dfb6cc9329d0bbe76dadda8a1113d026bb996ec76c509221368dc68349f4/pandas-3.0.6-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:47121f9571503f724c9b93e297ab6254ac99c77adf5e9ed085ea419fd585c258", size = 11108900, upload-time = "2026-09-17T23:20:30.65Z" }, + { url = "https://files.pythonhosted.org/packages/1a/6f/3d58f15bbe972f3d7bfa13ee06d731785a76fe8d232c92b2655a8de14127/pandas-3.0.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:994a79608263fe1c14cc48ffa7300e2b834b7d1cb406ffe96a08828cb0cdd79b", size = 11630226, upload-time = "2026-09-17T23:20:33.582Z" }, + { url = "https://files.pythonhosted.org/packages/58/54/9b494de4a3dd92fc6eb19187db1b21afb50fdc21962f32ea1aca9f270cb2/pandas-3.0.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a3a22e07fe75347eaacc75b0e85297947af4fba6b4aae23916bd8b6828d0bba3", size = 12146942, upload-time = "2026-09-17T23:20:36.792Z" }, + { url = "https://files.pythonhosted.org/packages/d3/dc/d2df02854aec5d47659acfb2be352eecc691845b2f86e99c84f1010a8671/pandas-3.0.6-cp311-cp311-win_amd64.whl", hash = "sha256:2e5fa32ff162dfdbc280157d664f44d23049ae414725af9676df339c501d82cd", size = 9859246, upload-time = "2026-09-17T23:20:43.976Z" }, + { url = "https://files.pythonhosted.org/packages/79/1e/2a30df0d7dede5c195300a1820b0bc21cea3aa24e4c8b6c4431565ecc79a/pandas-3.0.6-cp311-cp311-win_arm64.whl", hash = "sha256:5e75072773c1b2f7cb63faa3a6f562aede11f3976f68ed34cb538bc091a28171", size = 9106923, upload-time = "2026-09-17T23:20:46.611Z" }, +] + +[[package]] +name = "pillow" +version = "13.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/d7/af6af1b8cc55e07cb0489d5b0950bf5a9bb1461eeba825700b6d8d0e26ea/pillow-13.0.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb", size = 5592324, upload-time = "2026-10-16T22:15:24.672Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d2/2c12cb4fbb5d95f38d1001ff3d95fafcb830077018cba40e56a8f932dfbc/pillow-13.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061", size = 4856298, upload-time = "2026-10-16T22:15:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/229b27472483a4801ea94990815e710391836afdf987b4b722b62bd75db6/pillow-13.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0", size = 6517304, upload-time = "2026-10-16T22:15:29.43Z" }, + { url = "https://files.pythonhosted.org/packages/36/46/f509b74787f40ce0627501089d630b2c741b63b244c1f40b640b3b01e181/pillow-13.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c", size = 7140667, upload-time = "2026-10-16T22:15:31.368Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/5a398b8ec2c37145397d6461c0b551c23ec03072aa64f357aed25e582b00/pillow-13.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f", size = 6610583, upload-time = "2026-10-16T22:15:34.025Z" }, + { url = "https://files.pythonhosted.org/packages/4f/7b/f2f1109b230fd4e2d57ab2305de31adc37ea9b4ff8719436c623cb484415/pillow-13.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806", size = 7218241, upload-time = "2026-10-16T22:15:36.214Z" }, + { url = "https://files.pythonhosted.org/packages/ab/d3/069edb9083b267746baf59756282cacef904d3475c5288c7216fb5195a98/pillow-13.0.0-cp311-cp311-win32.whl", hash = "sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5", size = 6515278, upload-time = "2026-10-16T22:15:38.129Z" }, + { url = "https://files.pythonhosted.org/packages/7d/f6/6e2d96413e4c9dbec12ea584d9e646d602877d4cce3ea669099f959deac6/pillow-13.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3", size = 7278471, upload-time = "2026-10-16T22:15:40.286Z" }, + { url = "https://files.pythonhosted.org/packages/70/e7/baff21f8cb60496c8c250609501b88919eeedb4088d3da106f6c62f3f3c0/pillow-13.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13", size = 2698981, upload-time = "2026-10-16T22:15:42.637Z" }, + { url = "https://files.pythonhosted.org/packages/68/c0/fb7b1caf25ed5ac5d46116f09b8b0706b9559833c65c667cecb1a53153f2/pillow-13.0.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca", size = 5521630, upload-time = "2026-10-16T22:17:50.008Z" }, + { url = "https://files.pythonhosted.org/packages/1a/e6/4d11d5b1137f4fc080605cce410cfaae4f303ad400bdec75d27d3083fa29/pillow-13.0.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039", size = 4806023, upload-time = "2026-10-16T22:17:51.932Z" }, + { url = "https://files.pythonhosted.org/packages/f1/45/0923202a658e8ff6aafd72c1a4395ebadcdebaa182c437d8595d3dd3db32/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad", size = 5464831, upload-time = "2026-10-16T22:17:53.742Z" }, + { url = "https://files.pythonhosted.org/packages/07/52/d3e38f0cad1dadea2a658b9a7d6ba8a04048f5ae14f011b806e5c3bd6bcb/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2", size = 6043133, upload-time = "2026-10-16T22:17:55.625Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f9/2ed7685980c1d64f8131a7d87a19c369424747577152622b73ddeff163b7/pillow-13.0.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c", size = 7365208, upload-time = "2026-10-16T22:17:57.509Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.14.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/9a/8475be631fb33ca1466915e70fd594c42a4e84b512db650eaa14f90fe75d/platformdirs-4.14.5.tar.gz", hash = "sha256:32e9921db7385aa8169bee4fe9501923e5715ba9fb7ea3b9c69b0d8e0639f7a1", size = 71464, upload-time = "2026-11-04T16:54:50.358Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7c/ae/ecbbbfd0e4343a6a521d49b3c8656fb4643dee2a4f6eaf941cf3280391a8/platformdirs-4.14.5-py3-none-any.whl", hash = "sha256:8e778c6fa421516f4d3369449f8df3b0e1b72c0e0005fe88e3ec772d0a14e750", size = 35402, upload-time = "2026-11-04T16:54:48.875Z" }, +] + +[[package]] +name = "propcache" +version = "0.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b3/9a/9fbf4e4ec0c2d7f1c32519fff782ef467859b8faa9fbc5331a96f6395d43/propcache-0.5.4.tar.gz", hash = "sha256:ff6b113f50bc066a698db5d944d2c6dc7507168dd3341e255a8892fd0715a558", size = 61545, upload-time = "2026-09-16T00:17:14.386Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/40/14b21e505b7921617466576423f188a5c9caddfdaa1cf4b2b8a83d8fe216/propcache-0.5.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:897d1ddf6716e8f47200f7aad9a0efa6cc7586df66c6defa572f9eab379c078e", size = 86393, upload-time = "2026-09-16T00:14:06.9Z" }, + { url = "https://files.pythonhosted.org/packages/e7/4b/5a52e1a7b43563f7d408814194bb23cc8bf214eb6b86639b667a33a8d0d0/propcache-0.5.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9cbfff4423eef4cc6cafc021469641a2b835f610b2647a6c5281903e21b8670d", size = 50431, upload-time = "2026-09-16T00:14:08.025Z" }, + { url = "https://files.pythonhosted.org/packages/05/cf/b5248180bf056cc76acc60c9c6e8c0ebbfdbd1c6cffd31fd14996927b7c8/propcache-0.5.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3fc24f209c1b7f7f688b66b98293954f5504279760999b58920ee12dd8471c1d", size = 52116, upload-time = "2026-09-16T00:14:09.114Z" }, + { url = "https://files.pythonhosted.org/packages/86/a8/7c6cd6bfead1a11f2e411e688640e6d26574cb0bde7dcaa7423b0b65ed7a/propcache-0.5.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:62530ca89187827e4a4fe733f971abe81a7542eeea48ff61995f19b64d7199c8", size = 238729, upload-time = "2026-09-16T00:14:10.357Z" }, + { url = "https://files.pythonhosted.org/packages/5c/b4/442715b2e980df51be52d203549279e027728f24c80b00b5e525e31cd5ea/propcache-0.5.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:56fc3f7599528db40b1efa0889a620116e2704144495273d66066e8164e45838", size = 246121, upload-time = "2026-09-16T00:14:11.735Z" }, + { url = "https://files.pythonhosted.org/packages/bc/5d/df0684fc2b1732a01a7bec26d7897369022712422d25b09c37ce7dbc88a2/propcache-0.5.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4f2d880ff60f45898f4acfa152aac8d04e3ee627d90ff4003491bf92239d5757", size = 251735, upload-time = "2026-09-16T00:14:13.053Z" }, + { url = "https://files.pythonhosted.org/packages/c7/06/519a5ebb48b6f94beb48396e55c905f12246a25c3a3608a7ec7bceabf50e/propcache-0.5.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6e9368e87a3efc285e559131092c5db643eb8e56de4ee42064d5baec22ef2bb5", size = 235381, upload-time = "2026-09-16T00:14:14.398Z" }, + { url = "https://files.pythonhosted.org/packages/3c/07/1e0a9bb310830f2245edbd5cd3c6d24a783c053c4efd8e08e386e513c940/propcache-0.5.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:004e685b315646c410771836e72a44f143bbe624f29653a42687815069a303d5", size = 208973, upload-time = "2026-09-16T00:14:15.715Z" }, + { url = "https://files.pythonhosted.org/packages/62/5c/9324fab27d6088eecc47fe4332bf7aaf8c1ded93c36f558391e8a06d41a7/propcache-0.5.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:594eb4c6ec35e7179b058481f4e9f02521b56de16fa577c4b85c76fb1bf8a9f8", size = 233897, upload-time = "2026-09-16T00:14:17.25Z" }, + { url = "https://files.pythonhosted.org/packages/9c/a3/570d92fc952eae93b676f3a1568f4b89264102abd3c982ab6a9ebec58dcf/propcache-0.5.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:2dba2f02d2d5c09ef8a0e6c1a42aeaa451f4be9898cb00b04fe98717da2eb23b", size = 223512, upload-time = "2026-09-16T00:14:18.87Z" }, + { url = "https://files.pythonhosted.org/packages/65/47/26810d889d89bba31db397e6a88f8984af775f5ed6bad0a29dce84324cff/propcache-0.5.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:c3ef2818d63bc86071e9d2989ae75a1bc32b8f7059cfd9f5abbbee70c32e2ed6", size = 239043, upload-time = "2026-09-16T00:14:20.366Z" }, + { url = "https://files.pythonhosted.org/packages/89/2d/f9c47691aa024c8299a3afacd78d22a01ab57eb627b481b6089708e71017/propcache-0.5.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:dd2ac8f5b643454c2cc6b6118b13da16e88f4a6434fc3ba61aca384029f04f36", size = 208218, upload-time = "2026-09-16T00:14:21.801Z" }, + { url = "https://files.pythonhosted.org/packages/74/6b/d510c0c378cabbf9d0ac7b663af6d00f2e9074073d93b20c85f24aa5c071/propcache-0.5.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:4054acf80d40456a0537f2913b349718649d8d6458a14ab7f48d0ce28c30869d", size = 240301, upload-time = "2026-09-16T00:14:23.121Z" }, + { url = "https://files.pythonhosted.org/packages/3d/80/c80f6adaaa1e51f0db2dce8c9b3714d94ec45e358a21f9a1910b10b40a80/propcache-0.5.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:40e94adb1e7d39ff28a8bd8d8b8fbd1df6b9f40976dbe379134f1ce058e532dd", size = 230785, upload-time = "2026-09-16T00:14:24.458Z" }, + { url = "https://files.pythonhosted.org/packages/d9/e2/c32a7df3f39caa7f11b2eb37ea5b6960a6946f2bc7c4b8ff97bbdf6d6b6e/propcache-0.5.4-cp311-cp311-win32.whl", hash = "sha256:9f86f7259efe2c951f43e57d471c9b41daa5bfc7db9f67189059cf1ae6d77fd9", size = 42747, upload-time = "2026-09-16T00:14:25.715Z" }, + { url = "https://files.pythonhosted.org/packages/0a/8a/3db6a3543d8101263b4c52978b6276a04ead2caff2c5ab880d934f47bd89/propcache-0.5.4-cp311-cp311-win_amd64.whl", hash = "sha256:e904d4d01f36bd6e197590be1533c44e06058771e0746dd073a8ebb3ef880858", size = 46268, upload-time = "2026-09-16T00:14:26.996Z" }, + { url = "https://files.pythonhosted.org/packages/41/07/5222e2665bbf6e45847492ecbf3b9f3e4975a0ae300e5fd465df7d48ce55/propcache-0.5.4-cp311-cp311-win_arm64.whl", hash = "sha256:d42a9a856a4a6e2f6c10f1318c07e7daa498d6593abe745c71dae4521a26ca39", size = 43547, upload-time = "2026-09-16T00:14:28.143Z" }, + { url = "https://files.pythonhosted.org/packages/f5/cd/785c64ed382f3f04201870267b02783f63b4678c2acfddc177a3ebcc2727/propcache-0.5.4-py3-none-any.whl", hash = "sha256:62c60aec739ed00124573cce1178138fd690c7676352d67a37328c1cf51d7468", size = 16338, upload-time = "2026-09-16T00:17:13.106Z" }, +] + +[[package]] +name = "protobuf" +version = "6.33.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/66/70/e908e9c5e52ef7c3a6c7902c9dfbb34c7e29c25d2f81ade3856445fd5c94/protobuf-6.33.6.tar.gz", hash = "sha256:a6768d25248312c297558af96a9f9c929e8c4cee0659cb07e780731095f38135", size = 444531, upload-time = "2026-03-18T19:05:00.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/9f/2f509339e89cfa6f6a4c4ff50438db9ca488dec341f7e454adad60150b00/protobuf-6.33.6-cp310-abi3-win32.whl", hash = "sha256:7d29d9b65f8afef196f8334e80d6bc1d5d4adedb449971fefd3723824e6e77d3", size = 425739, upload-time = "2026-03-18T19:04:48.373Z" }, + { url = "https://files.pythonhosted.org/packages/76/5d/683efcd4798e0030c1bab27374fd13a89f7c2515fb1f3123efdfaa5eab57/protobuf-6.33.6-cp310-abi3-win_amd64.whl", hash = "sha256:0cd27b587afca21b7cfa59a74dcbd48a50f0a6400cfb59391340ad729d91d326", size = 437089, upload-time = "2026-03-18T19:04:50.381Z" }, + { url = "https://files.pythonhosted.org/packages/5c/01/a3c3ed5cd186f39e7880f8303cc51385a198a81469d53d0fdecf1f64d929/protobuf-6.33.6-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:9720e6961b251bde64edfdab7d500725a2af5280f3f4c87e57c0208376aa8c3a", size = 427737, upload-time = "2026-03-18T19:04:51.866Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/b3c01fdec7d2f627b3a6884243ba328c1217ed2d978def5c12dc50d328a3/protobuf-6.33.6-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:e2afbae9b8e1825e3529f88d514754e094278bb95eadc0e199751cdd9a2e82a2", size = 324610, upload-time = "2026-03-18T19:04:53.096Z" }, + { url = "https://files.pythonhosted.org/packages/9b/ca/25afc144934014700c52e05103c2421997482d561f3101ff352e1292fb81/protobuf-6.33.6-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:c96c37eec15086b79762ed265d59ab204dabc53056e3443e702d2681f4b39ce3", size = 339381, upload-time = "2026-03-18T19:04:54.616Z" }, + { url = "https://files.pythonhosted.org/packages/16/92/d1e32e3e0d894fe00b15ce28ad4944ab692713f2e7f0a99787405e43533a/protobuf-6.33.6-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:e9db7e292e0ab79dd108d7f1a94fe31601ce1ee3f7b79e0692043423020b0593", size = 323436, upload-time = "2026-03-18T19:04:55.768Z" }, + { url = "https://files.pythonhosted.org/packages/c4/72/02445137af02769918a93807b2b7890047c32bfb9f90371cbc12688819eb/protobuf-6.33.6-py3-none-any.whl", hash = "sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901", size = 170656, upload-time = "2026-03-18T19:04:59.826Z" }, +] + +[[package]] +name = "psutil" +version = "7.1.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e1/88/bdd0a41e5857d5d703287598cbf08dad90aed56774ea52ae071bae9071b6/psutil-7.1.3.tar.gz", hash = "sha256:6c86281738d77335af7aec228328e944b30930899ea760ecf33a4dba66be5e74", size = 489059, upload-time = "2025-11-02T12:25:54.619Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/94/46b9154a800253e7ecff5aaacdf8ebf43db99de4a2dfa18575b02548654e/psutil-7.1.3-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2bdbcd0e58ca14996a42adf3621a6244f1bb2e2e528886959c72cf1e326677ab", size = 238359, upload-time = "2025-11-02T12:26:25.284Z" }, + { url = "https://files.pythonhosted.org/packages/68/3a/9f93cff5c025029a36d9a92fef47220ab4692ee7f2be0fba9f92813d0cb8/psutil-7.1.3-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:bc31fa00f1fbc3c3802141eede66f3a2d51d89716a194bf2cd6fc68310a19880", size = 239171, upload-time = "2025-11-02T12:26:27.23Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b1/5f49af514f76431ba4eea935b8ad3725cdeb397e9245ab919dbc1d1dc20f/psutil-7.1.3-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3bb428f9f05c1225a558f53e30ccbad9930b11c3fc206836242de1091d3e7dd3", size = 263261, upload-time = "2025-11-02T12:26:29.48Z" }, + { url = "https://files.pythonhosted.org/packages/e0/95/992c8816a74016eb095e73585d747e0a8ea21a061ed3689474fabb29a395/psutil-7.1.3-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56d974e02ca2c8eb4812c3f76c30e28836fffc311d55d979f1465c1feeb2b68b", size = 264635, upload-time = "2025-11-02T12:26:31.74Z" }, + { url = "https://files.pythonhosted.org/packages/55/4c/c3ed1a622b6ae2fd3c945a366e64eb35247a31e4db16cf5095e269e8eb3c/psutil-7.1.3-cp37-abi3-win_amd64.whl", hash = "sha256:f39c2c19fe824b47484b96f9692932248a54c43799a84282cfe58d05a6449efd", size = 247633, upload-time = "2025-11-02T12:26:33.887Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ad/33b2ccec09bf96c2b2ef3f9a6f66baac8253d7565d8839e024a6b905d45d/psutil-7.1.3-cp37-abi3-win_arm64.whl", hash = "sha256:bd0d69cee829226a761e92f28140bec9a5ee9d5b4fb4b0cc589068dbfff559b1", size = 244608, upload-time = "2025-11-02T12:26:36.136Z" }, +] + +[[package]] +name = "pyarrow" +version = "17.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/27/4e/ea6d43f324169f8aec0e57569443a38bab4b398d09769ca64f7b4d467de3/pyarrow-17.0.0.tar.gz", hash = "sha256:4beca9521ed2c0921c1023e68d097d0299b62c362639ea315572a58f3f50fd28", size = 1112479, upload-time = "2024-07-17T10:41:25.092Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/46/ce89f87c2936f5bb9d879473b9663ce7a4b1f4359acc2f0eb39865eaa1af/pyarrow-17.0.0-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:1c8856e2ef09eb87ecf937104aacfa0708f22dfeb039c363ec99735190ffb977", size = 29028748, upload-time = "2024-07-16T10:30:02.609Z" }, + { url = "https://files.pythonhosted.org/packages/8d/8e/ce2e9b2146de422f6638333c01903140e9ada244a2a477918a368306c64c/pyarrow-17.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2e19f569567efcbbd42084e87f948778eb371d308e137a0f97afe19bb860ccb3", size = 27190965, upload-time = "2024-07-16T10:30:10.718Z" }, + { url = "https://files.pythonhosted.org/packages/3b/c8/5675719570eb1acd809481c6d64e2136ffb340bc387f4ca62dce79516cea/pyarrow-17.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b244dc8e08a23b3e352899a006a26ae7b4d0da7bb636872fa8f5884e70acf15", size = 39269081, upload-time = "2024-07-16T10:30:18.878Z" }, + { url = "https://files.pythonhosted.org/packages/5e/78/3931194f16ab681ebb87ad252e7b8d2c8b23dad49706cadc865dff4a1dd3/pyarrow-17.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0b72e87fe3e1db343995562f7fff8aee354b55ee83d13afba65400c178ab2597", size = 39864921, upload-time = "2024-07-16T10:30:27.008Z" }, + { url = "https://files.pythonhosted.org/packages/d8/81/69b6606093363f55a2a574c018901c40952d4e902e670656d18213c71ad7/pyarrow-17.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:dc5c31c37409dfbc5d014047817cb4ccd8c1ea25d19576acf1a001fe07f5b420", size = 38740798, upload-time = "2024-07-16T10:30:34.814Z" }, + { url = "https://files.pythonhosted.org/packages/4c/21/9ca93b84b92ef927814cb7ba37f0774a484c849d58f0b692b16af8eebcfb/pyarrow-17.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:e3343cb1e88bc2ea605986d4b94948716edc7a8d14afd4e2c097232f729758b4", size = 39871877, upload-time = "2024-07-16T10:30:42.672Z" }, + { url = "https://files.pythonhosted.org/packages/30/d1/63a7c248432c71c7d3ee803e706590a0b81ce1a8d2b2ae49677774b813bb/pyarrow-17.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:a27532c38f3de9eb3e90ecab63dfda948a8ca859a66e3a47f5f42d1e403c4d03", size = 25151089, upload-time = "2024-07-16T10:30:49.279Z" }, +] + +[[package]] +name = "pyarrow" +version = "20.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/a2/ee/a7810cb9f3d6e9238e61d312076a9859bf3668fd21c69744de9532383912/pyarrow-20.0.0.tar.gz", hash = "sha256:febc4a913592573c8d5805091a6c2b5064c8bd6e002131f01061797d91c783c1", size = 1125187, upload-time = "2025-04-27T12:34:23.264Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/a2/b7930824181ceadd0c63c1042d01fa4ef63eee233934826a7a2a9af6e463/pyarrow-20.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:24ca380585444cb2a31324c546a9a56abbe87e26069189e14bdba19c86c049f0", size = 30856035, upload-time = "2025-04-27T12:28:40.78Z" }, + { url = "https://files.pythonhosted.org/packages/9b/18/c765770227d7f5bdfa8a69f64b49194352325c66a5c3bb5e332dfd5867d9/pyarrow-20.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:95b330059ddfdc591a3225f2d272123be26c8fa76e8c9ee1a77aad507361cfdb", size = 32309552, upload-time = "2025-04-27T12:28:47.051Z" }, + { url = "https://files.pythonhosted.org/packages/44/fb/dfb2dfdd3e488bb14f822d7335653092dde150cffc2da97de6e7500681f9/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5f0fb1041267e9968c6d0d2ce3ff92e3928b243e2b6d11eeb84d9ac547308232", size = 41334704, upload-time = "2025-04-27T12:28:55.064Z" }, + { url = "https://files.pythonhosted.org/packages/58/0d/08a95878d38808051a953e887332d4a76bc06c6ee04351918ee1155407eb/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b8ff87cc837601532cc8242d2f7e09b4e02404de1b797aee747dd4ba4bd6313f", size = 42399836, upload-time = "2025-04-27T12:29:02.13Z" }, + { url = "https://files.pythonhosted.org/packages/f3/cd/efa271234dfe38f0271561086eedcad7bc0f2ddd1efba423916ff0883684/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:7a3a5dcf54286e6141d5114522cf31dd67a9e7c9133d150799f30ee302a7a1ab", size = 40711789, upload-time = "2025-04-27T12:29:09.951Z" }, + { url = "https://files.pythonhosted.org/packages/46/1f/7f02009bc7fc8955c391defee5348f510e589a020e4b40ca05edcb847854/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:a6ad3e7758ecf559900261a4df985662df54fb7fdb55e8e3b3aa99b23d526b62", size = 42301124, upload-time = "2025-04-27T12:29:17.187Z" }, + { url = "https://files.pythonhosted.org/packages/4f/92/692c562be4504c262089e86757a9048739fe1acb4024f92d39615e7bab3f/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6bb830757103a6cb300a04610e08d9636f0cd223d32f388418ea893a3e655f1c", size = 42916060, upload-time = "2025-04-27T12:29:24.253Z" }, + { url = "https://files.pythonhosted.org/packages/a4/ec/9f5c7e7c828d8e0a3c7ef50ee62eca38a7de2fa6eb1b8fa43685c9414fef/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96e37f0766ecb4514a899d9a3554fadda770fb57ddf42b63d80f14bc20aa7db3", size = 44547640, upload-time = "2025-04-27T12:29:32.782Z" }, + { url = "https://files.pythonhosted.org/packages/54/96/46613131b4727f10fd2ffa6d0d6f02efcc09a0e7374eff3b5771548aa95b/pyarrow-20.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:3346babb516f4b6fd790da99b98bed9708e3f02e734c84971faccb20736848dc", size = 25781491, upload-time = "2025-04-27T12:29:38.464Z" }, +] + +[[package]] +name = "pydantic" +version = "2.14.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/fc/1203d011145c98ddce3cd2f505bb54375ef8d43223053df6bfcf3c746f46/pydantic-2.14.3.tar.gz", hash = "sha256:1054f237f4d4733e5a30e1e2333bd33a2004ab9ab1510bd053a9a31bb48e232d", size = 925636, upload-time = "2026-11-05T09:17:04.686Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/b8/b864503789ef5c58597d2a7b4adbee62c26440ab1e682581fc6838df8947/pydantic-2.14.3-py3-none-any.whl", hash = "sha256:3f7b347782ab7e4cf4c798496ae3a82787d9f21ec12676a9c564355eeef8daa8", size = 494071, upload-time = "2026-11-05T09:17:02.426Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.50.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9c/0f/34f9ce4ba701dd0b815033ef94d99b56f66200e578ee6052aa3ac26f064e/pydantic_core-2.50.4.tar.gz", hash = "sha256:aead3b74b68396bf0feab5d57e050b730ded7df55853c1e048a87e00aaf033c6", size = 522249, upload-time = "2026-11-05T09:15:26.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/00/85e80811834d7cbd9bc228f9b5cdf8ec0edd69b55351ad720aac8c412d8c/pydantic_core-2.50.4-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:3e547ceec1da7382f01f9e13963023e53367a71802c88778b21b9645a077cbdf", size = 2170584, upload-time = "2026-11-05T09:11:41.139Z" }, + { url = "https://files.pythonhosted.org/packages/a3/f1/438de1fb99d717dcc6521922478dc16ef7b757302d4fc1f7faba3aaeac09/pydantic_core-2.50.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c813ada7a651193acda85b6bc1cf12abd4b37cd25c7c6a75d7183512cc374969", size = 2128471, upload-time = "2026-11-05T09:11:42.65Z" }, + { url = "https://files.pythonhosted.org/packages/b7/74/f21ab568c6d3f315988b40e53f809c95b63fafc5403332963aa6dfc2c054/pydantic_core-2.50.4-cp311-cp311-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:57fa0a9490785139f1a4e4f43891830d55dfe4408845c0c9cb5eff4aeaf75f69", size = 2281509, upload-time = "2026-11-05T09:11:44.359Z" }, + { url = "https://files.pythonhosted.org/packages/a1/42/24ed3ea8e2fb6463c9ba5b8b1f089e69040905c7fd81dcfa6f52fcc692d5/pydantic_core-2.50.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:30d4dc35bc0eea52202a90b3820445ee0072c820241bfa710a623a078c9b267b", size = 2128064, upload-time = "2026-11-05T09:11:46.01Z" }, + { url = "https://files.pythonhosted.org/packages/d6/d1/44f541b2c18a46df6f18281a557acefeb5bbf0733a0b80b0a5e835e10ee4/pydantic_core-2.50.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:789f88dea57841cdebef392b5d6e90444d767117e9ff2e0d9172df5c9de6690c", size = 2214472, upload-time = "2026-11-05T09:11:47.503Z" }, + { url = "https://files.pythonhosted.org/packages/bd/1b/e9a9ad8733e8051abca9e4acce37ba3ddd13930fd3b8730f4c7816fa979a/pydantic_core-2.50.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:d690121e80ab16e623415351ab24713534d4e500b3cadff216409cb6826063d4", size = 2401153, upload-time = "2026-11-05T09:11:49.403Z" }, + { url = "https://files.pythonhosted.org/packages/79/84/d88e8e6aa42d4d677666d6625db9177ad6851be9e7564a25aeb0b0cbcaf2/pydantic_core-2.50.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b42f64825f5d750228f08318a9bf4d723b7ecb4c472aedcb3013c3ec2dc1f949", size = 2453307, upload-time = "2026-11-05T09:11:51.118Z" }, + { url = "https://files.pythonhosted.org/packages/56/51/cbb7a1bc0196ff94d3478d265eed7449f811759988eb760d41f4edd0893b/pydantic_core-2.50.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0574866e05f6adeecc520d87e87dd06210c0a51706341f6ef8421572f5a64444", size = 2253434, upload-time = "2026-11-05T09:11:52.997Z" }, + { url = "https://files.pythonhosted.org/packages/9e/04/206b4881d631033ae88f005da6e11bd610c850e1850217342c03053d253b/pydantic_core-2.50.4-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:dcf2c7eaaa4cafe8e49b017e5bb49e76e084ab6f0cd712ee4019c812b5cf68b8", size = 2279365, upload-time = "2026-11-05T09:11:54.822Z" }, + { url = "https://files.pythonhosted.org/packages/a1/7c/d815b5a3f83069b283d3b6a2e61de6e14baac3b20c6cd3418e9e629551cf/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:3b8ee2589a082739c522c1fe4be227412fcf108b903abb6672ae2f5570558882", size = 2319407, upload-time = "2026-11-05T09:11:56.46Z" }, + { url = "https://files.pythonhosted.org/packages/ee/00/c9a483276d1052d5142e1e01eccac97d939f83a3a3fd94c4766495a9b807/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:aec3c2d741a8e3ee993de7f95f37afb51e31b169c95dbd29da4cf6688f340914", size = 2489900, upload-time = "2026-11-05T09:11:58.102Z" }, + { url = "https://files.pythonhosted.org/packages/2d/b5/8cd8ee29a1d63ad47f95593384df92476cef6896c644f280db0748b8e76b/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8923fcd49f875e8a0448d7223d1fdf1a9973ae2d1f20d4158753ceb8909facd2", size = 2497732, upload-time = "2026-11-05T09:11:59.928Z" }, + { url = "https://files.pythonhosted.org/packages/60/31/050a48c0c373df16442ac07f3fa167414bb0e22f54a3e886f6d6cb7ad1d4/pydantic_core-2.50.4-cp311-cp311-win32.whl", hash = "sha256:fc04affef30be98c1f36f0c422a4061ef618fdc1dde79f5ad5458dd496fecffa", size = 2132347, upload-time = "2026-11-05T09:12:01.928Z" }, + { url = "https://files.pythonhosted.org/packages/c6/06/cebeeb7a8e87b42a3d8bc189d0d400e47df5d1736cb326764bae8a74c433/pydantic_core-2.50.4-cp311-cp311-win_amd64.whl", hash = "sha256:15bece43a02ad543c621c8305e67dedb5f27d378c5ba741e5a2c36523f8ef37f", size = 2255970, upload-time = "2026-11-05T09:12:03.888Z" }, + { url = "https://files.pythonhosted.org/packages/46/db/5b4bf14347da658c994483043fbabffedcab98929c41c261ec168c3c1f87/pydantic_core-2.50.4-cp311-cp311-win_arm64.whl", hash = "sha256:e498900bfbf7ddddd862f810440c09e9b81674739e8a11d619b40906dccd4a9a", size = 2196799, upload-time = "2026-11-05T09:12:05.389Z" }, + { url = "https://files.pythonhosted.org/packages/d8/18/3ca5b3b8ce7a540305e6856d013e9c6b9c0fef93258fef6038db0beb233a/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:39f489ce31272073e6e146f6781690f9c1ee8c126836e6403361ef91154d89fe", size = 2166960, upload-time = "2026-11-05T09:15:06.902Z" }, + { url = "https://files.pythonhosted.org/packages/a3/60/65d725001bffcde0170f6d37ae8bccce715e5311122eb6127f698115957e/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:5b26e5f1793b96cdc60242bf38da86ff24a27a708aa396214cac9b534bf571c7", size = 2085636, upload-time = "2026-11-05T09:15:08.395Z" }, + { url = "https://files.pythonhosted.org/packages/ac/12/934cf1d44a3fee3c47231d4690dddee19264150c3aa59a3ddf66fa43454d/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:7210398a1607ad607dc73196e575b3148b00a333cbb602ddbe1b60ba54554f43", size = 2284621, upload-time = "2026-11-05T09:15:09.82Z" }, + { url = "https://files.pythonhosted.org/packages/c4/91/52248eee98d76f8d9239166d24928f805292df16729109f4f189cdb59be4/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2f42584e5785385f681163a42506cab0d51295e17599a648396c52a7046c1372", size = 2277673, upload-time = "2026-11-05T09:15:11.236Z" }, + { url = "https://files.pythonhosted.org/packages/9f/89/900a7970ef19843aa79522a95b461e9c365b7fedd7ee80ef28a84dae9a41/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:2039e323acee9abfec1fb5f661776e8965fe5928f3b7f8431900a774cba5c317", size = 2297354, upload-time = "2026-11-05T09:15:12.798Z" }, + { url = "https://files.pythonhosted.org/packages/de/ec/053d829437f70070cdd7116a0257cc0da651103328ff1e9e82954c45efd6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:71ade6d2e445839350d589ff99bbddfde16f3f32db28da5c894a09f99c8b2a03", size = 2469913, upload-time = "2026-11-05T09:15:14.319Z" }, + { url = "https://files.pythonhosted.org/packages/80/af/207c821cb0813e16d630660e0073491e3ab07370efaa6fa0b8b10fffb7b6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:d7d406709ae924cf0b08b8282ca2f0e1c90526911d93bc040557cbc83b74c55f", size = 2503746, upload-time = "2026-11-05T09:15:15.736Z" }, + { url = "https://files.pythonhosted.org/packages/e7/ca/8a053f24e22d8150349cabaecb2f35c89dcf07fbaadb5e48295184dd0e5b/pydantic_core-2.50.4-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:7472c39480ccc11dda69a196d1b7c7a6b48eb6594b77f05d945599d3e47f731c", size = 2333540, upload-time = "2026-11-05T09:15:17.883Z" }, + { url = "https://files.pythonhosted.org/packages/ac/9d/41b374c62cdb87f84081e2ef2963a115eacc6284a26dbc96bb83568e83ec/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_10_12_x86_64.whl", hash = "sha256:b67d38e8bb0ade7e6e84575e4bb153fab35b122458077273aeb08fdf12be9d2c", size = 2166962, upload-time = "2026-11-05T09:15:20.276Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/51ef440ee346d4388a2c4a3ac4b271fcc7b1d3ff68be8da2ed2be4d488b0/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:4eda7e3fdef382b7d4492745988a5baaf6953923a337f8b9dde5f76fa8afde20", size = 2085634, upload-time = "2026-11-05T09:15:21.953Z" }, + { url = "https://files.pythonhosted.org/packages/4b/5f/c9ed62b96beb9050db221d29e81856b6e28f277db601f8b0c3a08f8cf913/pydantic_core-2.50.4-pp311-pypy311_pp80-manylinux_2_28_x86_64.whl", hash = "sha256:474f7e598c7902165662a5d5160d3fce31037890a2975a9871ebf7c05862300b", size = 2277804, upload-time = "2026-11-05T09:15:23.836Z" }, + { url = "https://files.pythonhosted.org/packages/63/bd/b912a5e251ef10ed7be5e543a2bfbeebb0c79bf6302bee786f8dc3bf4341/pydantic_core-2.50.4-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:3e0b395648c6cb871bceb2906907f255dc876ec425f2d5b024e129985cea8519", size = 2333539, upload-time = "2026-11-05T09:15:25.354Z" }, +] + +[[package]] +name = "pyparsing" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/11/b213bebff182584360cb8d17c72c1677fec5c5c228de439e63bcf8ab1c8f/pyparsing-3.3.3.tar.gz", hash = "sha256:928ae7e20211f3b6f3915a72f06a0cfd29ab9d24279dd6346b6b1a7146397d36", size = 1050487, upload-time = "2026-09-20T20:59:05.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" }, +] + +[[package]] +name = "python-dateutil" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/16/a95b6757765b7b031c9374925bb718d55e0a9ba8a1b6a12d25962ea44347/pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", size = 185826, upload-time = "2025-09-25T21:31:58.655Z" }, + { url = "https://files.pythonhosted.org/packages/16/19/13de8e4377ed53079ee996e1ab0a9c33ec2faf808a4647b7b4c0d46dd239/pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", size = 175577, upload-time = "2025-09-25T21:32:00.088Z" }, + { url = "https://files.pythonhosted.org/packages/0c/62/d2eb46264d4b157dae1275b573017abec435397aa59cbcdab6fc978a8af4/pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", size = 775556, upload-time = "2025-09-25T21:32:01.31Z" }, + { url = "https://files.pythonhosted.org/packages/10/cb/16c3f2cf3266edd25aaa00d6c4350381c8b012ed6f5276675b9eba8d9ff4/pyyaml-6.0.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00", size = 882114, upload-time = "2025-09-25T21:32:03.376Z" }, + { url = "https://files.pythonhosted.org/packages/71/60/917329f640924b18ff085ab889a11c763e0b573da888e8404ff486657602/pyyaml-6.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d", size = 806638, upload-time = "2025-09-25T21:32:04.553Z" }, + { url = "https://files.pythonhosted.org/packages/dd/6f/529b0f316a9fd167281a6c3826b5583e6192dba792dd55e3203d3f8e655a/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a", size = 767463, upload-time = "2025-09-25T21:32:06.152Z" }, + { url = "https://files.pythonhosted.org/packages/f2/6a/b627b4e0c1dd03718543519ffb2f1deea4a1e6d42fbab8021936a4d22589/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4", size = 794986, upload-time = "2025-09-25T21:32:07.367Z" }, + { url = "https://files.pythonhosted.org/packages/45/91/47a6e1c42d9ee337c4839208f30d9f09caa9f720ec7582917b264defc875/pyyaml-6.0.3-cp311-cp311-win32.whl", hash = "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b", size = 142543, upload-time = "2025-09-25T21:32:08.95Z" }, + { url = "https://files.pythonhosted.org/packages/da/e3/ea007450a105ae919a72393cb06f122f288ef60bba2dc64b26e2646fa315/pyyaml-6.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf", size = 158763, upload-time = "2025-09-25T21:32:09.96Z" }, +] + +[[package]] +name = "regex" +version = "2026.11.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/61/27/a5afeb952577b84ee5fe48b8b9ce47ae662dbb69cc5b76c28eff98f83b1e/regex-2026.11.9.tar.gz", hash = "sha256:316a70fbd70e999c9664681cb0eb5b4982b2cc0f623c7c86a8a112e1bd4c6277", size = 419513, upload-time = "2026-11-09T00:42:09.786Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/cd/83393cd04d1cdafb07dc6d3e4f6f40455c7d54edcfb7513a51c632a2fa32/regex-2026.11.9-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bc0414bae708e91fa635af848ea1fdc13e442f30497077da562014f88ac67436", size = 496166, upload-time = "2026-11-09T00:39:39.152Z" }, + { url = "https://files.pythonhosted.org/packages/13/90/65cd23cc77094ea6953a7f4f9808539611b71881b7d91729243fcaa43109/regex-2026.11.9-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:26f5137412492f043d13903b8ee3bbc464a73c67ec9432e187f5a5eef25c398f", size = 295747, upload-time = "2026-11-09T00:39:40.41Z" }, + { url = "https://files.pythonhosted.org/packages/3d/61/6523251b377f38be938342fd52da4aead1a1d1b79ce137d4412e5b1eb79e/regex-2026.11.9-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:cf8ba77a8d23fac7912cd9890a49d8f006106147bb80312c9954558b24ec7f95", size = 292719, upload-time = "2026-11-09T00:39:41.711Z" }, + { url = "https://files.pythonhosted.org/packages/97/5c/59cceda8ed285cb277f90f22b220c89576a38ebd1f2d7f0af198af98a5c7/regex-2026.11.9-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c876a5e3992b5f14709c7260188929174247485ed3f940bd94d4beb70abbfed3", size = 799904, upload-time = "2026-11-09T00:39:43.023Z" }, + { url = "https://files.pythonhosted.org/packages/9b/d0/498c4f67179885a4baf3b4500ea371d671180c20e136844065c239fe95d4/regex-2026.11.9-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:49eecd9b855cc9e683fed1b258d4e22dcb8e7b3c82f09c5778ce154359607f09", size = 874027, upload-time = "2026-11-09T00:39:44.36Z" }, + { url = "https://files.pythonhosted.org/packages/33/b9/61d474ad8aa93022edb00f13fcaac44678a5ef858801c804ad7d201d048b/regex-2026.11.9-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2405a0e564a5a1226427b21ee02a70c64f33a10015a18e480039c8ddb46b4f00", size = 915647, upload-time = "2026-11-09T00:39:45.587Z" }, + { url = "https://files.pythonhosted.org/packages/82/14/ec0c0f9e600f308280b901b46dd6e0095b56017fc2216b2abe6182009655/regex-2026.11.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0447593c5f4e2b88446da7466c83fc913ddf191600bbb7aebc6c8856595ccfb1", size = 805976, upload-time = "2026-11-09T00:39:47.654Z" }, + { url = "https://files.pythonhosted.org/packages/5e/de/bf7d2789051771e637d36aab03adea41b1e5729fe0c2a3d1df5e85a422bb/regex-2026.11.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:727989b08b98af7592eb86af12ca4227c017579094d5893a76fdd20b319cd8cd", size = 807143, upload-time = "2026-11-09T00:39:48.999Z" }, + { url = "https://files.pythonhosted.org/packages/0d/14/1a62ebd94dc36f74e2bb7f37bb7d7faf3bfc013cc90c1b1463d157e20136/regex-2026.11.9-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b886e1b7be6c392ea99d1c04de9b7adb4774038a1041514dfc6d0c5fb1bee6c5", size = 780582, upload-time = "2026-11-09T00:39:50.189Z" }, + { url = "https://files.pythonhosted.org/packages/3e/9b/42ce68062387ad6cbc4e2c5dc36d7f25d7a4d7621b5a67b8cd1a913ff2b4/regex-2026.11.9-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f1ec6903dc8054129ccc9404a5aaf19e4fab9af98b03604c69db903da3c045a4", size = 788733, upload-time = "2026-11-09T00:39:51.267Z" }, + { url = "https://files.pythonhosted.org/packages/ff/17/8e5268e78894c2a979a1599f9261eb0ede9952028d0a2689fbd80f2998b5/regex-2026.11.9-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:5c31a4e92c02f5c9e85c37a3851b9f83a36d2afdaaa88368f0d29ac56d8c81b8", size = 863625, upload-time = "2026-11-09T00:39:52.437Z" }, + { url = "https://files.pythonhosted.org/packages/97/0a/82e544ef361afc84e85a47907210bd9d1ef5c887b11ae3e091317c699327/regex-2026.11.9-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3dbccc60fa24fa1bab1cffe580c9bcd6467a885b6260d5e419f6d13db8c3596f", size = 766599, upload-time = "2026-11-09T00:39:54.03Z" }, + { url = "https://files.pythonhosted.org/packages/bf/4b/6484189c5f81e668059464780802b4bd6023415655c9410e8668a0a52a29/regex-2026.11.9-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:b5ce8fd914c9eaedfefa444ed329fc5a80c723136bda90e9e69159c536854c52", size = 855980, upload-time = "2026-11-09T00:39:55.184Z" }, + { url = "https://files.pythonhosted.org/packages/59/f8/954254f0c28b8113b304f0a9fec86274ad043b997161bb019ece9a00e5b8/regex-2026.11.9-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ff675c20d54564cb2b6c480c2e4b362dcc3ce74887ee2d2e63037658a0f01ab5", size = 793610, upload-time = "2026-11-09T00:39:56.351Z" }, + { url = "https://files.pythonhosted.org/packages/d9/2e/c30c186c8e0d55f4fa6cc882fb3f7eb3731ad70ffc5f99d40e99f261fadc/regex-2026.11.9-cp311-cp311-win32.whl", hash = "sha256:dd679c8172c94291ccee40e17b03b6e34c553ad855a57dc52e811c3bb83403f1", size = 269436, upload-time = "2026-11-09T00:39:57.808Z" }, + { url = "https://files.pythonhosted.org/packages/b5/6a/c23207465db6bb7a98211e82e5f79dc5473abea56464960f1c705bda888a/regex-2026.11.9-cp311-cp311-win_amd64.whl", hash = "sha256:b75ea29155c988eb375325a9fd9270a550ea3427acf275d350538c5f83571abc", size = 281159, upload-time = "2026-11-09T00:39:58.824Z" }, + { url = "https://files.pythonhosted.org/packages/df/7e/fe3c59e5adec098cddf9d65ed5f6543c070a344527a20d20e6731d4e57da/regex-2026.11.9-cp311-cp311-win_arm64.whl", hash = "sha256:b9c9746f25607eabe931c42f25535c9461589e25a80879a361f9c02f7abb6dce", size = 279986, upload-time = "2026-11-09T00:39:59.892Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "rouge" +version = "1.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/db/e4/3420a1ab1e82a280fb6107f7ae99e88eb12383c978fe573c0c64d0327d6b/rouge-1.0.1.tar.gz", hash = "sha256:12b48346ca47d6bcf3c45061f315452b9ccec0620ee895ec85b7efc3d54aae34", size = 14292, upload-time = "2021-07-20T08:45:56.53Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/7c/650ae86f92460e9e8ef969cc5008b24798dcf56a9a8947d04c78f550b3f5/rouge-1.0.1-py3-none-any.whl", hash = "sha256:28d118536e8c774dc47d1d15ec266479b4dd0914c4672ce117d4002789bdc644", size = 13725, upload-time = "2021-07-20T08:45:54.605Z" }, +] + +[[package]] +name = "safetensors" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/a0/f718cda65b05407d228f97602cf60dca269c979867aa5beb25410de26cd3/safetensors-0.8.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0", size = 473568, upload-time = "2026-06-09T07:52:18.829Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b1/fa7c600e7dceae12e9606c7578cbc9ff1e1ed55844883ee5c92205e86226/safetensors-0.8.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25", size = 484562, upload-time = "2026-06-09T07:52:17.518Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" }, + { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" }, + { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" }, + { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" }, + { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" }, + { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" }, + { url = "https://files.pythonhosted.org/packages/0d/49/1e15de264dcc3b77943d2d0c56a95809956883b1c2d6d585c792523f180b/safetensors-0.8.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca", size = 559930, upload-time = "2026-06-09T07:52:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" }, + { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" }, + { url = "https://files.pythonhosted.org/packages/29/4b/1c19c509d56e01f4fbb3d0a2e597450f6cc04d1d56cf52defb0a62dfd715/safetensors-0.8.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d", size = 765683, upload-time = "2026-06-09T07:52:22.594Z" }, + { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" }, + { url = "https://files.pythonhosted.org/packages/8e/3f/73ccf82579412b4a71c4ca673f10b5f1f888d7cf5af7fe24f27d30307be4/safetensors-0.8.0-cp310-abi3-win32.whl", hash = "sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d", size = 342401, upload-time = "2026-06-09T07:52:28.895Z" }, + { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" }, + { url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" }, +] + +[[package]] +name = "scikit-learn" +version = "1.7.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "joblib" }, + { name = "numpy" }, + { name = "scipy" }, + { name = "threadpoolctl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/c2/a7855e41c9d285dfe86dc50b250978105dce513d6e459ea66a6aeb0e1e0c/scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda", size = 7193136, upload-time = "2025-09-09T08:21:29.075Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/83/564e141eef908a5863a54da8ca342a137f45a0bfb71d1d79704c9894c9d1/scikit_learn-1.7.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c7509693451651cd7361d30ce4e86a1347493554f172b1c72a39300fa2aea79e", size = 9331967, upload-time = "2025-09-09T08:20:32.421Z" }, + { url = "https://files.pythonhosted.org/packages/18/d6/ba863a4171ac9d7314c4d3fc251f015704a2caeee41ced89f321c049ed83/scikit_learn-1.7.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:0486c8f827c2e7b64837c731c8feff72c0bd2b998067a8a9cbc10643c31f0fe1", size = 8648645, upload-time = "2025-09-09T08:20:34.436Z" }, + { url = "https://files.pythonhosted.org/packages/ef/0e/97dbca66347b8cf0ea8b529e6bb9367e337ba2e8be0ef5c1a545232abfde/scikit_learn-1.7.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:89877e19a80c7b11a2891a27c21c4894fb18e2c2e077815bcade10d34287b20d", size = 9715424, upload-time = "2025-09-09T08:20:36.776Z" }, + { url = "https://files.pythonhosted.org/packages/f7/32/1f3b22e3207e1d2c883a7e09abb956362e7d1bd2f14458c7de258a26ac15/scikit_learn-1.7.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8da8bf89d4d79aaec192d2bda62f9b56ae4e5b4ef93b6a56b5de4977e375c1f1", size = 9509234, upload-time = "2025-09-09T08:20:38.957Z" }, + { url = "https://files.pythonhosted.org/packages/9f/71/34ddbd21f1da67c7a768146968b4d0220ee6831e4bcbad3e03dd3eae88b6/scikit_learn-1.7.2-cp311-cp311-win_amd64.whl", hash = "sha256:9b7ed8d58725030568523e937c43e56bc01cadb478fc43c042a9aca1dacb3ba1", size = 8894244, upload-time = "2025-09-09T08:20:41.166Z" }, +] + +[[package]] +name = "scipy" +version = "1.17.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/75/b4ce781849931fef6fd529afa6b63711d5a733065722d0c3e2724af9e40a/scipy-1.17.1-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1f95b894f13729334fb990162e911c9e5dc1ab390c58aa6cbecb389c5b5e28ec", size = 31613675, upload-time = "2026-02-23T00:16:00.13Z" }, + { url = "https://files.pythonhosted.org/packages/f7/58/bccc2861b305abdd1b8663d6130c0b3d7cc22e8d86663edbc8401bfd40d4/scipy-1.17.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:e18f12c6b0bc5a592ed23d3f7b891f68fd7f8241d69b7883769eb5d5dfb52696", size = 28162057, upload-time = "2026-02-23T00:16:09.456Z" }, + { url = "https://files.pythonhosted.org/packages/6d/ee/18146b7757ed4976276b9c9819108adbc73c5aad636e5353e20746b73069/scipy-1.17.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:a3472cfbca0a54177d0faa68f697d8ba4c80bbdc19908c3465556d9f7efce9ee", size = 20334032, upload-time = "2026-02-23T00:16:17.358Z" }, + { url = "https://files.pythonhosted.org/packages/ec/e6/cef1cf3557f0c54954198554a10016b6a03b2ec9e22a4e1df734936bd99c/scipy-1.17.1-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:766e0dc5a616d026a3a1cffa379af959671729083882f50307e18175797b3dfd", size = 22709533, upload-time = "2026-02-23T00:16:25.791Z" }, + { url = "https://files.pythonhosted.org/packages/4d/60/8804678875fc59362b0fb759ab3ecce1f09c10a735680318ac30da8cd76b/scipy-1.17.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:744b2bf3640d907b79f3fd7874efe432d1cf171ee721243e350f55234b4cec4c", size = 33062057, upload-time = "2026-02-23T00:16:36.931Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/af933f0f6e0767995b4e2d705a0665e454d1c19402aa7e895de3951ebb04/scipy-1.17.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43af8d1f3bea642559019edfe64e9b11192a8978efbd1539d7bc2aaa23d92de4", size = 35349300, upload-time = "2026-02-23T00:16:49.108Z" }, + { url = "https://files.pythonhosted.org/packages/b4/3d/7ccbbdcbb54c8fdc20d3b6930137c782a163fa626f0aef920349873421ba/scipy-1.17.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:cd96a1898c0a47be4520327e01f874acfd61fb48a9420f8aa9f6483412ffa444", size = 35127333, upload-time = "2026-02-23T00:17:01.293Z" }, + { url = "https://files.pythonhosted.org/packages/e8/19/f926cb11c42b15ba08e3a71e376d816ac08614f769b4f47e06c3580c836a/scipy-1.17.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4eb6c25dd62ee8d5edf68a8e1c171dd71c292fdae95d8aeb3dd7d7de4c364082", size = 37741314, upload-time = "2026-02-23T00:17:12.576Z" }, + { url = "https://files.pythonhosted.org/packages/95/da/0d1df507cf574b3f224ccc3d45244c9a1d732c81dcb26b1e8a766ae271a8/scipy-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:d30e57c72013c2a4fe441c2fcb8e77b14e152ad48b5464858e07e2ad9fbfceff", size = 36607512, upload-time = "2026-02-23T00:17:23.424Z" }, + { url = "https://files.pythonhosted.org/packages/68/7f/bdd79ceaad24b671543ffe0ef61ed8e659440eb683b66f033454dcee90eb/scipy-1.17.1-cp311-cp311-win_arm64.whl", hash = "sha256:9ecb4efb1cd6e8c4afea0daa91a87fbddbce1b99d2895d151596716c0b2e859d", size = 24599248, upload-time = "2026-02-23T00:17:34.561Z" }, +] + +[[package]] +name = "sentencepiece" +version = "0.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/15/15/2e7a025fc62d764b151ae6d0f2a92f8081755ebe8d4a64099accc6f77ba6/sentencepiece-0.2.1.tar.gz", hash = "sha256:8138cec27c2f2282f4a34d9a016e3374cd40e5c6e9cb335063db66a0a3b71fad", size = 3228515, upload-time = "2025-08-12T07:00:51.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d8/15/46afbab00733d81788b64be430ca1b93011bb9388527958e26cc31832de5/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6356d0986b8b8dc351b943150fcd81a1c6e6e4d439772e8584c64230e58ca987", size = 1942560, upload-time = "2025-08-12T06:59:25.82Z" }, + { url = "https://files.pythonhosted.org/packages/fa/79/7c01b8ef98a0567e9d84a4e7a910f8e7074fcbf398a5cd76f93f4b9316f9/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8f8ba89a3acb3dc1ae90f65ec1894b0b9596fdb98ab003ff38e058f898b39bc7", size = 1325385, upload-time = "2025-08-12T06:59:27.722Z" }, + { url = "https://files.pythonhosted.org/packages/bb/88/2b41e07bd24f33dcf2f18ec3b74247aa4af3526bad8907b8727ea3caba03/sentencepiece-0.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:02593eca45440ef39247cee8c47322a34bdcc1d8ae83ad28ba5a899a2cf8d79a", size = 1253319, upload-time = "2025-08-12T06:59:29.306Z" }, + { url = "https://files.pythonhosted.org/packages/a0/54/38a1af0c6210a3c6f95aa46d23d6640636d020fba7135cd0d9a84ada05a7/sentencepiece-0.2.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a0d15781a171d188b661ae4bde1d998c303f6bd8621498c50c671bd45a4798e", size = 1316162, upload-time = "2025-08-12T06:59:30.914Z" }, + { url = "https://files.pythonhosted.org/packages/ef/66/fb191403ade791ad2c3c1e72fe8413e63781b08cfa3aa4c9dfc536d6e795/sentencepiece-0.2.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4f5a3e0d9f445ed9d66c0fec47d4b23d12cfc858b407a03c194c1b26c2ac2a63", size = 1387785, upload-time = "2025-08-12T06:59:32.491Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/3bd9b08e70067b2124518b308db6a84a4f8901cc8a4317e2e4288cdd9b4d/sentencepiece-0.2.1-cp311-cp311-win32.whl", hash = "sha256:6d297a1748d429ba8534eebe5535448d78b8acc32d00a29b49acf28102eeb094", size = 999555, upload-time = "2025-08-12T06:59:34.475Z" }, + { url = "https://files.pythonhosted.org/packages/32/b8/f709977f5fda195ae1ea24f24e7c581163b6f142b1005bc3d0bbfe4d7082/sentencepiece-0.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:82d9ead6591015f009cb1be1cb1c015d5e6f04046dbb8c9588b931e869a29728", size = 1054617, upload-time = "2025-08-12T06:59:36.461Z" }, + { url = "https://files.pythonhosted.org/packages/7a/40/a1fc23be23067da0f703709797b464e8a30a1c78cc8a687120cd58d4d509/sentencepiece-0.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:39f8651bd10974eafb9834ce30d9bcf5b73e1fc798a7f7d2528f9820ca86e119", size = 1033877, upload-time = "2025-08-12T06:59:38.391Z" }, +] + +[[package]] +name = "sentry-sdk" +version = "2.74.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8e/7f/1b16ab4aee53cc5db976bac12e6df5d562aae3880965200cef812e7121d9/sentry_sdk-2.74.0.tar.gz", hash = "sha256:dd91d75aacaef636006b579ac3ddb2fdbc9dce35f00f4b353b6b1b110c6b256a", size = 1081514, upload-time = "2026-11-05T14:50:27.444Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/55/b1/736d4b4b308694b0071844a533522ac06669ad61751687b94edfbf863f17/sentry_sdk-2.74.0-py3-none-any.whl", hash = "sha256:40b205af015649df3ec9986e057ce24ce85956bee3fb75efa72c93aa7036bdff", size = 549800, upload-time = "2026-11-05T14:50:25.767Z" }, +] + +[[package]] +name = "setuptools" +version = "80.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/5d/3bf57dcd21979b887f014ea83c24ae194cfcd12b9e0fda66b957c69d1fca/setuptools-80.9.0.tar.gz", hash = "sha256:f36b47402ecde768dbfafc46e8e4207b4360c654f1f3bb84475f0a28628fb19c", size = 1319958, upload-time = "2025-05-27T00:56:51.443Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922", size = 1201486, upload-time = "2025-05-27T00:56:49.664Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "smmap" +version = "5.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/ea/49c993d6dfdd7338c9b1000a0f36817ed7ec84577ae2e52f890d1a4ff909/smmap-5.0.3.tar.gz", hash = "sha256:4d9debb8b99007ae47165abc08670bd74cb74b5227dda7f643eccc4e9eb5642c", size = 22506, upload-time = "2026-03-09T03:43:26.1Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/d4/59e74daffcb57a07668852eeeb6035af9f32cbfd7a1d2511f17d2fe6a738/smmap-5.0.3-py3-none-any.whl", hash = "sha256:c106e05d5a61449cf6ba9a1e650227ecfb141590d2a98412103ff35d89fc7b2f", size = 24390, upload-time = "2026-03-09T03:43:24.361Z" }, +] + +[[package]] +name = "sympy" +version = "1.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mpmath" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, +] + +[[package]] +name = "threadpoolctl" +version = "3.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/56/97/b4748951a683e369513691c8eea33d100298d556308dcb0ab66b132a67f0/threadpoolctl-3.8.0.tar.gz", hash = "sha256:01080674ad7ac6182429c918a79de92da789bb448acc02fc0b620b1abd6b6137", size = 39424, upload-time = "2026-11-05T11:08:51.112Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/1b/831f2de4840a25db1dd7b1afea433ccafe6bb10aca07e13264f2079462d0/threadpoolctl-3.8.0-py3-none-any.whl", hash = "sha256:f1b49c82704d50f13ffae019c727b0fa4f6791a58f48f06a09c45face1be66da", size = 32091, upload-time = "2026-11-05T11:08:49.773Z" }, +] + +[[package]] +name = "tokenizers" +version = "0.21.4" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "huggingface-hub" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c2/2f/402986d0823f8d7ca139d969af2917fefaa9b947d1fb32f6168c509f2492/tokenizers-0.21.4.tar.gz", hash = "sha256:fa23f85fbc9a02ec5c6978da172cdcbac23498c3ca9f3645c5c68740ac007880", size = 351253, upload-time = "2025-07-28T15:48:54.325Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/98/c6/fdb6f72bf6454f52eb4a2510be7fb0f614e541a2554d6210e370d85efff4/tokenizers-0.21.4-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:2ccc10a7c3bcefe0f242867dc914fc1226ee44321eb618cfe3019b5df3400133", size = 2863987, upload-time = "2025-07-28T15:48:44.877Z" }, + { url = "https://files.pythonhosted.org/packages/8d/a6/28975479e35ddc751dc1ddc97b9b69bf7fcf074db31548aab37f8116674c/tokenizers-0.21.4-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:5e2f601a8e0cd5be5cc7506b20a79112370b9b3e9cb5f13f68ab11acd6ca7d60", size = 2732457, upload-time = "2025-07-28T15:48:43.265Z" }, + { url = "https://files.pythonhosted.org/packages/aa/8f/24f39d7b5c726b7b0be95dca04f344df278a3fe3a4deb15a975d194cbb32/tokenizers-0.21.4-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:39b376f5a1aee67b4d29032ee85511bbd1b99007ec735f7f35c8a2eb104eade5", size = 3012624, upload-time = "2025-07-28T13:22:43.895Z" }, + { url = "https://files.pythonhosted.org/packages/58/47/26358925717687a58cb74d7a508de96649544fad5778f0cd9827398dc499/tokenizers-0.21.4-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:2107ad649e2cda4488d41dfd031469e9da3fcbfd6183e74e4958fa729ffbf9c6", size = 2939681, upload-time = "2025-07-28T13:22:47.499Z" }, + { url = "https://files.pythonhosted.org/packages/99/6f/cc300fea5db2ab5ddc2c8aea5757a27b89c84469899710c3aeddc1d39801/tokenizers-0.21.4-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3c73012da95afafdf235ba80047699df4384fdc481527448a078ffd00e45a7d9", size = 3247445, upload-time = "2025-07-28T15:48:39.711Z" }, + { url = "https://files.pythonhosted.org/packages/be/bf/98cb4b9c3c4afd8be89cfa6423704337dc20b73eb4180397a6e0d456c334/tokenizers-0.21.4-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f23186c40395fc390d27f519679a58023f368a0aad234af145e0f39ad1212732", size = 3428014, upload-time = "2025-07-28T13:22:49.569Z" }, + { url = "https://files.pythonhosted.org/packages/75/c7/96c1cc780e6ca7f01a57c13235dd05b7bc1c0f3588512ebe9d1331b5f5ae/tokenizers-0.21.4-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cc88bb34e23a54cc42713d6d98af5f1bf79c07653d24fe984d2d695ba2c922a2", size = 3193197, upload-time = "2025-07-28T13:22:51.471Z" }, + { url = "https://files.pythonhosted.org/packages/f2/90/273b6c7ec78af547694eddeea9e05de771278bd20476525ab930cecaf7d8/tokenizers-0.21.4-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:51b7eabb104f46c1c50b486520555715457ae833d5aee9ff6ae853d1130506ff", size = 3115426, upload-time = "2025-07-28T15:48:41.439Z" }, + { url = "https://files.pythonhosted.org/packages/91/43/c640d5a07e95f1cf9d2c92501f20a25f179ac53a4f71e1489a3dcfcc67ee/tokenizers-0.21.4-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:714b05b2e1af1288bd1bc56ce496c4cebb64a20d158ee802887757791191e6e2", size = 9089127, upload-time = "2025-07-28T15:48:46.472Z" }, + { url = "https://files.pythonhosted.org/packages/44/a1/dd23edd6271d4dca788e5200a807b49ec3e6987815cd9d0a07ad9c96c7c2/tokenizers-0.21.4-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:1340ff877ceedfa937544b7d79f5b7becf33a4cfb58f89b3b49927004ef66f78", size = 9055243, upload-time = "2025-07-28T15:48:48.539Z" }, + { url = "https://files.pythonhosted.org/packages/21/2b/b410d6e9021c4b7ddb57248304dc817c4d4970b73b6ee343674914701197/tokenizers-0.21.4-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:3c1f4317576e465ac9ef0d165b247825a2a4078bcd01cba6b54b867bdf9fdd8b", size = 9298237, upload-time = "2025-07-28T15:48:50.443Z" }, + { url = "https://files.pythonhosted.org/packages/b7/0a/42348c995c67e2e6e5c89ffb9cfd68507cbaeb84ff39c49ee6e0a6dd0fd2/tokenizers-0.21.4-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:c212aa4e45ec0bb5274b16b6f31dd3f1c41944025c2358faaa5782c754e84c24", size = 9461980, upload-time = "2025-07-28T15:48:52.325Z" }, + { url = "https://files.pythonhosted.org/packages/3d/d3/dacccd834404cd71b5c334882f3ba40331ad2120e69ded32cf5fda9a7436/tokenizers-0.21.4-cp39-abi3-win32.whl", hash = "sha256:6c42a930bc5f4c47f4ea775c91de47d27910881902b0f20e4990ebe045a415d0", size = 2329871, upload-time = "2025-07-28T15:48:56.841Z" }, + { url = "https://files.pythonhosted.org/packages/41/f2/fd673d979185f5dcbac4be7d09461cbb99751554ffb6718d0013af8604cb/tokenizers-0.21.4-cp39-abi3-win_amd64.whl", hash = "sha256:475d807a5c3eb72c59ad9b5fcdb254f6e17f53dfcbb9903233b0dfa9c943b597", size = 2507568, upload-time = "2025-07-28T15:48:55.456Z" }, +] + +[[package]] +name = "tokenizers" +version = "0.22.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "huggingface-hub" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/97/5dbfabf04c7e348e655e907ed27913e03db0923abb5dfdd120d7b25630e1/tokenizers-0.22.2-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:544dd704ae7238755d790de45ba8da072e9af3eea688f698b137915ae959281c", size = 3100275, upload-time = "2026-01-05T10:41:02.158Z" }, + { url = "https://files.pythonhosted.org/packages/2e/47/174dca0502ef88b28f1c9e06b73ce33500eedfac7a7692108aec220464e7/tokenizers-0.22.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:1e418a55456beedca4621dbab65a318981467a2b188e982a23e117f115ce5001", size = 2981472, upload-time = "2026-01-05T10:41:00.276Z" }, + { url = "https://files.pythonhosted.org/packages/d6/84/7990e799f1309a8b87af6b948f31edaa12a3ed22d11b352eaf4f4b2e5753/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2249487018adec45d6e3554c71d46eb39fa8ea67156c640f7513eb26f318cec7", size = 3290736, upload-time = "2026-01-05T10:40:32.165Z" }, + { url = "https://files.pythonhosted.org/packages/78/59/09d0d9ba94dcd5f4f1368d4858d24546b4bdc0231c2354aa31d6199f0399/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:25b85325d0815e86e0bac263506dd114578953b7b53d7de09a6485e4a160a7dd", size = 3168835, upload-time = "2026-01-05T10:40:38.847Z" }, + { url = "https://files.pythonhosted.org/packages/47/50/b3ebb4243e7160bda8d34b731e54dd8ab8b133e50775872e7a434e524c28/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bfb88f22a209ff7b40a576d5324bf8286b519d7358663db21d6246fb17eea2d5", size = 3521673, upload-time = "2026-01-05T10:40:56.614Z" }, + { url = "https://files.pythonhosted.org/packages/e0/fa/89f4cb9e08df770b57adb96f8cbb7e22695a4cb6c2bd5f0c4f0ebcf33b66/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1c774b1276f71e1ef716e5486f21e76333464f47bece56bbd554485982a9e03e", size = 3724818, upload-time = "2026-01-05T10:40:44.507Z" }, + { url = "https://files.pythonhosted.org/packages/64/04/ca2363f0bfbe3b3d36e95bf67e56a4c88c8e3362b658e616d1ac185d47f2/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:df6c4265b289083bf710dff49bc51ef252f9d5be33a45ee2bed151114a56207b", size = 3379195, upload-time = "2026-01-05T10:40:51.139Z" }, + { url = "https://files.pythonhosted.org/packages/2e/76/932be4b50ef6ccedf9d3c6639b056a967a86258c6d9200643f01269211ca/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:369cc9fc8cc10cb24143873a0d95438bb8ee257bb80c71989e3ee290e8d72c67", size = 3274982, upload-time = "2026-01-05T10:40:58.331Z" }, + { url = "https://files.pythonhosted.org/packages/1d/28/5f9f5a4cc211b69e89420980e483831bcc29dade307955cc9dc858a40f01/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:29c30b83d8dcd061078b05ae0cb94d3c710555fbb44861139f9f83dcca3dc3e4", size = 9478245, upload-time = "2026-01-05T10:41:04.053Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fb/66e2da4704d6aadebf8cb39f1d6d1957df667ab24cff2326b77cda0dcb85/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:37ae80a28c1d3265bb1f22464c856bd23c02a05bb211e56d0c5301a435be6c1a", size = 9560069, upload-time = "2026-01-05T10:45:10.673Z" }, + { url = "https://files.pythonhosted.org/packages/16/04/fed398b05caa87ce9b1a1bb5166645e38196081b225059a6edaff6440fac/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:791135ee325f2336f498590eb2f11dc5c295232f288e75c99a36c5dbce63088a", size = 9899263, upload-time = "2026-01-05T10:45:12.559Z" }, + { url = "https://files.pythonhosted.org/packages/05/a1/d62dfe7376beaaf1394917e0f8e93ee5f67fea8fcf4107501db35996586b/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38337540fbbddff8e999d59970f3c6f35a82de10053206a7562f1ea02d046fa5", size = 10033429, upload-time = "2026-01-05T10:45:14.333Z" }, + { url = "https://files.pythonhosted.org/packages/fd/18/a545c4ea42af3df6effd7d13d250ba77a0a86fb20393143bbb9a92e434d4/tokenizers-0.22.2-cp39-abi3-win32.whl", hash = "sha256:a6bf3f88c554a2b653af81f3204491c818ae2ac6fbc09e76ef4773351292bc92", size = 2502363, upload-time = "2026-01-05T10:45:20.593Z" }, + { url = "https://files.pythonhosted.org/packages/65/71/0670843133a43d43070abeb1949abfdef12a86d490bea9cd9e18e37c5ff7/tokenizers-0.22.2-cp39-abi3-win_amd64.whl", hash = "sha256:c9ea31edff2968b44a88f97d784c2f16dc0729b8b143ed004699ebca91f05c48", size = 2747786, upload-time = "2026-01-05T10:45:18.411Z" }, + { url = "https://files.pythonhosted.org/packages/72/f4/0de46cfa12cdcbcd464cc59fde36912af405696f687e53a091fb432f694c/tokenizers-0.22.2-cp39-abi3-win_arm64.whl", hash = "sha256:9ce725d22864a1e965217204946f830c37876eee3b2ba6fc6255e8e903d5fcbc", size = 2612133, upload-time = "2026-01-05T10:45:17.232Z" }, +] + +[[package]] +name = "torch" +version = "2.13.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-bindings", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "nvidia-nvshmem-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "triton", marker = "sys_platform == 'linux' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, + { name = "typing-extensions" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/fe/cba54dc58523434919b66f13a667e36e436deddd77ca519e96553617d4ec/torch-2.13.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:e76f9bcecc52b8ff711239a2f7547d5353df95878ab232f0773c1d95928b92f8", size = 111187938, upload-time = "2026-07-08T16:05:17.065Z" }, + { url = "https://files.pythonhosted.org/packages/c2/59/1e3160e18e12aa3038390efab3ce02b36a9d4d6a527ecdd8520dca2e68d8/torch-2.13.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:092790c696a760c729fd5722835f50b9d81fd7c8f141571f3f3cf4081a8f664c", size = 427199369, upload-time = "2026-07-08T16:04:51.054Z" }, + { url = "https://files.pythonhosted.org/packages/01/79/1f2d34ad7034ee1c7ffc1cf8bf0f8213af2a81df6ecdb3997ecec107c09d/torch-2.13.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:60fcdcb2f3876e21146cb4524ef06397d727ca9ad5f020818547e25075fe3cb7", size = 526574961, upload-time = "2026-07-08T16:04:07.075Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fd/0f2ce40f58aefbdb3392f9acce3c8171940943ae2d661f70558bfa73befb/torch-2.13.0-cp311-cp311-win_amd64.whl", hash = "sha256:a0d8b11f16a48d60e2015d8213aa0390744cbebb98e58b62b3514dddc656e330", size = 122015870, upload-time = "2026-07-08T16:05:27.59Z" }, +] + +[[package]] +name = "tqdm" +version = "4.70.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'group-24-official-agzo-experiment-modern' and extra == 'group-24-official-agzo-experiment-native')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0d/ea/b2a5bd54b28a324dae8211928b2d730b6547500342c7e6c6dea08bd0a485/tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4", size = 171846, upload-time = "2026-09-11T07:25:16.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" }, +] + +[[package]] +name = "transformers" +version = "4.53.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "filelock" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "requests" }, + { name = "safetensors" }, + { name = "tokenizers", version = "0.21.4", source = { registry = "https://pypi.org/simple" } }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4c/67/80f51466ec447028fd84469b208eb742533ce06cc8fad2e3181380199e5c/transformers-4.53.2.tar.gz", hash = "sha256:6c3ed95edfb1cba71c4245758f1b4878c93bf8cde77d076307dacb2cbbd72be2", size = 9201233, upload-time = "2025-07-11T12:39:08.742Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/96/88/beb33a79a382fcd2aed0be5222bdc47f41e4bfe7aaa90ae1374f1d8ea2af/transformers-4.53.2-py3-none-any.whl", hash = "sha256:db8f4819bb34f000029c73c3c557e7d06fc1b8e612ec142eecdae3947a9c78bf", size = 10826609, upload-time = "2025-07-11T12:39:05.461Z" }, +] + +[[package]] +name = "transformers" +version = "4.57.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "filelock" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "requests" }, + { name = "safetensors" }, + { name = "tokenizers", version = "0.22.2", source = { registry = "https://pypi.org/simple" } }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/68/a39307bcc4116a30b2106f2e689130a48de8bd8a1e635b5e1030e46fcd9e/transformers-4.57.1.tar.gz", hash = "sha256:f06c837959196c75039809636cd964b959f6604b75b8eeec6fdfc0440b89cc55", size = 10142511, upload-time = "2025-10-14T15:39:26.18Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/d3/c16c3b3cf7655a67db1144da94b021c200ac1303f82428f2beef6c2e72bb/transformers-4.57.1-py3-none-any.whl", hash = "sha256:b10d05da8fa67dc41644dbbf9bc45a44cb86ae33da6f9295f5fbf5b7890bd267", size = 11990925, upload-time = "2025-10-14T15:39:23.085Z" }, +] + +[[package]] +name = "triton" +version = "3.7.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/f9/19d842d06a08559534fa1eaab6ca551b1bcf40f06620bddec1babaa2772d/triton-3.7.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4a0e1cd4c4a76370ed74a8432a53cea28716827d19e40ffc732233e35ceb3f6", size = 184664887, upload-time = "2026-06-17T20:03:42.913Z" }, + { url = "https://files.pythonhosted.org/packages/cd/5e/fce69606f7f240297f163e25539906732b199530d486ce67ae319877e821/triton-3.7.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6744957e9fd610a29680ec2346057d0c86948ed3812468670719f391e94b44a5", size = 197701306, upload-time = "2026-06-17T19:53:13.673Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ff/50/0195198eb1d75bab716bb0a813abea4cc394bfa17a92a189f021a34859af/typing_inspection-0.4.5.tar.gz", hash = "sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7", size = 81194, upload-time = "2026-11-04T14:13:23.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" }, +] + +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + +[[package]] +name = "wandb" +version = "0.23.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "gitpython" }, + { name = "packaging" }, + { name = "platformdirs" }, + { name = "protobuf" }, + { name = "pydantic" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "sentry-sdk" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0a/cc/770ae3aa7ae44f6792f7ecb81c14c0e38b672deb35235719bb1006519487/wandb-0.23.1.tar.gz", hash = "sha256:f6fb1e3717949b29675a69359de0eeb01e67d3360d581947d5b3f98c273567d6", size = 44298053, upload-time = "2025-12-03T02:25:10.79Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/0b/c3d7053dfd93fd259a63c7818d9c4ac2ba0642ff8dc8db98662ea0cf9cc0/wandb-0.23.1-py3-none-macosx_12_0_arm64.whl", hash = "sha256:358e15471d19b7d73fc464e37371c19d44d39e433252ac24df107aff993a286b", size = 21527293, upload-time = "2025-12-03T02:24:48.011Z" }, + { url = "https://files.pythonhosted.org/packages/ee/9f/059420fa0cb6c511dc5c5a50184122b6aca7b178cb2aa210139e354020da/wandb-0.23.1-py3-none-macosx_12_0_x86_64.whl", hash = "sha256:110304407f4b38f163bdd50ed5c5225365e4df3092f13089c30171a75257b575", size = 22745926, upload-time = "2025-12-03T02:24:50.519Z" }, + { url = "https://files.pythonhosted.org/packages/96/b6/fd465827c14c64d056d30b4c9fcf4dac889a6969dba64489a88fc4ffa333/wandb-0.23.1-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:6cc984cf85feb2f8ee0451d76bc9fb7f39da94956bb8183e30d26284cf203b65", size = 21212973, upload-time = "2025-12-03T02:24:52.828Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/9a8bb9a39cc1f09c3060456cc79565110226dc4099a719af5c63432da21d/wandb-0.23.1-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:67431cd3168d79fdb803e503bd669c577872ffd5dadfa86de733b3274b93088e", size = 22887885, upload-time = "2025-12-03T02:24:55.281Z" }, + { url = "https://files.pythonhosted.org/packages/6d/4d/8d9e75add529142e037b05819cb3ab1005679272950128d69d218b7e5b2e/wandb-0.23.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:07be70c0baa97ea25fadc4a9d0097f7371eef6dcacc5ceb525c82491a31e9244", size = 21250967, upload-time = "2025-12-03T02:24:57.603Z" }, + { url = "https://files.pythonhosted.org/packages/97/72/0b35cddc4e4168f03c759b96d9f671ad18aec8bdfdd84adfea7ecb3f5701/wandb-0.23.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:216c95b08e0a2ec6a6008373b056d597573d565e30b43a7a93c35a171485ee26", size = 22988382, upload-time = "2025-12-03T02:25:00.518Z" }, + { url = "https://files.pythonhosted.org/packages/c0/6d/e78093d49d68afb26f5261a70fc7877c34c114af5c2ee0ab3b1af85f5e76/wandb-0.23.1-py3-none-win32.whl", hash = "sha256:fb5cf0f85692f758a5c36ab65fea96a1284126de64e836610f92ddbb26df5ded", size = 22150756, upload-time = "2025-12-03T02:25:02.734Z" }, + { url = "https://files.pythonhosted.org/packages/05/27/4f13454b44c9eceaac3d6e4e4efa2230b6712d613ff9bf7df010eef4fd18/wandb-0.23.1-py3-none-win_amd64.whl", hash = "sha256:21c8c56e436eb707b7d54f705652e030d48e5cfcba24cf953823eb652e30e714", size = 22150760, upload-time = "2025-12-03T02:25:05.106Z" }, + { url = "https://files.pythonhosted.org/packages/30/20/6c091d451e2a07689bfbfaeb7592d488011420e721de170884fedd68c644/wandb-0.23.1-py3-none-win_arm64.whl", hash = "sha256:8aee7f3bb573f2c0acf860f497ca9c684f9b35f2ca51011ba65af3d4592b77c1", size = 20137463, upload-time = "2025-12-03T02:25:08.317Z" }, +] + +[[package]] +name = "xxhash" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c9/b5/3d11d3830ace56d67ea83136c24385c3b07da5a9bc62b73b0b94ac096da3/xxhash-4.1.0.tar.gz", hash = "sha256:c9b288e4c1f5dae54417bc8a05e6f6daf505783d916b4783f4dd2f2e7d5db486", size = 114122, upload-time = "2026-11-09T13:47:33.276Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/cb/da501f3abc32f8c3a6f0fb24f1988ec6b862897034a6f44bff92e06b6f29/xxhash-4.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cf3e28ee18b17d253d85c0a0b3608b9b54f765df4af207722c1ce851f386a26d", size = 51515, upload-time = "2026-11-09T13:46:45.912Z" }, + { url = "https://files.pythonhosted.org/packages/5c/1d/112856c31d49a814854f19b3ecf8d81196a5b2d0c8cccbbe5a0cfe571e86/xxhash-4.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:796b8e5212ba90ebc8afac5ae3615502acd0d65363730cccd1d629b0fe7e87f6", size = 36825, upload-time = "2026-11-09T13:46:48.399Z" }, + { url = "https://files.pythonhosted.org/packages/40/37/fb258a692f0ecd93ff3af8f77a0122db1e33853f6c6c433cb841f46da13f/xxhash-4.1.0-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:822f6aa36f336f65188ae987b9627e843b6963f749d8a2a187f5b6fd72715088", size = 448119, upload-time = "2026-11-09T13:46:48.427Z" }, + { url = "https://files.pythonhosted.org/packages/2f/be/4e9efad09e3152cd437a6ad46148a9fe992f9bdfc1117808e71bc02178c4/xxhash-4.1.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f948b71013e0a0922176563dd4538967e2d7717b845bd61e0407f2e410962050", size = 274457, upload-time = "2026-11-09T13:46:46.078Z" }, + { url = "https://files.pythonhosted.org/packages/3a/11/177b6b4a781ae0a38e2d335b2a6bfe4e70c3e8edace541b1615da408d4ef/xxhash-4.1.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3fbf446e75b80f2a605b4b1637cb5bfdad5c317bc54ecd91ac7cb9e28314fe4b", size = 296295, upload-time = "2026-11-09T13:46:48.728Z" }, + { url = "https://files.pythonhosted.org/packages/30/d7/d59d72875eb268e83743ce507de3ce983a611e18c79d4d4169500932a747/xxhash-4.1.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:586ce49f8d73dc214f9da8e87824f332f2b4ddb7d15534736a2f906373b2030d", size = 273599, upload-time = "2026-11-09T13:46:49.98Z" }, + { url = "https://files.pythonhosted.org/packages/10/8a/3c85277e544cae7f6fa1dad71e23485b21d5695d3ac69a10ea46d3257896/xxhash-4.1.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b6b09351f73f6d0a3df59b02b9d2154a66fcc716fae8f0b8b2bdd63c42a1d2f6", size = 506958, upload-time = "2026-11-09T13:46:47.172Z" }, + { url = "https://files.pythonhosted.org/packages/b6/4f/5b195a79fafb6e9ab8e95229cc5346572a6cc40d6d6ed9227183a25315ea/xxhash-4.1.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e713f5db9e1a8aafac59a45cc1ffce11ca507730f5dc12e212ea7b73d9debde", size = 471448, upload-time = "2026-11-09T13:46:47.314Z" }, + { url = "https://files.pythonhosted.org/packages/d8/6d/c34662fae63220b90d6803dab8fdc9240cf6cef06fbdea73fef0750ff438/xxhash-4.1.0-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:eadb2724470fd9507cb8f864c969d761dac7d549223ff15ff998c1c3c8e134d5", size = 337233, upload-time = "2026-11-09T13:46:49.72Z" }, + { url = "https://files.pythonhosted.org/packages/86/f7/7def1a3b835ef30b8f1a192405dd99db448922aeda8f45eb0359f00613c0/xxhash-4.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0119cf9ae630c5365596dd9dccf29932f364e8ef0f9162e1d7ef9df3e15ccb8e", size = 270274, upload-time = "2026-11-09T13:46:50.189Z" }, + { url = "https://files.pythonhosted.org/packages/bf/fb/677fef1a69b67c62eb12f71b7f49f801db1191df2f336d2930608f61c9f4/xxhash-4.1.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:3f580ff0d8dec8b495c6c6b281a89be3913158b01937281006993168b4375f84", size = 297452, upload-time = "2026-11-09T13:46:47.438Z" }, + { url = "https://files.pythonhosted.org/packages/95/15/5017ecacab16636c244e2cbd014cc56e17528caa736abcea4e151102e514/xxhash-4.1.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6179c5e008d2f1ca3a2e9c7935c021f84c5dc7516dfe5c9ee3edc0e9f26d20f0", size = 442167, upload-time = "2026-11-09T13:46:50.278Z" }, + { url = "https://files.pythonhosted.org/packages/45/0d/29c13f74ac43011aaafff9d9b23effefdf9243fcce764fed17087b1bd12c/xxhash-4.1.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:bdeaa333f8fbc237c5e62e0fb70e694dbfde62d15e242be23ba491ecd706e520", size = 271153, upload-time = "2026-11-09T13:46:51.737Z" }, + { url = "https://files.pythonhosted.org/packages/ef/89/d01eedb87d3ef1f7ec81080a160acd7ba42f29a43706b36d7fb4a8192706/xxhash-4.1.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:7c6bcd4eeeb5411a176b1a63dc505de99cd6182e88b02722d4407f96cf082e62", size = 327241, upload-time = "2026-11-09T13:46:48.482Z" }, + { url = "https://files.pythonhosted.org/packages/69/6a/82eb13aff0e06861cf2ff7a5b4e91092a3e7f7da5442c8be19e4c876d1a4/xxhash-4.1.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9f200a2bc05bade88e7c50c28d2a6637468ff0bacbcf1720928ae55b905bb1af", size = 474740, upload-time = "2026-11-09T13:46:48.76Z" }, + { url = "https://files.pythonhosted.org/packages/64/eb/0859f45d7b690f44704f3d8dc9a6a00eea931bcb0f3c5f5da7799a8740bb/xxhash-4.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e8b54cf9df8802572be9b8af0e3c1bc9eae80f653cd16f97d340a0098c48bb9c", size = 453590, upload-time = "2026-11-09T13:46:51.495Z" }, + { url = "https://files.pythonhosted.org/packages/18/99/e74773a5bc7b8decc874f0c74fb13e2058259101c6f54f87ecf07709e030/xxhash-4.1.0-cp311-cp311-win32.whl", hash = "sha256:b0042c684cf5739352d47afa77d387300805773a756f3677c1113481015934d6", size = 45112, upload-time = "2026-11-09T13:46:51.691Z" }, + { url = "https://files.pythonhosted.org/packages/5d/5f/299d6c8733add97f1b3e25f102dc473cd25b7ca147e6a828ec560c9740f2/xxhash-4.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:306a5538aa1152a3c411ebcce31a824721159495f391290ddcfa5b3f07c051a5", size = 48163, upload-time = "2026-11-09T13:46:48.804Z" }, + { url = "https://files.pythonhosted.org/packages/49/ee/e6d087e0fb37800c84ad842a4f6989ae3bc24964b63440fef1c89ec7f0e9/xxhash-4.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:bf3ebcbed4efff1ec177385e4b906c8ba75881d975ea59f49aa6edc2d37752aa", size = 33410, upload-time = "2026-11-09T13:46:51.735Z" }, + { url = "https://files.pythonhosted.org/packages/c0/41/89fa8c4f2d1190f8a9efca46f5779bdb4481356aec35119529e1ba91d35c/xxhash-4.1.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:d7a55bb01f866f948a4439e325e3e92645d97ca22c43777d2a71e7e51b63a986", size = 47341, upload-time = "2026-11-09T13:49:04.925Z" }, + { url = "https://files.pythonhosted.org/packages/93/5c/aa12a2f255cceb0941fa706d802bd502f64d42a76f17ea68ad62d860499b/xxhash-4.1.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:50e76857c8c47d8feb48ff1de711eaccfc5d28d97a5b1f7bd449b20796ecbf2b", size = 33938, upload-time = "2026-11-09T13:47:34.712Z" }, + { url = "https://files.pythonhosted.org/packages/c8/d1/d009e49747f1344c5c6fce52d67dfd53dfd0a0e75c4525abfc1dac44380b/xxhash-4.1.0-pp311-pypy311_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:49471b564ebae5d664daae4ecb2a02b03dc2e86f2065ed49f85e9367e8ca1428", size = 61619, upload-time = "2026-11-09T13:49:08.256Z" }, + { url = "https://files.pythonhosted.org/packages/9f/b7/473abf21c56969387bf90ac1d36bfbef620776bbe43a66ab4b1dc9fe0f1a/xxhash-4.1.0-pp311-pypy311_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2967f41d315ef1f9530af306ab79af7e5e6f3a4fdb3f02228bfc39414c11c273", size = 42795, upload-time = "2026-11-09T13:47:27.548Z" }, + { url = "https://files.pythonhosted.org/packages/e8/91/7981fb798edebeb130f95bd062f71f2512178af37925da889638ad63eb64/xxhash-4.1.0-pp311-pypy311_pp80-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0dcfb880344d6f1ed6feb867a898031b942f9c158f777c9ad678c078d7614b99", size = 47906, upload-time = "2026-11-09T13:47:30.555Z" }, + { url = "https://files.pythonhosted.org/packages/30/01/3876a8938f4dab623b501c77e874d7b3ac211fb1871e3bb236815dc66499/xxhash-4.1.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:100efa355bcc08b60a719926f9ce3c9ebf21cfa61db0a3bf43ebf64686d66ea3", size = 95476, upload-time = "2026-11-09T13:47:35.059Z" }, +] + +[[package]] +name = "yarl" +version = "1.25.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/75/16/e8be8e2fb175bbf41a0680381a319f1199fae256588241a2ac8677eafb49/yarl-1.25.1.tar.gz", hash = "sha256:03dd38de09bc213e9a8b29761eec33ee1d5318dac0e49d8af36e4d27830e23a7", size = 246245, upload-time = "2026-09-15T19:35:02.264Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/b3/2cea721d495ca57f8f414aa4867ee263f486b274e07463158cf52f02ba7f/yarl-1.25.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9d693bf4bf534e9ba3ae2780cfd577f5135629f7b5ac653490859d0b77864865", size = 143794, upload-time = "2026-09-15T19:30:26.946Z" }, + { url = "https://files.pythonhosted.org/packages/55/e6/cd145cff8e5cf60b8b3c41fbecfa2a45028a8dec3fbc52bec03595ff3d3b/yarl-1.25.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ab2054c5531af2a9ba7b69b8ec91e4f884420e83a8c5e579b013084cb57e5e5d", size = 103993, upload-time = "2026-09-15T19:30:28.661Z" }, + { url = "https://files.pythonhosted.org/packages/ce/7c/fbb40fe2d53747c40aa36a9e2bd2178a202f942bda0b670f3306d4aefbce/yarl-1.25.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:564fdc7085d2245ab84f88882fdb1d6ac0723124bff6ded35bfb1c00f812630d", size = 104010, upload-time = "2026-09-15T19:30:31.069Z" }, + { url = "https://files.pythonhosted.org/packages/f0/0b/5a516f70641092283f57cf3670bdb75e7327bcc0dcb5038697e4dfbfd569/yarl-1.25.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:acae6b45d1ace09b6ba3876da43b88366ef368f73b988c7f57e14231753d4420", size = 116444, upload-time = "2026-09-15T19:30:32.894Z" }, + { url = "https://files.pythonhosted.org/packages/b6/8a/d1a627f827b0a404ae0f5647cab0534959081cde13b0756a783469fb3b5e/yarl-1.25.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1fb2a01ba8cd9c5d2c5dc1ec35e0fc951d04b4f037541d4ac090c993ce58b3d7", size = 107565, upload-time = "2026-09-15T19:30:35.188Z" }, + { url = "https://files.pythonhosted.org/packages/aa/cf/c8e0aaec886840a6c4480fe44eaec7cd4319f79a563b79321473be79c56f/yarl-1.25.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e92b6bcc741b86d67606c40d3cb9c7cc8e6c737f81e31f4a94efc204456c92e3", size = 125006, upload-time = "2026-09-15T19:30:37.1Z" }, + { url = "https://files.pythonhosted.org/packages/50/26/0cce366d54a93cdc8342965dc7663385e4db161625cc1e8b18e786753d24/yarl-1.25.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:72c34ac7ad4314c19362d5ce27626dcc8429bd30bbf8c179f4234078851f9492", size = 128717, upload-time = "2026-09-15T19:30:38.904Z" }, + { url = "https://files.pythonhosted.org/packages/95/0c/a71501bbc1a674ff72c4d6c2b75f4d9a5af819f5244c3a7558080a8802c5/yarl-1.25.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d5add7b4ca7afeea91d52e4d4e4db3b1fe9885b71f07054560d8c4296b7441a2", size = 117728, upload-time = "2026-09-15T19:30:40.809Z" }, + { url = "https://files.pythonhosted.org/packages/e7/6f/c3267ca01defeed9ed9c4ff9b17bd54915432c405945233265b707475d1c/yarl-1.25.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:def538065f9e4d4cf1ae164bd59aba00dfa84f03923e0de4c3788f252d6bcd17", size = 116224, upload-time = "2026-09-15T19:30:42.818Z" }, + { url = "https://files.pythonhosted.org/packages/8f/69/fad57ee52d648431718ee0f1f68966a99c1352c3924688ffbdcc9d3fe51a/yarl-1.25.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0a191bfdb30a79b98e5d175d75285f9fcb78bf0e46ba5efda042e1c72071a0de", size = 116299, upload-time = "2026-09-15T19:30:44.966Z" }, + { url = "https://files.pythonhosted.org/packages/2a/d4/6a8c1e29f33338687ca278cba0a8fbf6525a322c2c02a9a500ccbe041152/yarl-1.25.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:71f42c5b9a948c113bbdebfa544598321431d064ff959d32e99b1feb61d68345", size = 108625, upload-time = "2026-09-15T19:30:46.874Z" }, + { url = "https://files.pythonhosted.org/packages/e8/d2/3a35ae791c9cb6522c106923ff25c3230d999091e5e65511bca23bbd9914/yarl-1.25.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:72849d892954be4d09e569b8b831ac39ce58417fedc767d4308a0fe542018a40", size = 124515, upload-time = "2026-09-15T19:30:49.082Z" }, + { url = "https://files.pythonhosted.org/packages/be/fd/2b022109a6b4af0f7dc371cf7500af380b0d4f034010243e1b0ce218dc93/yarl-1.25.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:efb01a106f971cb3752856bca2318bbdf7f01bd8823779c461586cbe5ffd5258", size = 115711, upload-time = "2026-09-15T19:30:51.208Z" }, + { url = "https://files.pythonhosted.org/packages/18/59/f7586271136c3ddb0126bbfe661844699369b76b555fe38c4efe86870b2e/yarl-1.25.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:a1daf47cd95a7c3a63456336bc5aaa8c86dd3a47d07ed3d0e76132ae4666a5a1", size = 122751, upload-time = "2026-09-15T19:30:53.535Z" }, + { url = "https://files.pythonhosted.org/packages/a0/0b/07f7a2d881f7e16c385b47fc1753382600847cad305dcc7fa0c25828acf8/yarl-1.25.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9489e6abf47ba37f332075a91444c7cfedb03e6ce99fbb2f116bfe1ce810da3b", size = 117983, upload-time = "2026-09-15T19:30:55.277Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9d/8cdceec66a9b940700cb45931741403f045b162afd79bcb93c41cadd0972/yarl-1.25.1-cp311-cp311-win_amd64.whl", hash = "sha256:d7306dee25b8a0e737363f347362b875094b4dc4e367311470656ae420fdbf8e", size = 102894, upload-time = "2026-09-15T19:30:57.606Z" }, + { url = "https://files.pythonhosted.org/packages/17/f1/7ec357db1d3ad2863542d71e8fe64a126bbec17b134cd7d30951196809a5/yarl-1.25.1-cp311-cp311-win_arm64.whl", hash = "sha256:abb1384477f5901d436b5d2e5465954de46ea6098f59163d243660b5c4461d35", size = 98609, upload-time = "2026-09-15T19:30:59.705Z" }, + { url = "https://files.pythonhosted.org/packages/54/22/318c7980066769c6bcd9221ed2248294f5698811da099013098c670565ed/yarl-1.25.1-py3-none-any.whl", hash = "sha256:681c758b0490f9e96b78e5fa8e8dc6e648e9185bb6eaebe73183c33ea0c445f3", size = 63617, upload-time = "2026-09-15T19:34:59.616Z" }, +] diff --git a/baselines/agzo/zo-bench/fusion_result.json b/baselines/agzo/zo-bench/fusion_result.json new file mode 100644 index 0000000..ec747fa --- /dev/null +++ b/baselines/agzo/zo-bench/fusion_result.json @@ -0,0 +1 @@ +null \ No newline at end of file diff --git a/baselines/agzo/zo-bench/gradient_pruning/__init__.py b/baselines/agzo/zo-bench/gradient_pruning/__init__.py new file mode 100644 index 0000000..72386f7 --- /dev/null +++ b/baselines/agzo/zo-bench/gradient_pruning/__init__.py @@ -0,0 +1,3 @@ +# -*- coding: utf-8 -*- +# @Author: pingzhili +# @Time: 2024/1/17 diff --git a/baselines/agzo/zo-bench/gradient_pruning/pruning_utils.py b/baselines/agzo/zo-bench/gradient_pruning/pruning_utils.py new file mode 100644 index 0000000..00f8fc2 --- /dev/null +++ b/baselines/agzo/zo-bench/gradient_pruning/pruning_utils.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- +# @Author: pingzhili +# @Time: 2024/1/18 +from typing import Dict + +import torch +from transformers import PreTrainedModel + + +@torch.no_grad() +def random_mask_like(tensor, nonzero_ratio, generator=None): + """ + Return a random mask with the same shape as the input tensor, where the fraction of True is equal to the sparsity. + + Examples + -------- + >>> random_mask_like(torch.randn(10, 10), 0.1).count_nonzero() + tensor(10) + """ + mask = torch.zeros_like(tensor) + mask.view(-1)[torch.randperm(mask.numel(), generator=generator)[:int(nonzero_ratio * mask.numel())]] = 1 + return mask.bool() + + +@torch.no_grad() +def fast_random_mask_like(tensor, nonzero_ratio, generator=None): + """ + A much faster version of random_zero_mask_like, but the sparsity is not guaranteed. + + Examples + -------- + >>> fast_random_mask_like(torch.randn(10, 10), 0.1).count_nonzero() < 20 + tensor(True) + """ + mask = torch.empty_like(tensor).normal_(generator=generator) < nonzero_ratio + return mask.bool() + + +@torch.no_grad() +def estimate_pretrained_model_magnitude_pruning_threshold( + model: PreTrainedModel, + global_sparsity: float, +) -> float: + """ + Compute the magnitude threshold for pruning based on the global sparsity requirement. + """ + all_weights = [] + for param in model.parameters(): + all_weights.append( + param.view(-1).abs().clone().detach().cpu() + ) + all_weights = torch.cat(all_weights) + # subsample 102400 elements to estimate the threshold + sample_size = int(min(1e7, all_weights.numel())) + print(f"[Sparse gradient] Subsampling {sample_size} elements to estimate the threshold.") + sub_weights = all_weights[torch.randperm(all_weights.numel())[:sample_size]] + return torch.quantile(sub_weights.float(), global_sparsity).item() + + +@torch.no_grad() +def compute_named_parameters_to_sparsity( + model: PreTrainedModel, + threshold: float, +) -> Dict[str, float]: + """ + Compute the sparsity of each named parameter in the model. + """ + named_parameters_to_sparsity = {} + for name, param in model.named_parameters(): + named_parameters_to_sparsity[name] = param.abs().le(threshold).float().mean().item() + return named_parameters_to_sparsity diff --git a/baselines/agzo/zo-bench/gradient_pruning/wanda.py b/baselines/agzo/zo-bench/gradient_pruning/wanda.py new file mode 100644 index 0000000..43360b9 --- /dev/null +++ b/baselines/agzo/zo-bench/gradient_pruning/wanda.py @@ -0,0 +1,60 @@ +# -*- coding: utf-8 -*- +# @Author: pingzhili +# @Time: 2024/1/17 +"""WANDA: Pruning by Weights and activations (https://arxiv.org/pdf/2306.11695.pdf)""" + +from dataclasses import dataclass +from typing import Optional + +import torch +from transformers import PreTrainedModel + + +@dataclass +class WandaPruningConfig: + sparsity: Optional[float] = 0.5 + comparison_group: Optional[str] = "model" # model, layer, linear + scaler_device: Optional[str] = "cuda" + + +class WandaPruner: + def __init__( + self, + config: WandaPruningConfig, + model: PreTrainedModel, + ): + self.model = model + self.config = config + + self.linear_module_scaler_dict = {} + self.linear_module_num_samples_dict = {} + self.linear_module_hook_dict = {} + self._init_hooks_and_scaler() + + def _init_hooks_and_scaler(self): + device = self.config.scaler_device + + def _get_forward_hook(name, input_dim): + + def _forward_hook(module, input, output): + input = input.reshape(-1, input_dim) + num_prev_samples = self.linear_module_num_samples_dict[name] + num_curr_samples = input.shape[0] + self.linear_module_scaler_dict[name] *= (num_prev_samples / (num_prev_samples + num_curr_samples)) + self.linear_module_num_samples_dict[name] += num_curr_samples + self.linear_module_scaler_dict[name] += torch.norm( + input, dim=0, p=2 + ) / (num_prev_samples + num_curr_samples) + + return _forward_hook + + for name, module in self.model.named_modules(): + if isinstance(module, torch.nn.Linear): + self.linear_module_num_samples_dict[name] = 0 + self.linear_module_scaler_dict[name] = torch.ones(module.weight.shape[1], device=device) + _hook = module.register_forward_hook(_get_forward_hook(name, module.weight.shape[1])) + self.linear_module_hook_dict[name] = _hook + + def remove_hooks(self): + for name, hook in self.linear_module_hook_dict.items(): + hook.remove() diff --git a/baselines/agzo/zo-bench/lora.py b/baselines/agzo/zo-bench/lora.py new file mode 100644 index 0000000..bef93d8 --- /dev/null +++ b/baselines/agzo/zo-bench/lora.py @@ -0,0 +1,204 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import torch +from torch import nn +from torch.nn import functional as F +import math + + +def find_module(root_module: nn.Module, key: str): + """ + Find a module with a specific name in a Transformer model + From OpenDelta https://github.com/thunlp/OpenDelta + """ + sub_keys = key.split(".") + parent_module = root_module + for sub_key in sub_keys[:-1]: + parent_module = getattr(parent_module, sub_key) + module = getattr(parent_module, sub_keys[-1]) + return parent_module, sub_keys[-1], module + + +class LoRALinear(nn.Linear): + """ + LoRA implemented in a dense layer + From https://github.com/microsoft/LoRA/blob/main/loralib/layers.py + """ + + def __init__( + self, + in_features: int, + out_features: int, + r: int = 0, + lora_alpha: int = 1, + lora_dropout: float = 0., + fan_in_fan_out: bool = False, + # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + merge_weights: bool = False, + # Not sure if this will affect saving/loading models so just set it to be False + **kwargs + ): + nn.Linear.__init__(self, in_features, out_features, **kwargs) + + self.r = r + self.lora_alpha = lora_alpha + # Optional dropout + if lora_dropout > 0.: + self.lora_dropout = nn.Dropout(p=lora_dropout) + else: + self.lora_dropout = lambda x: x + # Mark the weight as unmerged + self.merged = False + self.merge_weights = merge_weights + self.fan_in_fan_out = fan_in_fan_out + # Actual trainable parameters + if r > 0: + self.lora_A = nn.Parameter(self.weight.new_zeros((r, in_features))) + self.lora_B = nn.Parameter(self.weight.new_zeros((out_features, r))) + self.scaling = self.lora_alpha / self.r + # Freezing the pre-trained weight matrix + self.weight.requires_grad = False + self.reset_parameters() + if fan_in_fan_out: + self.weight.data = self.weight.data.transpose(0, 1) + + def reset_parameters(self): + nn.Linear.reset_parameters(self) + if hasattr(self, 'lora_A'): + # initialize A the same way as the default for nn.Linear and B to zero + nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5)) + nn.init.zeros_(self.lora_B) + + def train(self, mode: bool = True): + def T(w): + return w.transpose(0, 1) if self.fan_in_fan_out else w + + nn.Linear.train(self, mode) + if mode: + if self.merge_weights and self.merged: + # Make sure that the weights are not merged + if self.r > 0: + self.weight.data -= T(self.lora_B @ self.lora_A) * self.scaling + self.merged = False + else: + if self.merge_weights and not self.merged: + # Merge the weights and mark it + if self.r > 0: + self.weight.data += T(self.lora_B @ self.lora_A) * self.scaling + self.merged = True + + def forward(self, x: torch.Tensor): + def T(w): + return w.transpose(0, 1) if self.fan_in_fan_out else w + + if self.r > 0 and not self.merged: + result = F.linear(x, T(self.weight), bias=self.bias) + if self.r > 0: + result += (self.lora_dropout(x) @ self.lora_A.transpose(0, 1) @ self.lora_B.transpose(0, + 1)) * self.scaling + return result + else: + return F.linear(x, T(self.weight), bias=self.bias) + + +class LoRA: + + def __init__(self, model, r, alpha, float16): + """ + Input: + r, alpha: LoRA hyperparameters + float16: Whether the model parameters are float16 or not + """ + + self.model = model + self.hidden_dim = model.config.hidden_size + self.float16 = float16 + + if model.config.model_type == "opt": + attention_name = "attn" + elif model.config.model_type == "roberta": + attention_name = "attention" + elif model.config.model_type in ["llama", "mistral"]: + attention_name = "self_attn" + else: + raise NotImplementedError + + # Insert LoRA + for key, _ in model.named_modules(): + if key[-len(attention_name):] == attention_name: + logger.info(f"Inject lora to: {key}") + _, _, attn = find_module(model, key) + + if model.config.model_type == "opt": + original_q_weight = attn.q_proj.weight.data + original_q_bias = attn.q_proj.bias.data + original_v_weight = attn.v_proj.weight.data + original_v_bias = attn.v_proj.bias.data + attn.q_proj = LoRALinear(model.config.hidden_size, model.config.hidden_size, r=r, lora_alpha=alpha, + bias=model.config.enable_bias).to(original_q_weight.device) + attn.v_proj = LoRALinear(model.config.hidden_size, model.config.hidden_size, r=r, lora_alpha=alpha, + bias=model.config.enable_bias).to(original_v_weight.device) + if float16: + attn.q_proj.half() + attn.v_proj.half() + attn.q_proj.weight.data = original_q_weight + attn.q_proj.bias.data = original_q_bias + attn.v_proj.weight.data = original_v_weight + attn.v_proj.bias.data = original_v_bias + elif model.config.model_type == "llama": + # in early version of transformers, llama attention bias is hard coded to False + attention_bias = False if not hasattr(model.config, "attention_bias") else model.config.attention_bias + original_q_weight = attn.q_proj.weight.data + original_v_weight = attn.v_proj.weight.data + original_q_bias = attn.q_proj.bias.data if attention_bias else None + original_v_bias = attn.v_proj.bias.data if attention_bias else None + attn.q_proj = LoRALinear( + model.config.hidden_size, + model.config.hidden_size, + r=r, lora_alpha=alpha, bias=attention_bias + ).to(original_q_weight.device) + attn.v_proj = LoRALinear( + model.config.hidden_size, + model.config.hidden_size, + r=r, lora_alpha=alpha, bias=attention_bias + ).to(original_v_weight.device) + if float16: + attn.q_proj.half() + attn.v_proj.half() + attn.q_proj.weight.data = original_q_weight + attn.v_proj.weight.data = original_v_weight + if attention_bias: + attn.q_proj.bias.data = original_q_bias + attn.v_proj.bias.data = original_v_bias + elif model.config.model_type == "mistral": + # in early version of transformers, llama attention bias is hard coded to False + config = model.config + original_q_weight = attn.q_proj.weight.data + original_v_weight = attn.v_proj.weight.data + head_dim = config.hidden_size // config.num_attention_heads + attn.q_proj = LoRALinear( + config.hidden_size, + config.hidden_size, + r=r, lora_alpha=alpha + ).to(original_q_weight.device) + attn.v_proj = LoRALinear( + config.hidden_size, + config.num_key_value_heads * head_dim, + r=r, lora_alpha=alpha + ).to(original_v_weight.device) + if float16: + attn.q_proj.half() + attn.v_proj.half() + attn.q_proj.weight.data = original_q_weight + attn.v_proj.weight.data = original_v_weight + else: + raise NotImplementedError + + # Freeze non-LoRA parameters + for n, p in model.named_parameters(): + if "lora" not in n: + p.requires_grad = False diff --git a/baselines/agzo/zo-bench/metrics.py b/baselines/agzo/zo-bench/metrics.py new file mode 100644 index 0000000..0e0a282 --- /dev/null +++ b/baselines/agzo/zo-bench/metrics.py @@ -0,0 +1,78 @@ +import numpy as np +import collections +import re +import string +from collections import Counter + +def normalize_answer(s): + """Lower text and remove punctuation, articles and extra whitespace.""" + + def remove_articles(text): + return re.sub(r'\b(a|an|the)\b', ' ', text) + + def white_space_fix(text): + return ' '.join(text.split()) + + def remove_punc(text): + exclude = set(string.punctuation) + return ''.join(ch for ch in text if ch not in exclude) + + def lower(text): + return text.lower() + + return white_space_fix(remove_articles(remove_punc(lower(s)))) + + +def calculate_metric(predictions, metric_name): + if metric_name == "accuracy": + if isinstance(predictions[0].correct_candidate, list): + return np.mean([pred.predicted_candidate in pred.correct_candidate for pred in predictions]) + else: + return np.mean([pred.correct_candidate == pred.predicted_candidate for pred in predictions]) + elif metric_name == "em": + # For question answering + return np.mean([any([normalize_answer(ans) == normalize_answer(pred.predicted_candidate) for ans in pred.correct_candidate]) for pred in predictions]) + elif metric_name == "f1": + # For question answering + f1 = [] + for pred in predictions: + all_f1s = [] + if pred.correct_candidate[0] == "CANNOTANSWER" or pred.correct_candidate[0] == "no answer": + f1.append(int(normalize_answer(pred.correct_candidate[0]) == normalize_answer(pred.predicted_candidate))) + else: + for ans in pred.correct_candidate: + prediction_tokens = normalize_answer(pred.predicted_candidate).split() + ground_truth_tokens = normalize_answer(ans).split() + common = Counter(prediction_tokens) & Counter(ground_truth_tokens) + num_same = sum(common.values()) + if num_same == 0: + all_f1s.append(0) + else: + precision = 1.0 * num_same / len(prediction_tokens) + recall = 1.0 * num_same / len(ground_truth_tokens) + all_f1s.append((2 * precision * recall) / (precision + recall)) + f1.append(max(all_f1s)) + + return np.mean(f1) + + +def f1(pred, gold): + """ + This separate F1 function is used as non-differentiable metric for SQuAD + """ + if gold[0] == "CANNOTANSWER" or gold[0] == "no answer": + return int(normalize_answer(gold[0]) == normalize_answer(pred)) + else: + all_f1s = [] + for ans in gold: + prediction_tokens = normalize_answer(pred).split() + ground_truth_tokens = normalize_answer(ans).split() + common = Counter(prediction_tokens) & Counter(ground_truth_tokens) + num_same = sum(common.values()) + if num_same == 0: + all_f1s.append(0) + else: + precision = 1.0 * num_same / len(prediction_tokens) + recall = 1.0 * num_same / len(ground_truth_tokens) + all_f1s.append((2 * precision * recall) / (precision + recall)) + return np.max(all_f1s) \ No newline at end of file diff --git a/baselines/agzo/zo-bench/modeling_llama.py b/baselines/agzo/zo-bench/modeling_llama.py new file mode 100644 index 0000000..88c84c8 --- /dev/null +++ b/baselines/agzo/zo-bench/modeling_llama.py @@ -0,0 +1,1413 @@ +# coding=utf-8 +# Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved. +# +# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX +# and OPT implementations in this library. It has been modified from its +# original forms to accommodate minor architectural differences compared +# to GPT-NeoX and OPT used by the Meta AI team that trained the model. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" PyTorch LLaMA model.""" +import math +import warnings +from typing import List, Optional, Tuple, Union + +import torch +import torch.nn.functional as F +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss +from transformers.activations import ACT2FN +from transformers.cache_utils import Cache, DynamicCache +from transformers.modeling_attn_mask_utils import ( + AttentionMaskConverter, + _prepare_4d_attention_mask, + _prepare_4d_causal_attention_mask, + _prepare_4d_causal_attention_mask_for_sdpa, +) +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, \ + SequenceClassifierOutputWithPast +from transformers.modeling_utils import PreTrainedModel +from transformers.models.llama.configuration_llama import LlamaConfig +from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13 +from transformers.utils import ( + add_start_docstrings, + add_start_docstrings_to_model_forward, + is_flash_attn_2_available, + is_flash_attn_greater_or_equal_2_10, + logging, + replace_return_docstrings, +) +from transformers.utils.import_utils import is_torch_fx_available + +if is_flash_attn_2_available(): + from flash_attn import flash_attn_func, flash_attn_varlen_func + from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa + +# This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph. +# It means that the function will not be traced through and simply appear as a node in the graph. +if is_torch_fx_available(): + if not is_torch_greater_or_equal_than_1_13: + import torch.fx + + _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask) + +logger = logging.get_logger(__name__) + +_CONFIG_FOR_DOC = "LlamaConfig" + + +def _get_unpad_data(attention_mask): + seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) + indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() + max_seqlen_in_batch = seqlens_in_batch.max().item() + cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)) + return ( + indices, + cu_seqlens, + max_seqlen_in_batch, + ) + + +def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): + warnings.warn( + "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask" + ) + return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len) + + +def _make_causal_mask( + input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 +): + warnings.warn( + "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask" + ) + return AttentionMaskConverter._make_causal_mask( + input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length + ) + + +class LlamaRMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + """ + LlamaRMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states): + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return self.weight * hidden_states.to(input_dtype) + + +ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm) + + +class LlamaRotaryEmbedding(nn.Module): + def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): + super().__init__() + + self.dim = dim + self.max_position_embeddings = max_position_embeddings + self.base = base + inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + + # Build here to make `torch.jit.trace` work. + self._set_cos_sin_cache( + seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() + ) + + def _set_cos_sin_cache(self, seq_len, device, dtype): + self.max_seq_len_cached = seq_len + t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) + + freqs = torch.outer(t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1) + self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) + self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) + + def forward(self, x, seq_len=None): + # x: [bs, num_attention_heads, seq_len, head_size] + if seq_len > self.max_seq_len_cached: + self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) + + return ( + self.cos_cached[:seq_len].to(dtype=x.dtype), + self.sin_cached[:seq_len].to(dtype=x.dtype), + ) + + +class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding): + """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev""" + + def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): + self.scaling_factor = scaling_factor + super().__init__(dim, max_position_embeddings, base, device) + + def _set_cos_sin_cache(self, seq_len, device, dtype): + self.max_seq_len_cached = seq_len + t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) + t = t / self.scaling_factor + + freqs = torch.outer(t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1) + self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) + self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) + + +class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding): + """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla""" + + def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0): + self.scaling_factor = scaling_factor + super().__init__(dim, max_position_embeddings, base, device) + + def _set_cos_sin_cache(self, seq_len, device, dtype): + self.max_seq_len_cached = seq_len + + if seq_len > self.max_position_embeddings: + base = self.base * ( + (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1) + ) ** (self.dim / (self.dim - 2)) + inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + + t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) + + freqs = torch.outer(t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1) + self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) + self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) + + +def rotate_half(x): + """Rotates half the hidden dims of the input.""" + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2:] + return torch.cat((-x2, x1), dim=-1) + + +def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): + """Applies Rotary Position Embedding to the query and key tensors. + + Args: + q (`torch.Tensor`): The query tensor. + k (`torch.Tensor`): The key tensor. + cos (`torch.Tensor`): The cosine part of the rotary embedding. + sin (`torch.Tensor`): The sine part of the rotary embedding. + position_ids (`torch.Tensor`): + The position indices of the tokens corresponding to the query and key tensors. For example, this can be + used to pass offsetted position ids when working with a KV-cache. + unsqueeze_dim (`int`, *optional*, defaults to 1): + The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and + sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note + that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and + k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes + cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have + the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. + Returns: + `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. + """ + cos = cos[position_ids].unsqueeze(unsqueeze_dim) + sin = sin[position_ids].unsqueeze(unsqueeze_dim) + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + return q_embed, k_embed + + +class LlamaMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) + self.act_fn = ACT2FN[config.hidden_act] + + def forward(self, x): + if self.config.pretraining_tp > 1: + slice = self.intermediate_size // self.config.pretraining_tp + gate_proj_slices = self.gate_proj.weight.split(slice, dim=0) + up_proj_slices = self.up_proj.weight.split(slice, dim=0) + down_proj_slices = self.down_proj.weight.split(slice, dim=1) + + gate_proj = torch.cat( + [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1 + ) + up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1) + + intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2) + down_proj = [ + F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp) + ] + down_proj = sum(down_proj) + else: + down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + + return down_proj + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +class LlamaAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None): + super().__init__() + self.config = config + self.layer_idx = layer_idx + if layer_idx is None: + logger.warning_once( + f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will " + "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " + "when creating this class." + ) + + self.attention_dropout = config.attention_dropout + self.hidden_size = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = self.hidden_size // self.num_heads + self.num_key_value_heads = config.num_key_value_heads + self.num_key_value_groups = self.num_heads // self.num_key_value_heads + self.max_position_embeddings = config.max_position_embeddings + self.rope_theta = config.rope_theta + self.is_causal = True + + if (self.head_dim * self.num_heads) != self.hidden_size: + raise ValueError( + f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" + f" and `num_heads`: {self.num_heads})." + ) + + self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias) + self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias) + self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias) + self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias) + self._init_rope() + + def _init_rope(self): + if self.config.rope_scaling is None: + self.rotary_emb = LlamaRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + base=self.rope_theta, + ) + else: + scaling_type = self.config.rope_scaling["type"] + scaling_factor = self.config.rope_scaling["factor"] + if scaling_type == "linear": + self.rotary_emb = LlamaLinearScalingRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + scaling_factor=scaling_factor, + base=self.rope_theta, + ) + elif scaling_type == "dynamic": + self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + scaling_factor=scaling_factor, + base=self.rope_theta, + ) + else: + raise ValueError(f"Unknown RoPE scaling type {scaling_type}") + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if "padding_mask" in kwargs: + warnings.warn( + "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" + ) + + bsz, q_len, _ = hidden_states.size() + + if self.config.pretraining_tp > 1: + key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp + query_slices = self.q_proj.weight.split( + (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0 + ) + key_slices = self.k_proj.weight.split(key_value_slicing, dim=0) + value_slices = self.v_proj.weight.split(key_value_slicing, dim=0) + + query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)] + query_states = torch.cat(query_states, dim=-1) + + key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)] + key_states = torch.cat(key_states, dim=-1) + + value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)] + value_states = torch.cat(value_states, dim=-1) + + else: + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + if self.layer_idx is None: + raise ValueError( + f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} " + "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class " + "with a layer index." + ) + kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) + cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + + if past_key_value is not None: + cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) + + if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): + raise ValueError( + f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" + ) + attn_weights = attn_weights + attention_mask + + # upcast attention to fp32 + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) + attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training) + attn_output = torch.matmul(attn_weights, value_states) + + if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.transpose(1, 2).contiguous() + + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) + + if self.config.pretraining_tp > 1: + attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2) + o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1) + attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)]) + else: + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + +class LlamaFlashAttention2(LlamaAttention): + """ + Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays + untouched. The only required change would be on the forward pass where it needs to correctly call the public API of + flash attention and deal with padding tokens in case the input contains any of them. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. + # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. + # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). + self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + **kwargs, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + # LlamaFlashAttention2 attention does not support output_attentions + if "padding_mask" in kwargs: + warnings.warn( + "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" + ) + + # overwrite attention_mask with padding_mask + attention_mask = kwargs.pop("padding_mask") + + output_attentions = False + + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + # Flash attention requires the input to have the shape + # batch_size x seq_length x head_dim x hidden_dim + # therefore we just need to keep the original shape + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) + cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + + if past_key_value is not None: + cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache + # to be able to avoid many of these transpose/reshape/view. + query_states = query_states.transpose(1, 2) + key_states = key_states.transpose(1, 2) + value_states = value_states.transpose(1, 2) + + dropout_rate = self.attention_dropout if self.training else 0.0 + + # In PEFT, usually we cast the layer norms in float32 for training stability reasons + # therefore the input hidden states gets silently casted in float32. Hence, we need + # cast them back in the correct dtype just to be sure everything works as expected. + # This might slowdown training & inference so it is recommended to not cast the LayerNorms + # in fp32. (LlamaRMSNorm handles it correctly) + + input_dtype = query_states.dtype + if input_dtype == torch.float32: + # Handle the case where the model is quantized + if hasattr(self.config, "_pre_quantization_dtype"): + target_dtype = self.config._pre_quantization_dtype + elif torch.is_autocast_enabled(): + target_dtype = torch.get_autocast_gpu_dtype() + else: + target_dtype = self.q_proj.weight.dtype + + logger.warning_once( + f"The input hidden states seems to be silently casted in float32, this might be related to" + f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" + f" {target_dtype}." + ) + + query_states = query_states.to(target_dtype) + key_states = key_states.to(target_dtype) + value_states = value_states.to(target_dtype) + + attn_output = self._flash_attention_forward( + query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate + ) + + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + def _flash_attention_forward( + self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None + ): + """ + Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token + first unpad the input, then computes the attention scores and pad the final attention scores. + + Args: + query_states (`torch.Tensor`): + Input query states to be passed to Flash Attention API + key_states (`torch.Tensor`): + Input key states to be passed to Flash Attention API + value_states (`torch.Tensor`): + Input value states to be passed to Flash Attention API + attention_mask (`torch.Tensor`): + The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the + position of padding tokens and 1 for the position of non-padding tokens. + dropout (`int`, *optional*): + Attention dropout + softmax_scale (`float`, *optional*): + The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) + """ + if not self._flash_attn_uses_top_left_mask: + causal = self.is_causal + else: + # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__. + causal = self.is_causal and query_length != 1 + + # Contains at least one padding token in the sequence + if attention_mask is not None: + batch_size = query_states.shape[0] + query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input( + query_states, key_states, value_states, attention_mask, query_length + ) + + cu_seqlens_q, cu_seqlens_k = cu_seq_lens + max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens + + attn_output_unpad = flash_attn_varlen_func( + query_states, + key_states, + value_states, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_in_batch_q, + max_seqlen_k=max_seqlen_in_batch_k, + dropout_p=dropout, + softmax_scale=softmax_scale, + causal=causal, + ) + + attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) + else: + attn_output = flash_attn_func( + query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal + ) + + return attn_output + + def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length): + indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) + batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape + + key_layer = index_first_axis( + key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k + ) + value_layer = index_first_axis( + value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k + ) + if query_length == kv_seq_len: + query_layer = index_first_axis( + query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k + ) + cu_seqlens_q = cu_seqlens_k + max_seqlen_in_batch_q = max_seqlen_in_batch_k + indices_q = indices_k + elif query_length == 1: + max_seqlen_in_batch_q = 1 + cu_seqlens_q = torch.arange( + batch_size + 1, dtype=torch.int32, device=query_layer.device + ) # There is a memcpy here, that is very bad. + indices_q = cu_seqlens_q[:-1] + query_layer = query_layer.squeeze(1) + else: + # The -q_len: slice assumes left padding. + attention_mask = attention_mask[:, -query_length:] + query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask) + + return ( + query_layer, + key_layer, + value_layer, + indices_q, + (cu_seqlens_q, cu_seqlens_k), + (max_seqlen_in_batch_q, max_seqlen_in_batch_k), + ) + + +class LlamaSdpaAttention(LlamaAttention): + """ + Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from + `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to + SDPA API. + """ + + # Adapted from LlamaAttention.forward + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Cache] = None, + output_attentions: bool = False, + use_cache: bool = False, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + if output_attentions: + # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented. + logger.warning_once( + "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, " + 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.' + ) + return super().forward( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) + cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + + if past_key_value is not None: + cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models + key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs) + + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" + ) + + # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask, + # Reference: https://github.com/pytorch/pytorch/issues/112577. + if query_states.device.type == "cuda" and attention_mask is not None: + query_states = query_states.contiguous() + key_states = key_states.contiguous() + value_states = value_states.contiguous() + + attn_output = torch.nn.functional.scaled_dot_product_attention( + query_states, + key_states, + value_states, + attn_mask=attention_mask, + dropout_p=self.attention_dropout if self.training else 0.0, + # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1. + is_causal=self.is_causal and attention_mask is None and q_len > 1, + ) + + attn_output = attn_output.transpose(1, 2).contiguous() + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) + + attn_output = self.o_proj(attn_output) + + return attn_output, None, past_key_value + + +LLAMA_ATTENTION_CLASSES = { + "eager": LlamaAttention, + "flash_attention_2": LlamaFlashAttention2, + "sdpa": LlamaSdpaAttention, +} + + +class LlamaDecoderLayer(nn.Module): + def __init__(self, config: LlamaConfig, layer_idx: int): + super().__init__() + self.hidden_size = config.hidden_size + + self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx) + + self.mlp = LlamaMLP(config) + self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + **kwargs, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): + attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, + query_sequence_length, key_sequence_length)` if default attention is used. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + if "padding_mask" in kwargs: + warnings.warn( + "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" + ) + + residual = hidden_states + + hidden_states = self.input_layernorm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + **kwargs, + ) + hidden_states = residual + hidden_states + + # Fully Connected + residual = hidden_states + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +LLAMA_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`LlamaConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", + LLAMA_START_DOCSTRING, +) +class LlamaPreTrainedModel(PreTrainedModel): + config_class = LlamaConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["LlamaDecoderLayer"] + _skip_keys_device_placement = "past_key_values" + _supports_flash_attn_2 = True + _supports_sdpa = True + _supports_cache_class = True + + def _init_weights(self, module): + std = self.config.initializer_range + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + +LLAMA_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.n_positions - 1]`. + + [What are position IDs?](../glossary#position-ids) + past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): + Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` + returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`. + + Two formats are allowed: + - a [`~cache_utils.Cache`] instance; + - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy + cache format. + + The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the + legacy cache format will be returned. + + If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't + have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` + of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +@add_start_docstrings( + "The bare LLaMA Model outputting raw hidden-states without any specific head on top.", + LLAMA_START_DOCSTRING, +) +class LlamaModel(LlamaPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`] + + Args: + config: LlamaConfig + """ + + def __init__(self, config: LlamaConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList( + [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)] + ) + self._use_sdpa = config._attn_implementation == "sdpa" + self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2" + self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + self.gradient_checkpointing = False + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + elif input_ids is not None: + batch_size, seq_length = input_ids.shape[:2] + elif inputs_embeds is not None: + batch_size, seq_length = inputs_embeds.shape[:2] + else: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + past_key_values_length = 0 + if use_cache: + use_legacy_cache = not isinstance(past_key_values, Cache) + if use_legacy_cache: + past_key_values = DynamicCache.from_legacy_cache(past_key_values) + past_key_values_length = past_key_values.get_usable_length(seq_length) + + if position_ids is None: + device = input_ids.device if input_ids is not None else inputs_embeds.device + position_ids = torch.arange( + past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device + ) + position_ids = position_ids.unsqueeze(0) + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + if self._use_flash_attention_2: + # 2d mask is passed through the layers + attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None + elif self._use_sdpa and not output_attentions: + # output_attentions=True can not be supported when using SDPA, and we fall back on + # the manual implementation that requires a 4D causal mask in all cases. + attention_mask = _prepare_4d_causal_attention_mask_for_sdpa( + attention_mask, + (batch_size, seq_length), + inputs_embeds, + past_key_values_length, + ) + else: + # 4d mask is passed through the layers + attention_mask = _prepare_4d_causal_attention_mask( + attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length + ) + + # embed positions + hidden_states = inputs_embeds + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = None + + for decoder_layer in self.layers: + if output_hidden_states: + all_hidden_states += (hidden_states,) + + if self.gradient_checkpointing and self.training: + layer_outputs = self._gradient_checkpointing_func( + decoder_layer.__call__, + hidden_states, + attention_mask, + position_ids, + past_key_values, + output_attentions, + use_cache, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_values, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache = layer_outputs[2 if output_attentions else 1] + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = None + if use_cache: + next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +class LlamaForCausalLMWithHeadTuning(LlamaPreTrainedModel): + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = LlamaModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, LlamaForCausalLM + + >>> model = LlamaForCausalLMWithHeadTuning.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) + >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) + + >>> prompt = "Hey, are you conscious? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." + ```""" + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + # MeZO added: torch.no_grad + with torch.no_grad(): + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0] + if self.config.pretraining_tp > 1: + lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0) + logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)] + logits = torch.cat(logits, dim=-1) + else: + logits = self.lm_head(hidden_states) + logits = logits.float() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + shift_logits = shift_logits.view(-1, self.config.vocab_size) + shift_labels = shift_labels.view(-1) + # Enable model parallelism + shift_labels = shift_labels.to(shift_logits.device) + loss = loss_fct(shift_logits, shift_labels) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + ): + if past_key_values is not None: + if isinstance(past_key_values, Cache): + cache_length = past_key_values.get_seq_length() + past_length = past_key_values.seen_tokens + max_cache_length = past_key_values.get_max_length() + else: + cache_length = past_length = past_key_values[0][0].shape[2] + max_cache_length = None + + # Keep only the unprocessed tokens: + # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where + # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as + # input) + if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]: + input_ids = input_ids[:, -(attention_mask.shape[1] - past_length):] + # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard + # input_ids based on the past_length. + elif past_length < input_ids.shape[1]: + input_ids = input_ids[:, past_length:] + # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens. + + # If we are about to go beyond the maximum cache length, we need to crop the input attention mask. + if ( + max_cache_length is not None + and attention_mask is not None + and cache_length + input_ids.shape[1] > max_cache_length + ): + attention_mask = attention_mask[:, -max_cache_length:] + + position_ids = kwargs.get("position_ids", None) + if attention_mask is not None and position_ids is None: + # create position_ids on the fly for batch generation + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + if past_key_values: + position_ids = position_ids[:, -input_ids.shape[1]:] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + model_inputs.update( + { + "position_ids": position_ids, + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += ( + tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past), + ) + return reordered_past + + +@add_start_docstrings( + """ + The LLaMa Model transformer with a sequence classification head on top (linear layer). + + [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + LLAMA_START_DOCSTRING, +) +class LlamaForSequenceClassification(LlamaPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + self.model = LlamaModel(config) + self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + + if self.config.pad_token_id is None and batch_size != 1: + raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to( + logits.device + ) + else: + sequence_lengths = -1 + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + labels = labels.to(logits.device) + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) diff --git a/baselines/agzo/zo-bench/modeling_mistral/__init__.py b/baselines/agzo/zo-bench/modeling_mistral/__init__.py new file mode 100644 index 0000000..711f2b6 --- /dev/null +++ b/baselines/agzo/zo-bench/modeling_mistral/__init__.py @@ -0,0 +1,8 @@ +from .configuration_mistral import MistralConfig, MISTRAL_PRETRAINED_CONFIG_ARCHIVE_MAP +from .modeling_mistral import ( + MistralModel, + MistralForCausalLM, + MistralForSequenceClassification, + MistralPreTrainedModel, + MistralForCausalLMWithHeadTuning +) diff --git a/baselines/agzo/zo-bench/modeling_mistral/configuration_mistral.py b/baselines/agzo/zo-bench/modeling_mistral/configuration_mistral.py new file mode 100644 index 0000000..e888c99 --- /dev/null +++ b/baselines/agzo/zo-bench/modeling_mistral/configuration_mistral.py @@ -0,0 +1,152 @@ +# coding=utf-8 +# Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" Mistral model configuration""" + +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import logging + + +logger = logging.get_logger(__name__) + +MISTRAL_PRETRAINED_CONFIG_ARCHIVE_MAP = { + "mistralai/Mistral-7B-v0.1": "https://huggingface.co/mistralai/Mistral-7B-v0.1/resolve/main/config.json", + "mistralai/Mistral-7B-Instruct-v0.1": "https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1/resolve/main/config.json", +} + + +class MistralConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`MistralModel`]. It is used to instantiate an + Mistral model according to the specified arguments, defining the model architecture. Instantiating a configuration + with the defaults will yield a similar configuration to that of the Mistral-7B-v0.1 or Mistral-7B-Instruct-v0.1. + + [mistralai/Mistral-7B-v0.1](https://huggingface.co/mistralai/Mistral-7B-v0.1) + [mistralai/Mistral-7B-Instruct-v0.1](https://huggingface.co/mistralai/Mistral-7B-Instruct-v0.1) + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + + Args: + vocab_size (`int`, *optional*, defaults to 32000): + Vocabulary size of the Mistral model. Defines the number of different tokens that can be represented by the + `inputs_ids` passed when calling [`MistralModel`] + hidden_size (`int`, *optional*, defaults to 4096): + Dimension of the hidden representations. + intermediate_size (`int`, *optional*, defaults to 14336): + Dimension of the MLP representations. + num_hidden_layers (`int`, *optional*, defaults to 32): + Number of hidden layers in the Transformer encoder. + num_attention_heads (`int`, *optional*, defaults to 32): + Number of attention heads for each attention layer in the Transformer encoder. + num_key_value_heads (`int`, *optional*, defaults to 8): + This is the number of key_value heads that should be used to implement Grouped Query Attention. If + `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if + `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When + converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed + by meanpooling all the original heads within that group. For more details checkout [this + paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `8`. + hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): + The non-linear activation function (function or string) in the decoder. + max_position_embeddings (`int`, *optional*, defaults to `4096*32`): + The maximum sequence length that this model might ever be used with. Mistral's sliding window attention + allows sequence of up to 4096*32 tokens. + initializer_range (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + rms_norm_eps (`float`, *optional*, defaults to 1e-06): + The epsilon used by the rms normalization layers. + use_cache (`bool`, *optional*, defaults to `True`): + Whether or not the model should return the last key/values attentions (not used by all models). Only + relevant if `config.is_decoder=True`. + pad_token_id (`int`, *optional*): + The id of the padding token. + bos_token_id (`int`, *optional*, defaults to 1): + The id of the "beginning-of-sequence" token. + eos_token_id (`int`, *optional*, defaults to 2): + The id of the "end-of-sequence" token. + tie_word_embeddings (`bool`, *optional*, defaults to `False`): + Whether the model's input and output word embeddings should be tied. + rope_theta (`float`, *optional*, defaults to 10000.0): + The base period of the RoPE embeddings. + sliding_window (`int`, *optional*, defaults to 4096): + Sliding window attention window size. If not specified, will default to `4096`. + attention_dropout (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + + ```python + >>> from transformers import MistralModel, MistralConfig + + >>> # Initializing a Mistral 7B style configuration + >>> configuration = MistralConfig() + + >>> # Initializing a model from the Mistral 7B style configuration + >>> model = MistralModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + + model_type = "mistral" + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + vocab_size=32000, + hidden_size=4096, + intermediate_size=14336, + num_hidden_layers=32, + num_attention_heads=32, + num_key_value_heads=8, + hidden_act="silu", + max_position_embeddings=4096 * 32, + initializer_range=0.02, + rms_norm_eps=1e-6, + use_cache=True, + pad_token_id=None, + bos_token_id=1, + eos_token_id=2, + tie_word_embeddings=False, + rope_theta=10000.0, + sliding_window=4096, + attention_dropout=0.0, + **kwargs, + ): + self.vocab_size = vocab_size + self.max_position_embeddings = max_position_embeddings + self.hidden_size = hidden_size + self.intermediate_size = intermediate_size + self.num_hidden_layers = num_hidden_layers + self.num_attention_heads = num_attention_heads + self.sliding_window = sliding_window + + # for backward compatibility + if num_key_value_heads is None: + num_key_value_heads = num_attention_heads + + self.num_key_value_heads = num_key_value_heads + self.hidden_act = hidden_act + self.initializer_range = initializer_range + self.rms_norm_eps = rms_norm_eps + self.use_cache = use_cache + self.rope_theta = rope_theta + self.attention_dropout = attention_dropout + + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + tie_word_embeddings=tie_word_embeddings, + **kwargs, + ) \ No newline at end of file diff --git a/baselines/agzo/zo-bench/modeling_mistral/modeling_mistral.py b/baselines/agzo/zo-bench/modeling_mistral/modeling_mistral.py new file mode 100644 index 0000000..123ae52 --- /dev/null +++ b/baselines/agzo/zo-bench/modeling_mistral/modeling_mistral.py @@ -0,0 +1,1405 @@ +# coding=utf-8 +# Copyright 2023 Mistral AI and the HuggingFace Inc. team. All rights reserved. +# +# This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX +# and OPT implementations in this library. It has been modified from its +# original forms to accommodate minor architectural differences compared +# to GPT-NeoX and OPT used by the Meta AI team that trained the model. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" PyTorch Mistral model.""" +import math +from typing import List, Optional, Tuple, Union + +import torch +import torch.nn.functional as F +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss +from transformers.activations import ACT2FN +from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, \ + SequenceClassifierOutputWithPast +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import ( + add_start_docstrings, + add_start_docstrings_to_model_forward, + # is_flash_attn_available, + logging, + replace_return_docstrings, +) + +from .configuration_mistral import MistralConfig + +# if is_flash_attn_available(): +# from flash_attn import flash_attn_func, flash_attn_varlen_func +# from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa +# +# _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters) +_flash_supports_window_size = False + +logger = logging.get_logger(__name__) + +_CONFIG_FOR_DOC = "MistralConfig" + + +# Copied from transformers.models.llama.modeling_llama._get_unpad_data +def _get_unpad_data(padding_mask): + seqlens_in_batch = padding_mask.sum(dim=-1, dtype=torch.int32) + indices = torch.nonzero(padding_mask.flatten(), as_tuple=False).flatten() + max_seqlen_in_batch = seqlens_in_batch.max().item() + cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0)) + return ( + indices, + cu_seqlens, + max_seqlen_in_batch, + ) + + +def _make_sliding_window_causal_mask( + input_ids_shape: torch.Size, + dtype: torch.dtype, + device: torch.device, + past_key_values_length: int = 0, + sliding_window: int = 4096, +): + """ + Make causal mask used for sliding window attention + """ + bsz, tgt_len = input_ids_shape + + tensor = torch.full( + (tgt_len, tgt_len), + fill_value=1, + device=device, + ) + mask = torch.tril(tensor, diagonal=0) + # make the mask banded to account for sliding window + mask = torch.triu(mask, diagonal=-sliding_window) + mask = torch.log(mask).to(dtype) + + if past_key_values_length > 0: + mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) + return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) + + +# Copied from transformers.models.bart.modeling_bart._expand_mask +def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + bsz, src_len = mask.size() + tgt_len = tgt_len if tgt_len is not None else src_len + + expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) + + inverted_mask = 1.0 - expanded_mask + + return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) + + +# Copied from transformers.models.llama.modeling_llama.LlamaRMSNorm with Llama->Mistral +class MistralRMSNorm(nn.Module): + def __init__(self, hidden_size, eps=1e-6): + """ + MistralRMSNorm is equivalent to T5LayerNorm + """ + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.variance_epsilon = eps + + def forward(self, hidden_states): + input_dtype = hidden_states.dtype + hidden_states = hidden_states.to(torch.float32) + variance = hidden_states.pow(2).mean(-1, keepdim=True) + hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) + return self.weight * hidden_states.to(input_dtype) + + +# Copied from transformers.models.llama.modeling_llama.LlamaRotaryEmbedding with Llama->Mistral +class MistralRotaryEmbedding(nn.Module): + def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): + super().__init__() + + self.dim = dim + self.max_position_embeddings = max_position_embeddings + self.base = base + inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim)) + self.register_buffer("inv_freq", inv_freq, persistent=False) + + # Build here to make `torch.jit.trace` work. + self._set_cos_sin_cache( + seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype() + ) + + def _set_cos_sin_cache(self, seq_len, device, dtype): + self.max_seq_len_cached = seq_len + t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype) + + freqs = torch.einsum("i,j->ij", t, self.inv_freq) + # Different from paper, but it uses a different permutation in order to obtain the same calculation + emb = torch.cat((freqs, freqs), dim=-1) + self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False) + self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False) + + def forward(self, x, seq_len=None): + # x: [bs, num_attention_heads, seq_len, head_size] + if seq_len > self.max_seq_len_cached: + self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) + + return ( + self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype), + self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype), + ) + + +# Copied from transformers.models.llama.modeling_llama.rotate_half +def rotate_half(x): + """Rotates half the hidden dims of the input.""" + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2:] + return torch.cat((-x2, x1), dim=-1) + + +# Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb +def apply_rotary_pos_emb(q, k, cos, sin, position_ids): + # The first two dimensions of cos and sin are always 1, so we can `squeeze` them. + cos = cos.squeeze(1).squeeze(0) # [seq_len, dim] + sin = sin.squeeze(1).squeeze(0) # [seq_len, dim] + cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] + sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim] + q_embed = (q * cos) + (rotate_half(q) * sin) + k_embed = (k * cos) + (rotate_half(k) * sin) + return q_embed, k_embed + + +class MistralMLP(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.intermediate_size = config.intermediate_size + self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) + self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) + self.act_fn = ACT2FN[config.hidden_act] + + def forward(self, x): + return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) + + +def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: + """ + This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, + num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) + """ + batch, num_key_value_heads, slen, head_dim = hidden_states.shape + if n_rep == 1: + return hidden_states + hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim) + return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) + + +class MistralAttention(nn.Module): + """ + Multi-headed attention from 'Attention Is All You Need' paper. Modified to use sliding window attention: Longformer + and "Generating Long Sequences with Sparse Transformers". + """ + + def __init__(self, config: MistralConfig): + super().__init__() + self.config = config + self.hidden_size = config.hidden_size + self.num_heads = config.num_attention_heads + self.head_dim = self.hidden_size // self.num_heads + self.num_key_value_heads = config.num_key_value_heads + self.num_key_value_groups = self.num_heads // self.num_key_value_heads + self.max_position_embeddings = config.max_position_embeddings + self.rope_theta = config.rope_theta + + if (self.head_dim * self.num_heads) != self.hidden_size: + raise ValueError( + f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}" + f" and `num_heads`: {self.num_heads})." + ) + self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False) + self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) + self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=False) + self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False) + + self.rotary_emb = MistralRotaryEmbedding( + self.head_dim, + max_position_embeddings=self.max_position_embeddings, + base=self.rope_theta, + ) + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: bool = False, + use_cache: bool = False, + padding_mask: Optional[torch.Tensor] = None, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + kv_seq_len += past_key_value[0].shape[-2] + cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + + if past_key_value is not None: + # reuse k, v, self_attention + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + + past_key_value = (key_states, value_states) if use_cache else None + + # repeat k/v heads if n_kv_heads < n_heads + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim) + + if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): + raise ValueError( + f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" + ) + + attn_weights = attn_weights + attention_mask + + # upcast attention to fp32 + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype) + attn_output = torch.matmul(attn_weights, value_states) + + if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.transpose(1, 2).contiguous() + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size) + + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + +class MistralFlashAttention2(MistralAttention): + """ + Mistral flash attention module. This module inherits from `MistralAttention` as the weights of the module stays + untouched. The only required change would be on the forward pass where it needs to correctly call the public API of + flash attention and deal with padding tokens in case the input contains any of them. + """ + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: bool = False, + use_cache: bool = False, + padding_mask: Optional[torch.LongTensor] = None, + ): + bsz, q_len, _ = hidden_states.size() + + query_states = self.q_proj(hidden_states) + key_states = self.k_proj(hidden_states) + value_states = self.v_proj(hidden_states) + + query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2) + key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2) + + kv_seq_len = key_states.shape[-2] + if past_key_value is not None: + kv_seq_len += past_key_value[0].shape[-2] + + # Because the input can be padded, the absolute sequence length depends on the max position id. + rotary_seq_len = max(kv_seq_len, position_ids[:, -1].max().item()) + 1 + cos, sin = self.rotary_emb(value_states, seq_len=rotary_seq_len) + + query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids) + + use_sliding_windows = ( + _flash_supports_window_size + and hasattr(self.config, "sliding_window") is not None + and kv_seq_len > self.config.sliding_window + ) + + if not _flash_supports_window_size: + logger.warning_once( + "The current flash attention version does not support sliding window attention, for a more memory efficient implementation" + " make sure to upgrade flash-attn library." + ) + + if past_key_value is not None: + # Activate slicing cache only if the config has a value `sliding_windows` attribute + if hasattr(self.config, "sliding_window") and kv_seq_len > self.config.sliding_window: + slicing_tokens = kv_seq_len - self.config.sliding_window + + past_key = past_key_value[0] + past_value = past_key_value[1] + + past_key = past_key[:, :, slicing_tokens:, :].contiguous() + past_value = past_value[:, :, slicing_tokens:, :].contiguous() + + if past_key.shape[-2] != self.config.sliding_window - 1: + raise ValueError( + f"past key much have a shape of (`batch_size, num_heads, self.config.sliding_window-1, head_dim`), got" + f" {past_key.shape}" + ) + + past_key_value = (past_key, past_value) + + if padding_mask is not None: + padding_mask = padding_mask[:, slicing_tokens:] + padding_mask = torch.cat([padding_mask, torch.ones_like(padding_mask[:, -1:])], dim=-1) + + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + + past_key_value = (key_states, value_states) if use_cache else None + + # repeat k/v heads if n_kv_heads < n_heads + key_states = repeat_kv(key_states, self.num_key_value_groups) + value_states = repeat_kv(value_states, self.num_key_value_groups) + + # TODO: Mistral does not have dropout in the config?? + # It is recommended to use dropout with FA according to the docs + # when training. + dropout_rate = 0.0 # if not self.training else self.attn_dropout + + # In PEFT, usually we cast the layer norms in float32 for training stability reasons + # therefore the input hidden states gets silently casted in float32. Hence, we need + # cast them back in float16 just to be sure everything works as expected. + input_dtype = query_states.dtype + if input_dtype == torch.float32: + logger.warning_once( + "The input hidden states seems to be silently casted in float32, this might be related to" + " the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" + " float16." + ) + + query_states = query_states.to(torch.float16) + key_states = key_states.to(torch.float16) + value_states = value_states.to(torch.float16) + + # Reashape to the expected shape for Flash Attention + query_states = query_states.transpose(1, 2) + key_states = key_states.transpose(1, 2) + value_states = value_states.transpose(1, 2) + + attn_output = self._flash_attention_forward( + query_states, + key_states, + value_states, + padding_mask, + q_len, + dropout=dropout_rate, + use_sliding_windows=use_sliding_windows, + ) + + attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous() + attn_output = self.o_proj(attn_output) + + if not output_attentions: + attn_weights = None + + return attn_output, attn_weights, past_key_value + + def _flash_attention_forward( + self, + query_states, + key_states, + value_states, + padding_mask, + query_length, + dropout=0.0, + softmax_scale=None, + use_sliding_windows=False, + ): + """ + Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token + first unpad the input, then computes the attention scores and pad the final attention scores. + + Args: + query_states (`torch.Tensor`): + Input query states to be passed to Flash Attention API + key_states (`torch.Tensor`): + Input key states to be passed to Flash Attention API + value_states (`torch.Tensor`): + Input value states to be passed to Flash Attention API + padding_mask (`torch.Tensor`): + The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the + position of padding tokens and 1 for the position of non-padding tokens. + dropout (`int`, *optional*): + Attention dropout + softmax_scale (`float`, *optional*): + The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) + use_sliding_windows (`bool`, *optional*): + Whether to activate sliding window attention. + """ + # Contains at least one padding token in the sequence + if padding_mask is not None: + batch_size = query_states.shape[0] + query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input( + query_states, key_states, value_states, padding_mask, query_length + ) + + cu_seqlens_q, cu_seqlens_k = cu_seq_lens + max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens + + if not use_sliding_windows: + attn_output_unpad = flash_attn_varlen_func( + query_states, + key_states, + value_states, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_in_batch_q, + max_seqlen_k=max_seqlen_in_batch_k, + dropout_p=dropout, + softmax_scale=softmax_scale, + causal=True, + ) + else: + attn_output_unpad = flash_attn_varlen_func( + query_states, + key_states, + value_states, + cu_seqlens_q=cu_seqlens_q, + cu_seqlens_k=cu_seqlens_k, + max_seqlen_q=max_seqlen_in_batch_q, + max_seqlen_k=max_seqlen_in_batch_k, + dropout_p=dropout, + softmax_scale=softmax_scale, + causal=True, + window_size=(self.config.sliding_window, self.config.sliding_window), + ) + + attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length) + else: + if not use_sliding_windows: + attn_output = flash_attn_func( + query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=True + ) + else: + attn_output = flash_attn_func( + query_states, + key_states, + value_states, + dropout, + softmax_scale=softmax_scale, + causal=True, + window_size=(self.config.sliding_window, self.config.sliding_window), + ) + + return attn_output + + def _upad_input(self, query_layer, key_layer, value_layer, padding_mask, query_length): + batch_size, kv_seq_len, num_heads, head_dim = key_layer.shape + + # On the first iteration we need to properly re-create the padding mask + # by slicing it on the proper place + if kv_seq_len != padding_mask.shape[-1]: + padding_mask_num_tokens = padding_mask.shape[-1] + padding_mask = padding_mask[:, padding_mask_num_tokens - kv_seq_len:] + + indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(padding_mask) + + key_layer = index_first_axis(key_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k) + value_layer = index_first_axis(value_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k) + + if query_length == kv_seq_len: + query_layer = index_first_axis( + query_layer.reshape(batch_size * kv_seq_len, num_heads, head_dim), indices_k + ) + cu_seqlens_q = cu_seqlens_k + max_seqlen_in_batch_q = max_seqlen_in_batch_k + indices_q = indices_k + elif query_length == 1: + max_seqlen_in_batch_q = 1 + cu_seqlens_q = torch.arange( + batch_size + 1, dtype=torch.int32, device=query_layer.device + ) # There is a memcpy here, that is very bad. + indices_q = cu_seqlens_q[:-1] + query_layer = query_layer.squeeze(1) + else: + # The -q_len: slice assumes left padding. + padding_mask = padding_mask[:, -query_length:] + query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, padding_mask) + + return ( + query_layer, + key_layer, + value_layer, + indices_q, + (cu_seqlens_q, cu_seqlens_k), + (max_seqlen_in_batch_q, max_seqlen_in_batch_k), + ) + + +class MistralDecoderLayer(nn.Module): + def __init__(self, config: MistralConfig): + super().__init__() + self.hidden_size = config.hidden_size + self.self_attn = ( + MistralAttention(config=config) + if not getattr(config, "_flash_attn_2_enabled", False) + else MistralFlashAttention2(config) + ) + self.mlp = MistralMLP(config) + self.input_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + self.post_attention_layernorm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + padding_mask: Optional[torch.Tensor] = None, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + + residual = hidden_states + + hidden_states = self.input_layernorm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + padding_mask=padding_mask, + ) + hidden_states = residual + hidden_states + + # Fully Connected + residual = hidden_states + hidden_states = self.post_attention_layernorm(hidden_states) + hidden_states = self.mlp(hidden_states) + hidden_states = residual + hidden_states + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +MISTRAL_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`MistralConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare Mistral Model outputting raw hidden-states without any specific head on top.", + MISTRAL_START_DOCSTRING, +) +class MistralPreTrainedModel(PreTrainedModel): + config_class = MistralConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["MistralDecoderLayer"] + _skip_keys_device_placement = "past_key_values" + _supports_flash_attn_2 = True + + def _init_weights(self, module): + std = self.config.initializer_range + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, MistralModel): + module.gradient_checkpointing = value + + +MISTRAL_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.n_positions - 1]`. + + [What are position IDs?](../glossary#position-ids) + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape + `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape + `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +@add_start_docstrings( + "The bare Mistral Model outputting raw hidden-states without any specific head on top.", + MISTRAL_START_DOCSTRING, +) +class MistralModel(MistralPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`MistralDecoderLayer`] + + Args: + config: MistralConfig + """ + + def __init__(self, config: MistralConfig): + super().__init__(config) + self.padding_idx = config.pad_token_id + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx) + self.layers = nn.ModuleList([MistralDecoderLayer(config) for _ in range(config.num_hidden_layers)]) + self.norm = MistralRMSNorm(config.hidden_size, eps=config.rms_norm_eps) + + self.gradient_checkpointing = False + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + def _prepare_decoder_attention_mask( + self, attention_mask, input_shape, inputs_embeds, past_key_values_length, sliding_window + ): + # create causal mask + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + combined_attention_mask = None + if input_shape[-1] > 1: + combined_attention_mask = _make_sliding_window_causal_mask( + input_shape, + inputs_embeds.dtype, + device=inputs_embeds.device, + past_key_values_length=past_key_values_length, + sliding_window=sliding_window, + ) + + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( + inputs_embeds.device + ) + combined_attention_mask = ( + expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask + ) + + return combined_attention_mask + + @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + batch_size, seq_length = input_ids.shape + elif inputs_embeds is not None: + batch_size, seq_length, _ = inputs_embeds.shape + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + seq_length_with_past = seq_length + past_key_values_length = 0 + + if past_key_values is not None: + past_key_values_length = past_key_values[0][0].shape[2] + seq_length_with_past = seq_length_with_past + past_key_values_length + + if position_ids is None: + device = input_ids.device if input_ids is not None else inputs_embeds.device + position_ids = torch.arange( + past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device + ) + position_ids = position_ids.unsqueeze(0).view(-1, seq_length) + else: + position_ids = position_ids.view(-1, seq_length).long() + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + padding_mask = None + + # embed positions + if attention_mask is None: + attention_mask = torch.ones( + (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device + ) + elif 0 in attention_mask: + padding_mask = attention_mask + + if ( + padding_mask is not None + and hasattr(self.config, "_flash_attn_2_enabled") + and self.config._flash_attn_2_enabled + ): + is_padding_right = padding_mask[:, -1].sum().item() != batch_size + if is_padding_right: + raise ValueError( + "You are attempting to perform batched generation with padding_side='right'" + " this may lead to unexpected behaviour for Flash Attention version of Mistral. Make sure to " + " call `tokenizer.padding_side = 'left'` before tokenizing the input. " + ) + + attention_mask = self._prepare_decoder_attention_mask( + attention_mask, + (batch_size, seq_length), + inputs_embeds, + past_key_values_length, + sliding_window=self.config.sliding_window, + ) + + hidden_states = inputs_embeds + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + for idx, decoder_layer in enumerate(self.layers): + if output_hidden_states: + all_hidden_states += (hidden_states,) + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, past_key_value, output_attentions, padding_mask=padding_mask) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + position_ids, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + padding_mask=padding_mask, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + hidden_states = self.norm(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +class MistralForCausalLM(MistralPreTrainedModel): + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = MistralModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, MistralForCausalLM + + >>> model = MistralForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) + >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) + + >>> prompt = "Hey, are you conscious? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + logits = logits.float() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + shift_logits = shift_logits.view(-1, self.config.vocab_size) + shift_labels = shift_labels.view(-1) + # Enable model parallelism + shift_labels = shift_labels.to(shift_logits.device) + loss = loss_fct(shift_logits, shift_labels) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + ): + if past_key_values: + input_ids = input_ids[:, -1:] + + position_ids = kwargs.get("position_ids", None) + if attention_mask is not None and position_ids is None: + # create position_ids on the fly for batch generation + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + if past_key_values: + position_ids = position_ids[:, -1].unsqueeze(-1) + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + model_inputs.update( + { + "position_ids": position_ids, + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += ( + tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past), + ) + return reordered_past + + +@add_start_docstrings( + """ + The Mistral Model transformer with a sequence classification head on top (linear layer). + + [`MistralForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + MISTRAL_START_DOCSTRING, +) +# Copied from transformers.models.llama.modeling_llama.LlamaForSequenceClassification with Llama->Mistral, LLAMA->MISTRAL +class MistralForSequenceClassification(MistralPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + self.model = MistralModel(config) + self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + + if self.config.pad_token_id is None and batch_size != 1: + raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.") + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to( + logits.device + ) + else: + sequence_lengths = -1 + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + labels = labels.to(logits.device) + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + +class MistralForCausalLMWithHeadTuning(MistralPreTrainedModel): + _tied_weights_keys = ["lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = MistralModel(config) + self.vocab_size = config.vocab_size + self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.embed_tokens + + def set_input_embeddings(self, value): + self.model.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model = decoder + + def get_decoder(self): + return self.model + + @add_start_docstrings_to_model_forward(MISTRAL_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + position_ids: Optional[torch.LongTensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, MistralForCausalLM + + >>> model = MistralForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) + >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) + + >>> prompt = "Hey, are you conscious? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + with torch.no_grad(): + outputs = self.model( + input_ids=input_ids, + attention_mask=attention_mask, + position_ids=position_ids, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + hidden_states = outputs[0] + logits = self.lm_head(hidden_states) + logits = logits.float() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + shift_logits = shift_logits.view(-1, self.config.vocab_size) + shift_labels = shift_labels.view(-1) + # Enable model parallelism + shift_labels = shift_labels.to(shift_logits.device) + loss = loss_fct(shift_logits, shift_labels) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + ): + if past_key_values: + input_ids = input_ids[:, -1:] + + position_ids = kwargs.get("position_ids", None) + if attention_mask is not None and position_ids is None: + # create position_ids on the fly for batch generation + position_ids = attention_mask.long().cumsum(-1) - 1 + position_ids.masked_fill_(attention_mask == 0, 1) + if past_key_values: + position_ids = position_ids[:, -1].unsqueeze(-1) + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + model_inputs.update( + { + "position_ids": position_ids, + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += ( + tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past), + ) + return reordered_past diff --git a/baselines/agzo/zo-bench/modeling_opt.py b/baselines/agzo/zo-bench/modeling_opt.py new file mode 100644 index 0000000..3079a49 --- /dev/null +++ b/baselines/agzo/zo-bench/modeling_opt.py @@ -0,0 +1,1268 @@ +# For head-tuning, we use torch.no_grad() for all the forward functions except the lm head +# The following code is mostly copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/opt/modeling_opt.py +# Search "MeZO added" to find we we added + +# coding=utf-8 +# Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" PyTorch OPT model.""" +import random +from typing import List, Optional, Tuple, Union + +import torch +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +from transformers.activations import ACT2FN +from transformers.modeling_outputs import ( + BaseModelOutputWithPast, + CausalLMOutputWithPast, + QuestionAnsweringModelOutput, + SequenceClassifierOutputWithPast, +) +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import ( + add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, + logging, + replace_return_docstrings, +) +from transformers.models.opt.configuration_opt import OPTConfig + + +logger = logging.get_logger(__name__) + +_CHECKPOINT_FOR_DOC = "facebook/opt-350m" +_CONFIG_FOR_DOC = "OPTConfig" + +# Base model docstring +_EXPECTED_OUTPUT_SHAPE = [1, 8, 1024] + +# SequenceClassification docstring +_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ArthurZ/opt-350m-dummy-sc" +_SEQ_CLASS_EXPECTED_LOSS = 1.71 +_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_0'" + +OPT_PRETRAINED_MODEL_ARCHIVE_LIST = [ + "facebook/opt-125m", + "facebook/opt-350m", + "facebook/opt-1.3b", + "facebook/opt-2.7b", + "facebook/opt-6.7b", + "facebook/opt-13b", + "facebook/opt-30b", + # See all OPT models at https://huggingface.co/models?filter=opt +] + + +# Copied from transformers.models.bart.modeling_bart._make_causal_mask +def _make_causal_mask( + input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 +): + """ + Make causal mask used for bi-directional self-attention. + """ + bsz, tgt_len = input_ids_shape + mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device) + mask_cond = torch.arange(mask.size(-1), device=device) + mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) + mask = mask.to(dtype) + + if past_key_values_length > 0: + mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) + return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) + + +def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + bsz, src_len = mask.size() + tgt_len = tgt_len if tgt_len is not None else src_len + + expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) + + inverted_mask = 1.0 - expanded_mask + + return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) + + +class OPTLearnedPositionalEmbedding(nn.Embedding): + """ + This module learns positional embeddings up to a fixed maximum size. + """ + + def __init__(self, num_embeddings: int, embedding_dim: int): + # OPT is set up so that if padding_idx is specified then offset the embedding ids by 2 + # and adjust num_embeddings appropriately. Other models don't have this hack + self.offset = 2 + super().__init__(num_embeddings + self.offset, embedding_dim) + + def forward(self, attention_mask: torch.LongTensor, past_key_values_length: int = 0): + """`input_ids_shape` is expected to be [bsz x seqlen].""" + attention_mask = attention_mask.long() + + # create positions depending on attention_mask + positions = (torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask).long() - 1 + + # cut positions if `past_key_values_length` is > 0 + positions = positions[:, past_key_values_length:] + + return super().forward(positions + self.offset) + + +class OPTAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__( + self, + embed_dim: int, + num_heads: int, + dropout: float = 0.0, + is_decoder: bool = False, + bias: bool = True, + ): + super().__init__() + self.embed_dim = embed_dim + self.num_heads = num_heads + self.dropout = dropout + self.head_dim = embed_dim // num_heads + + if (self.head_dim * num_heads) != self.embed_dim: + raise ValueError( + f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" + f" and `num_heads`: {num_heads})." + ) + self.scaling = self.head_dim**-0.5 + self.is_decoder = is_decoder + + self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def forward( + self, + hidden_states: torch.Tensor, + key_value_states: Optional[torch.Tensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + """Input shape: Batch x Time x Channel""" + + # if key_value_states are provided this layer is used as a cross-attention layer + # for the decoder + is_cross_attention = key_value_states is not None + + bsz, tgt_len, _ = hidden_states.size() + + # get query proj + query_states = self.q_proj(hidden_states) * self.scaling + # get key, value proj + if is_cross_attention and past_key_value is not None: + # reuse k,v, cross_attentions + key_states = past_key_value[0] + value_states = past_key_value[1] + elif is_cross_attention: + # cross_attentions + key_states = self._shape(self.k_proj(key_value_states), -1, bsz) + value_states = self._shape(self.v_proj(key_value_states), -1, bsz) + elif past_key_value is not None: + # reuse k, v, self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + else: + # self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + + if self.is_decoder: + # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. + # Further calls to cross_attention layer can then reuse all cross-attention + # key/value_states (first "if" case) + # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of + # all previous decoder key/value_states. Further calls to uni-directional self-attention + # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) + # if encoder bi-directional self-attention `past_key_value` is always `None` + past_key_value = (key_states, value_states) + + proj_shape = (bsz * self.num_heads, -1, self.head_dim) + query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape) + key_states = key_states.view(*proj_shape) + value_states = value_states.view(*proj_shape) + + src_len = key_states.size(1) + attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) + + if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len): + raise ValueError( + f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, tgt_len, src_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" + ) + attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask + attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437 + if attn_weights.dtype == torch.float16: + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16) + else: + attn_weights = nn.functional.softmax(attn_weights, dim=-1) + + if layer_head_mask is not None: + if layer_head_mask.size() != (self.num_heads,): + raise ValueError( + f"Head mask for a single layer should be of size {(self.num_heads,)}, but is" + f" {layer_head_mask.size()}" + ) + attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + if output_attentions: + # this operation is a bit awkward, but it's required to + # make sure that attn_weights keeps its gradient. + # In order to do so, attn_weights have to be reshaped + # twice and have to be reused in the following + attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len) + else: + attn_weights_reshaped = None + + attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) + + attn_output = torch.bmm(attn_probs, value_states) + + if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) + attn_output = attn_output.transpose(1, 2) + + # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be + # partitioned aross GPUs when using tensor-parallelism. + attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) + + attn_output = self.out_proj(attn_output) + + return attn_output, attn_weights_reshaped, past_key_value + + +class OPTDecoderLayer(nn.Module): + def __init__(self, config: OPTConfig): + super().__init__() + self.embed_dim = config.hidden_size + self.self_attn = OPTAttention( + embed_dim=self.embed_dim, + num_heads=config.num_attention_heads, + dropout=config.attention_dropout, + is_decoder=True, + bias=config.enable_bias, + ) + self.do_layer_norm_before = config.do_layer_norm_before + self.dropout = config.dropout + self.activation_fn = ACT2FN[config.activation_function] + + self.self_attn_layer_norm = nn.LayerNorm( + self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine + ) + self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim, bias=config.enable_bias) + self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim, bias=config.enable_bias) + self.final_layer_norm = nn.LayerNorm(self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size + `(encoder_attention_heads,)`. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + past_key_value=past_key_value, + attention_mask=attention_mask, + layer_head_mask=layer_head_mask, + output_attentions=output_attentions, + ) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + hidden_states = residual + hidden_states + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Fully Connected + hidden_states_shape = hidden_states.shape + hidden_states = hidden_states.reshape(-1, hidden_states.size(-1)) + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + hidden_states = self.fc1(hidden_states) + hidden_states = self.activation_fn(hidden_states) + + hidden_states = self.fc2(hidden_states) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + + hidden_states = (residual + hidden_states).view(hidden_states_shape) + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +OPT_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`OPTConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTPreTrainedModel(PreTrainedModel): + config_class = OPTConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["OPTDecoderLayer"] + _keys_to_ignore_on_load_unexpected = [r"decoder\.version"] + + def _init_weights(self, module): + std = self.config.init_std + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, (OPTDecoder)): + module.gradient_checkpointing = value + + +OPT_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape + `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape + `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +class OPTDecoder(OPTPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`] + + Args: + config: OPTConfig + """ + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.dropout = config.dropout + self.layerdrop = config.layerdrop + self.padding_idx = config.pad_token_id + self.max_target_positions = config.max_position_embeddings + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.word_embed_proj_dim, self.padding_idx) + self.embed_positions = OPTLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size) + + if config.word_embed_proj_dim != config.hidden_size: + self.project_out = nn.Linear(config.hidden_size, config.word_embed_proj_dim, bias=False) + else: + self.project_out = None + + if config.word_embed_proj_dim != config.hidden_size: + self.project_in = nn.Linear(config.word_embed_proj_dim, config.hidden_size, bias=False) + else: + self.project_in = None + + # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility + # with checkpoints that have been fine-tuned before transformers v4.20.1 + # see https://github.com/facebookresearch/metaseq/pull/164 + if config.do_layer_norm_before and not config._remove_final_layer_norm: + self.final_layer_norm = nn.LayerNorm( + config.hidden_size, elementwise_affine=config.layer_norm_elementwise_affine + ) + else: + self.final_layer_norm = None + + self.layers = nn.ModuleList([OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)]) + + self.gradient_checkpointing = False + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask + def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): + # create causal mask + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + combined_attention_mask = None + if input_shape[-1] > 1: + combined_attention_mask = _make_causal_mask( + input_shape, + inputs_embeds.dtype, + device=inputs_embeds.device, + past_key_values_length=past_key_values_length, + ) + + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( + inputs_embeds.device + ) + combined_attention_mask = ( + expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask + ) + + return combined_attention_mask + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + """ + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + batch_size, seq_length = input_shape + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + # required mask seq length can be calculated via length of past + mask_seq_length = past_key_values_length + seq_length + + # embed positions + if attention_mask is None: + attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device) + causal_attention_mask = self._prepare_decoder_attention_mask( + attention_mask, input_shape, inputs_embeds, past_key_values_length + ) + pos_embeds = self.embed_positions(attention_mask, past_key_values_length) + + if self.project_in is not None: + inputs_embeds = self.project_in(inputs_embeds) + + hidden_states = inputs_embeds + pos_embeds + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + # check if head_mask has a correct number of layers specified if desired + for attn_mask, mask_name in zip([head_mask], ["head_mask"]): + if attn_mask is not None: + if attn_mask.size()[0] != (len(self.layers)): + raise ValueError( + f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" + f" {head_mask.size()[0]}." + ) + + for idx, decoder_layer in enumerate(self.layers): + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + causal_attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=causal_attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + if self.final_layer_norm is not None: + hidden_states = self.final_layer_norm(hidden_states) + + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTModel(OPTPreTrainedModel): + def __init__(self, config: OPTConfig): + super().__init__(config) + self.decoder = OPTDecoder(config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.decoder.embed_tokens = value + + def get_decoder(self): + return self.decoder + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=BaseModelOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_EXPECTED_OUTPUT_SHAPE, + ) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn) + decoder_outputs = self.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + if not return_dict: + return decoder_outputs + + return BaseModelOutputWithPast( + last_hidden_state=decoder_outputs.last_hidden_state, + past_key_values=decoder_outputs.past_key_values, + hidden_states=decoder_outputs.hidden_states, + attentions=decoder_outputs.attentions, + ) + + +class OPTForCausalLM(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = OPTModel(config) + + # the lm_head weight is automatically tied to the embed tokens weight + self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model.decoder = decoder + + def get_decoder(self): + return self.model.decoder + + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional + tensors are only required when the model is used as a decoder in a Sequence to Sequence model. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, OPTForCausalLM + + >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m") + >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") + + >>> prompt = "Hey, are you consciours? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + # MeZO added: torch.no_grad + with torch.no_grad(): + outputs = self.model.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + logits = self.lm_head(outputs[0]).contiguous() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + ): + if past_key_values: + input_ids = input_ids[:, -1:] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + model_inputs.update( + { + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) + return reordered_past + + +@add_start_docstrings( + """ + The OPT Model transformer with a sequence classification head on top (linear layer). + + [`OPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + OPT_START_DOCSTRING, +) +class OPTForSequenceClassification(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.num_labels = config.num_labels + self.model = OPTModel(config) + self.score = nn.Linear(config.word_embed_proj_dim, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION, + output_type=SequenceClassifierOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_SEQ_CLASS_EXPECTED_OUTPUT, + expected_loss=_SEQ_CLASS_EXPECTED_LOSS, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size, sequence_length = input_ids.shape[:2] + else: + batch_size, sequence_length = inputs_embeds.shape[:2] + + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device) + else: + sequence_lengths = -1 + logger.warning( + f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " + "unexpected if using padding tokens in conjunction with `inputs_embeds.`" + ) + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + +@add_start_docstrings( + """ + The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD + (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + """, + OPT_START_DOCSTRING, +) +class OPTForQuestionAnswering(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.model = OPTModel(config) + self.qa_outputs = nn.Linear(config.word_embed_proj_dim, 2) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + start_positions: Optional[torch.LongTensor] = None, + end_positions: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, QuestionAnsweringModelOutput]: + r""" + start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, OPTForQuestionAnswering + >>> import torch + + >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT + >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") + + >>> # note: we are loading a OPTForQuestionAnswering from the hub here, + >>> # so the head will be randomly initialized, hence the predictions will be random + >>> model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m") + + >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" + + >>> inputs = tokenizer(question, text, return_tensors="pt") + >>> with torch.no_grad(): + ... outputs = model(**inputs) + + >>> answer_start_index = outputs.start_logits.argmax() + >>> answer_end_index = outputs.end_logits.argmax() + + >>> answer_offset = len(tokenizer(question)[0]) + + >>> predict_answer_tokens = inputs.input_ids[ + ... 0, answer_offset + answer_start_index : answer_offset + answer_end_index + 1 + ... ] + >>> predicted = tokenizer.decode(predict_answer_tokens) + >>> predicted + ' a nice puppet' + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + + logits = self.qa_outputs(hidden_states) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + transformer_outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value diff --git a/baselines/agzo/zo-bench/npu_compat.py b/baselines/agzo/zo-bench/npu_compat.py new file mode 100644 index 0000000..27b481f --- /dev/null +++ b/baselines/agzo/zo-bench/npu_compat.py @@ -0,0 +1,488 @@ +"""用于统一 NPU/CUDA 调用的兼容性辅助函数。 + +该模块提供了一组在仓库中复用的轻量函数,优先使用 `torch.npu` 或 +`torch_npu`(如果可用)的 NPU 能力;若无则回退到 CUDA;再无则使用 CPU。 + +仅提供小而明确的辅助,避免对现有代码做大规模侵入式改动。 +""" +from __future__ import annotations +import contextlib +import typing +import torch +import importlib +import warnings +import os + + +_HAS_TORCH_NPU = False +try: + # 部分 NPU 发行版直接提供 `torch.npu`,或通过独立的 `torch_npu` 包暴露接口。 + if hasattr(torch, "npu"): + _HAS_TORCH_NPU = True + else: + # 在导入 torch_npu 时屏蔽常见的冗余告警 + with warnings.catch_warnings(): + warnings.filterwarnings( + "ignore", + category=ImportWarning, + module=r"torch_npu\.contrib\.transfer_to_npu", + ) + warnings.filterwarnings( + "ignore", + category=RuntimeWarning, + message=r".*torch\.jit\.script.*", + ) + importlib.import_module("torch_npu") + _HAS_TORCH_NPU = True +except Exception: + _HAS_TORCH_NPU = False + + +def is_npu_available() -> bool: + """返回 NPU 运行时是否可用。""" + if _HAS_TORCH_NPU and hasattr(torch, "npu"): + try: + return torch.npu.is_available() + except Exception: + return True + return False + +# 返回可用设备数量(优先 NPU) +def device_count() -> int: + if is_npu_available() and hasattr(torch, "npu"): + try: + return torch.npu.device_count() + except Exception: + return 0 + + +# 查询当前设备的可用/总内存,优先 NPU +def mem_get_info() -> typing.Tuple[int, int]: + """返回当前设备的 (free, total) 内存信息(字节)。 + """ + # 若存在 torch.npu 且提供 mem_get_info 风格的接口则优先使用 + if is_npu_available() and hasattr(torch, "npu"): + try: + if hasattr(torch.npu, "mem_get_info"): + return torch.npu.mem_get_info() + except Exception: + pass + + # 尝试 torch_npu 包(许多发行版在此暴露 NPU 辅助接口) + try: + tn = importlib.import_module("torch_npu") + # 常见位置:torch_npu.npu.memory_stats / memory_stats_as_nested_dict + npu_mod = getattr(tn, "npu", None) + # 从统计字典中抽取 free/total 的辅助函数 + def _extract_free_total(stats) -> typing.Optional[typing.Tuple[int, int]]: + # 非字典则直接放弃 + if not isinstance(stats, dict): + return None + # 直接键命中 + if "total" in stats and "free" in stats: + try: + return int(stats["free"]), int(stats["total"]) + except Exception: + pass + # 常见模式:total 与 used/allocated -> free = total - used + if "total" in stats and ("used" in stats or "allocated" in stats): + try: + used = int(stats.get("used", stats.get("allocated"))) + total = int(stats["total"]) + return max(total - used, 0), total + except Exception: + pass + # reserved/allocated 模式 + if "reserved" in stats and "allocated" in stats: + try: + total = int(stats.get("reserved")) + allocated = int(stats.get("allocated")) + return max(total - allocated, 0), total + except Exception: + pass + # 展平嵌套字典并搜索可能的键 + def _walk(d): + for k, v in d.items(): + if isinstance(v, dict): + for sub in _walk(v): + yield sub + else: + yield (k, v) + + flat = dict(_walk(stats)) + # 尝试找到数值候选项 + nums = {k: v for k, v in flat.items() if isinstance(v, (int, float))} + if not nums: + return None + # 启发式:优先包含 'total' 与 'free'/'avail'/'used' 的键 + total_key = None + free_key = None + for k in nums: + lk = k.lower() + if "total" in lk or "reserved" in lk: + total_key = k + break + for k in nums: + lk = k.lower() + if "free" in lk or "avail" in lk or "available" in lk: + free_key = k + break + if total_key and free_key: + try: + return int(nums[free_key]), int(nums[total_key]) + except Exception: + pass + # 回退:若有 total 与任一 allocated/used,则计算 free + if total_key: + for k in nums: + lk = k.lower() + if "used" in lk or "alloc" in lk: + try: + return max(int(nums[total_key]) - int(nums[k]), 0), int(nums[total_key]) + except Exception: + pass + return None + + # 若可用,优先使用 npu.memory_stats + if npu_mod is not None: + try: + if hasattr(npu_mod, "memory_stats"): + stats = npu_mod.memory_stats(device=None) + got = _extract_free_total(stats) + if got: + return got + if hasattr(npu_mod, "memory_stats_as_nested_dict"): + stats = npu_mod.memory_stats_as_nested_dict(device=None) + got = _extract_free_total(stats) + if got: + return got + # 尝试其他辅助接口 + if hasattr(npu_mod, "memory_summary"): + # memory_summary 返回字符串,为安全起见不解析 + pass + except Exception: + pass + + # 最后尝试 torch_npu 顶层的相关辅助 + for name in ["memory_stats", "memory_stats_as_nested_dict", "memory_snapshot", "memory_summary"]: + fn = getattr(tn, name, None) + if callable(fn): + try: + stats = fn() if name != "memory_summary" else None + if stats is not None: + got = _extract_free_total(stats) + if got: + return got + except Exception: + pass + except Exception: + pass + + # NPU/CUDA 内存接口均不可用:返回安全默认值 + try: + import warnings + + warnings.warn("npu_compat.mem_get_info: no NPU mem API found and CUDA unavailable; returning (0,0)") + except Exception: + pass + return (0, 0) + + +# 获取设备的峰值已分配显存(优先 NPU) +def max_memory_allocated(device: typing.Optional[int] = None) -> int: + if is_npu_available() and hasattr(torch, "npu"): + try: + if device is None: + return torch.npu.max_memory_allocated() + return torch.npu.max_memory_allocated(device) + except Exception: + pass + + +# 重置峰值已分配显存统计(优先 NPU) +def reset_max_memory_allocated(device: typing.Optional[int] = None): + if is_npu_available() and hasattr(torch, "npu"): + try: + if device is None: + return torch.npu.reset_max_memory_allocated() + return torch.npu.reset_max_memory_allocated(device) + except Exception: + pass + + +# 重置峰值显存统计(优先 NPU) +def reset_peak_memory_stats(): + if is_npu_available() and hasattr(torch, "npu"): + try: + return torch.npu.reset_peak_memory_stats() + except Exception: + pass + + +# 清理缓存显存(优先 NPU) +def empty_cache(): + if is_npu_available() and hasattr(torch, "npu"): + try: + return torch.npu.empty_cache() + except Exception: + pass + + +# 为所有设备设置随机种子(优先 NPU) +def manual_seed_all(seed: int): + if is_npu_available(): + torch.npu.manual_seed_all(seed) + else: + logging.warning("manual_seed_all: NPU not available, falling back to CUDA if available") + + +# 设备同步(优先 NPU,再到 CUDA) +def synchronize(): + """同步设备;优先 NPU,再到 CUDA,尽力而为。""" + if is_npu_available() and hasattr(torch, "npu"): + try: + if hasattr(torch.npu, "synchronize"): + return torch.npu.synchronize() + except Exception: + pass + + +# 返回自动混合精度上下文应使用的设备类型 +def manual_device_type() -> str: + """返回自动混合精度/上下文优选的设备类型字符串:'npu'|'cpu'。""" + if is_npu_available(): + return "npu" + return "cpu" + + +# 设置当前活动设备(优先 NPU) +def set_device(index: int) -> None: + """按索引选择 NPU 的活动设备。 + + - NPU:优先 `torch.npu.set_device(index)`,若用户已设置 `ASCEND_VISIBLE_DEVICES` 亦尊重。 + - CPU:不执行任何操作。 + + 可在模型创建前的程序启动阶段安全调用。 + """ + try: + if index is None: + return + # Normalize index to int + idx = int(index) + except Exception: + return + + # Prefer NPU if available + if is_npu_available() and hasattr(torch, "npu"): + try: + # If the environment already constrains visible devices, we still set current device + if hasattr(torch.npu, "set_device"): + torch.npu.set_device(idx) + return + except Exception: + pass + # Fallback: some distros may expose set_device under torch_npu.npu + try: + tn = importlib.import_module("torch_npu") + if hasattr(tn, "npu") and hasattr(tn.npu, "set_device"): + tn.npu.set_device(idx) + return + except Exception: + pass + + # CPU: nothing to do + return + + +def safe_set_device(index: typing.Optional[int]) -> int: + """安全设置活动设备索引,并返回最终生效的索引。 + + - 将传入索引规范化为 `int`;若无效则回退为 0。 + - 使用 `device_count()` 对索引进行边界裁剪,避免越界或负值。 + - 调用 `set_device()` 应用设备选择(优先 NPU,回退 CUDA)。 + - 返回最终使用的设备索引。 + """ + try: + idx = int(index) if index is not None else 0 + except Exception: + idx = 0 + try: + visible = device_count() + except Exception: + visible = None + if visible and (idx < 0 or idx >= visible): + idx = 0 + set_device(idx) + return idx,visible + + +# 将张量移动到可用设备(优先 NPU) +def to_device(t: torch.Tensor) -> torch.Tensor: + """若有 NPU 则迁移到 NPU,否则若有 CUDA 则迁移到 CUDA,否则保持不变。""" + if is_npu_available(): + try: + return t.npu() + except Exception: + return t.to("npu") + return t + + +# 获取自动混合精度的 GradScaler(优先 NPU) +def amp_grad_scaler(enabled: bool = True): + """返回可用设备的 AMP GradScaler(优先 NPU)。""" + # 若存在 torch.npu.amp 则优先 + if is_npu_available() and hasattr(torch, "npu") and hasattr(torch, "amp") and hasattr(torch.amp, "GradScaler"): + try: + # Some NPU distributions expose amp under torch.amp + return torch.amp.GradScaler(enabled=enabled) + except Exception: + pass + + +# 根据优选设备类型封装 autocast 上下文 +@contextlib.contextmanager +def autocast(dtype=torch.float16, enabled=True): + """为优选设备类型封装 torch.autocast 的上下文管理器。""" + device_type = manual_device_type() + if device_type == "cpu": + # CPU 不支持或无需 autocast:直接空操作 + yield + else: + # torch.autocast 支持 device_type 字符串 + with torch.autocast(device_type=device_type, dtype=dtype, enabled=enabled): + yield + + +# 设备名称查询(优先 NPU,再到 CUDA) +def get_device_name(index: typing.Optional[int] = None) -> typing.Optional[str]: + """返回指定设备索引的设备名称/芯片型号。 + + - NPU:优先使用 `torch.npu.get_device_name`,回退到 `torch_npu.get_device_name` + 或 `torch_npu.npu.get_device_name`(若可用)。 + - CPU:返回 None。 + """ + try: + idx = int(index) if index is not None else None + except Exception: + idx = None + + if is_npu_available() and hasattr(torch, "npu"): + try: + if hasattr(torch.npu, "get_device_name"): + return str(torch.npu.get_device_name(idx if idx is not None else 0)) + except Exception: + pass + try: + tn = importlib.import_module("torch_npu") + if hasattr(tn, "get_device_name"): + return str(tn.get_device_name(idx if idx is not None else 0)) + if hasattr(tn, "npu") and hasattr(tn.npu, "get_device_name"): + return str(tn.npu.get_device_name(idx if idx is not None else 0)) + except Exception: + pass + + return None + + +def current_device_index() -> typing.Optional[int]: + """返回当前活动设备索引(优先 NPU,再到 CUDA)。若不可用则返回 None。""" + if is_npu_available() and hasattr(torch, "npu"): + try: + if hasattr(torch.npu, "current_device"): + return int(torch.npu.current_device()) + except Exception: + pass + return 0 + return None + + +def get_active_device_info() -> typing.Tuple[typing.Optional[str], typing.Optional[int], typing.Optional[int], typing.Optional[str]]: + """返回当前活跃设备信息 (dev_type, dev_idx, total_gb, device_name)。 + + - dev_type: 'npu' | None(CPU/未知) + - dev_idx: 设备索引(若未知则 0,CPU 则 None) + - total_gb: 设备总显存(GB,若不可得则 None) + - device_name: 设备名称/芯片型号(若不可得则 None) + """ + dev_type: typing.Optional[str] = None + dev_idx: typing.Optional[int] = None + total_gb: typing.Optional[int] = None + device_name: typing.Optional[str] = None + + try: + if is_npu_available(): + dev_type = "npu" + try: + dev_idx = current_device_index() + if dev_idx is None: + dev_idx = 0 + except Exception: + dev_idx = 0 + try: + _, total_b = mem_get_info() + total_gb = int(total_b / 1024 ** 3) if total_b else None + except Exception: + total_gb = None + try: + device_name = get_device_name(dev_idx) + except Exception: + device_name = None + except Exception: + logging.warning("get_active_device_info: failed to get device info", exc_info=True) + + return dev_type, dev_idx, total_gb, device_name + + +def collect_npu_memory_metrics() -> dict: + """收集设备显存指标(优先 NPU,回退 CUDA),返回用于日志的字典。 + + 指标包括: + - npu_mem_free_gb / npu_mem_used_gb / npu_mem_total_gb + - npu_mem_peak_gb(所有设备峰值分配总和) + - 以及可选的 allocated/reserved 当前/峰值(若 torch_npu.memory_stats 可用) + """ + metrics: dict = {} + + # 基础 free/total/used + try: + free_bytes, total_bytes = mem_get_info() + used_bytes = max((total_bytes or 0) - (free_bytes or 0), 0) + if total_bytes: + metrics["npu_mem_free_gb"] = free_bytes / 1024 ** 3 + metrics["npu_mem_used_gb"] = used_bytes / 1024 ** 3 + metrics["npu_mem_total_gb"] = total_bytes / 1024 ** 3 + except Exception: + pass + + # 峰值统计(汇总所有设备) + try: + peak_bytes = 0 + for device_id in range(device_count()): + peak_bytes += max_memory_allocated(device_id) + if peak_bytes: + metrics["npu_mem_peak_gb"] = peak_bytes / 1024 ** 3 + except Exception: + pass + + # 详细统计(若 torch_npu 可用) + try: + tn = importlib.import_module("torch_npu") # 可选依赖 + stats = None + if hasattr(tn, "npu") and hasattr(tn.npu, "memory_stats"): + stats = tn.npu.memory_stats() + elif hasattr(tn, "memory_stats"): + stats = tn.memory_stats() + if isinstance(stats, dict): + current_alloc = stats.get("allocated_bytes.all.current") + peak_alloc = stats.get("allocated_bytes.all.peak") + reserved_alloc = stats.get("reserved_bytes.all.current") + if current_alloc is not None: + metrics["npu_mem_allocated_gb"] = current_alloc / 1024 ** 3 + if peak_alloc is not None: + metrics["npu_mem_allocated_peak_gb"] = peak_alloc / 1024 ** 3 + if reserved_alloc is not None: + metrics["npu_mem_reserved_gb"] = reserved_alloc / 1024 ** 3 + except Exception: + pass + + return metrics diff --git a/baselines/agzo/zo-bench/prefix_tuning.py b/baselines/agzo/zo-bench/prefix_tuning.py new file mode 100644 index 0000000..153884a --- /dev/null +++ b/baselines/agzo/zo-bench/prefix_tuning.py @@ -0,0 +1,213 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import torch +from torch import nn +import npu_compat as npu + + +def find_module(root_module: nn.Module, key: str): + """ + Find a module with a specific name in a Transformer model + From OpenDelta https://github.com/thunlp/OpenDelta + """ + sub_keys = key.split(".") + parent_module = root_module + for sub_key in sub_keys[:-1]: + parent_module = getattr(parent_module, sub_key) + module = getattr(parent_module, sub_keys[-1]) + return parent_module, sub_keys[-1], module + + +def attn_forward_hook(self, *args, **kwargs): + """ + Replace the original attention forward with this to enable prefix + """ + + def _expand_bsz(x, bsz): + x = x.reshape(x.size(0), self.num_heads, -1).transpose(0, + 1) # (num_prefix, hidden) -> (num_head, num_prefix, hidden/num_head) + x = x.unsqueeze(0).expand(bsz, *x.shape) # -> (bsz, num_head, num_prefix, hidden/num_head) + return x + + if "hidden_states" in kwargs: + hidden_states = kwargs["hidden_states"] + else: + hidden_states = args[0] + bsz = hidden_states.size(0) + + if 'past_key_value' not in kwargs or kwargs['past_key_value'] is None: + if self.reparam: + prefix_keys = self.prefix_mlp_keys(self.prefix_input_embeds) + prefix_values = self.prefix_mlp_values(self.prefix_input_embeds) + else: + prefix_keys, prefix_values = self.prefix_keys, self.prefix_values + kwargs['past_key_value'] = (_expand_bsz(prefix_keys, bsz), _expand_bsz(prefix_values, bsz)) + + if 'attention_mask' in kwargs and kwargs['attention_mask'] is not None: + am = kwargs['attention_mask'] + kwargs['attention_mask'] = torch.cat( + [-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1) + elif len(args) > 1: # attention mask is passed via positional argument + am = args[1] + am = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], + dim=-1) + args = (args[0], am) + args[2:] + + return self.original_forward(*args, **kwargs) + + +def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs): + """ + Replace the original "prepare_inputs_for_generation" with this to pass prefix correctly + """ + original_input_len = input_ids.size(-1) + if past_key_values: + input_ids = input_ids[:, -1:] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + if past_key_values is not None: + # Check if we should add extra to attention mask + if past_key_values[0][0].size(2) != attention_mask.size(1) - 1: + num_prefix = past_key_values[0][0].size(2) - (attention_mask.size(1) - 1) + attention_mask = torch.cat([torch.ones((attention_mask.size(0), num_prefix), dtype=attention_mask.dtype, + device=attention_mask.device), attention_mask], dim=-1) + + model_inputs.update( + { + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + +class PrefixTuning: + + def __init__(self, model, num_prefix, reparam=True, embed_dim=512, mid_dim=512, float16=False, + init_by_real_act=False): + """ + Inputs: + num_prefix: number of prefix tokens + reparam: use reparameterization trick (not used in MeZO) + embed_dim, mid_dim: hyperparameters for reparameterization trick (not used in MeZO) + float15: whether the model parameters are float15 + init_by_real_act: init prefix tokens by real activations + """ + + self.model = model + self.num_prefix = num_prefix + self.hidden_dim = model.config.hidden_size + self.float16 = float16 + + # Reparameterization + self.reparam = reparam + self.embed_dim = embed_dim + self.mid_dim = mid_dim + + input_embeds = None # For reparameterization + if model.config.model_type == "opt": + attention_name = "attn" + first_layer_name = "layers.0" + layer_name = "layers." + elif model.config.model_type == "roberta": + attention_name = "attention" + first_layer_name = "layer.0" + layer_name = "layer." + elif model.config.model_type in ["llama", "mistral"]: + attention_name = "self_attn" + first_layer_name = "layers.0" + layer_name = "layers." + else: + raise NotImplementedError + + if init_by_real_act: + # Initialize prefix with real words' activations + assert not reparam + + # Randomly sample input tokens + input_tokens = npu.to_device(torch.randint(low=0, high=model.config.vocab_size, size=(1, num_prefix), + dtype=torch.long)) + if model.config.model_type in ["opt", "llama", "mistral"]: + with torch.no_grad(): + # Get the real activations + real_key_values = model(input_ids=input_tokens, use_cache=True).past_key_values + else: + raise NotImplementedError + + # Insert prefix + for key, _ in model.named_modules(): + if key[-len(attention_name):] == attention_name: + layer_id = int(key.split(layer_name)[1].split(".")[0]) + logger.info(f"Inject prefix to: {key}") + _, _, attn = find_module(model, key) + + # Replace the old forward functions + attn.original_forward = attn.forward + attn.forward = attn_forward_hook.__get__(attn, type(attn)) + if not hasattr(attn, "num_heads"): + attn.num_heads = model.config.num_attention_heads + first = first_layer_name in key + self.add_prefix(attn, first=first, input_embeds=input_embeds) + + if first and self.reparam: + input_embeds = attn.prefix_input_embeds + if init_by_real_act: + logger.info(f"Reinitialize with actual activation: {key} (layer {layer_id})") + keys = real_key_values[layer_id][0].squeeze(0).transpose(0, 1).reshape(num_prefix, -1) + values = real_key_values[layer_id][1].squeeze(0).transpose(0, 1).reshape(num_prefix, -1) + attn.prefix_keys.data = keys.to(attn.prefix_keys.data.device) + attn.prefix_values.data = values.to(attn.prefix_values.data.device) + + # Freeze non-prefix parameters + for n, p in model.named_parameters(): + if "prefix" not in n: + p.requires_grad = False + + # Replace the old prepare_inputs_for_generation function + model.prepare_inputs_for_generation = prepare_inputs_for_generation.__get__(model, type(model)) + + def add_prefix(self, module, first, input_embeds=None): + device = module.k_proj.weight.data.device + module.num_prefix = self.num_prefix + module.reparam = self.reparam + if self.reparam: + if first: + # For the first layer we inject the embeddings + logger.info("For prefix+reparameterization, inject the embeddings in the first layer.") + module.prefix_input_embeds = nn.Parameter( + torch.randn(self.num_prefix, self.embed_dim, device=device, dtype=self.model.dtype), + requires_grad=True) + else: + assert input_embeds is not None + module.prefix_input_embeds = input_embeds + module.prefix_mlp_keys = nn.Sequential( + nn.Linear(self.embed_dim, self.mid_dim), + nn.Tanh(), + nn.Linear(self.mid_dim, self.hidden_dim) + ).to(device) + module.prefix_mlp_values = nn.Sequential( + nn.Linear(self.embed_dim, self.mid_dim), + nn.Tanh(), + nn.Linear(self.mid_dim, self.hidden_dim) + ).to(device) + if self.float16: + module.prefix_mlp_keys = module.prefix_mlp_keys.half() + module.prefix_mlp_values = module.prefix_mlp_values.half() + else: + module.prefix_keys = nn.Parameter( + torch.randn(self.num_prefix, self.hidden_dim, device=device, dtype=self.model.dtype), + requires_grad=True) + module.prefix_values = nn.Parameter( + torch.randn(self.num_prefix, self.hidden_dim, device=device, dtype=self.model.dtype), + requires_grad=True) diff --git a/baselines/agzo/zo-bench/prompt_tuning.py b/baselines/agzo/zo-bench/prompt_tuning.py new file mode 100644 index 0000000..d4e468a --- /dev/null +++ b/baselines/agzo/zo-bench/prompt_tuning.py @@ -0,0 +1,218 @@ +import logging +from functools import partial +from typing import Optional, Callable + +import torch +from torch import nn +from transformers import PreTrainedModel + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +class PromptEmbedding(nn.Module): + def __init__( + self, + num_virtual_tokens: int, + token_dim: int, + init_by_real_text: bool, + word_embeddings: Optional[nn.Module] = None, + vocab_size: Optional[int] = None, + ): + super().__init__() + self.num_virtual_tokens = num_virtual_tokens + + self.embedding = torch.nn.Embedding(num_virtual_tokens, token_dim) + if init_by_real_text: + init_token_ids = torch.randint( + low=0, high=vocab_size, + size=(num_virtual_tokens,), dtype=torch.long + ).to(word_embeddings.weight.device) + + word_embedding_weights = word_embeddings(init_token_ids).detach().clone() + word_embedding_weights = word_embedding_weights.to(torch.float32) + self.embedding.weight = nn.Parameter(word_embedding_weights) + + def forward(self, indices): + # Just get embeddings + prompt_embeddings = self.embedding(indices) + return prompt_embeddings + + +def _get_batch_size(input_ids: Optional[torch.Tensor], inputs_embeds: Optional[torch.Tensor]) -> int: + if (input_ids is None) and (inputs_embeds is None): + raise ValueError("You have to provide either input_ids or inputs_embeds") + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + return batch_size + + +def _model_forward_hook( + self, + embedding_module: Callable, + embedding_module_device_refer, + hide_virtual_token_logits: bool, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + **kwargs, +): + batch_size = _get_batch_size(input_ids, inputs_embeds) + num_virtual_tokens = self.prompt_encoder.num_virtual_tokens + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + if kwargs.get("position_ids", None) is not None: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if labels is not None: + if len(labels.shape) == 1: + # if sequence classification task, labels do not have to be padded + kwargs["labels"] = labels + elif len(labels.shape) == 2: + # suppose to be language modeling task, labels have to be padded with -100 + kwargs["labels"] = torch.cat( + ( + -100 * torch.ones(batch_size, num_virtual_tokens).to(labels.device).long(), + labels, + ), + dim=1, + ) + else: + raise NotImplementedError("Not implemented for labels with shape {}".format(labels.shape)) + + if kwargs.get("token_type_ids", None) is not None: + kwargs["token_type_ids"] = torch.cat( + ( + torch.zeros(batch_size, num_virtual_tokens).to(kwargs["token_type_ids"].device), + kwargs["token_type_ids"], + ), + dim=1, + ).long() + + if kwargs.get("mask_pos", None) is not None: + kwargs["mask_pos"] = num_virtual_tokens + kwargs["mask_pos"] + + input_device = input_ids.device if input_ids is not None else inputs_embeds.device + if inputs_embeds is None: + inputs_embeds = embedding_module(input_ids.to(embedding_module_device_refer.device)) + inputs_embeds = inputs_embeds.to(input_device) + prompts = torch.arange(num_virtual_tokens).unsqueeze(0).expand(batch_size, -1).to( + self.prompt_encoder.embedding.weight.device) + prompts = self.prompt_encoder(prompts).to(dtype=inputs_embeds.dtype, device=input_device) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + + outputs = self.prompt_tuning_original_forward(inputs_embeds=inputs_embeds, **kwargs) + if hide_virtual_token_logits and hasattr(outputs, "logits"): + outputs.logits = outputs.logits[..., num_virtual_tokens:, :] + return outputs + + +class PromptTuning: + + def __init__( + self, + model: PreTrainedModel, + num_virtual_tokens: int, + init_by_real_tokens: Optional[bool] = False, + hide_virtual_token_logits: Optional[bool] = True, + ): + """ + Prompt tuning model initializer. + + Parameters + ---------- + model: PreTrainedModel, required + The model to be tuned. + num_virtual_tokens: int, required + The number of virtual tokens to be added. + init_by_real_tokens: bool, optional, default=False + Whether to initialize the virtual tokens by real tokens. + """ + hidden_dim = model.config.hidden_size + + if model.config.model_type == "opt": + embedding_module = model.get_input_embeddings() + embedding_module_device_refer = embedding_module.weight + elif model.config.model_type == "roberta": + if hasattr(model, "roberta"): # is RoBERTaForMaskedLM etc. + embedding_module = partial(model.roberta.embeddings, past_key_values_length=num_virtual_tokens) + embedding_module_device_refer = model.roberta.embeddings.word_embeddings.weight + elif hasattr(model, "embeddings"): # is RoBERTa base model + embedding_module = partial(model.embeddings, past_key_values_length=num_virtual_tokens) + embedding_module_device_refer = model.embeddings.word_embeddings.weight + else: + raise ValueError(f"Cannot find embedding module in {model.__class__.__name__}") + elif model.config.model_type in ["llama", "mistral"]: + embedding_module = model.get_input_embeddings() + embedding_module_device_refer = embedding_module.weight + else: + raise NotImplementedError + + model.prompt_encoder = PromptEmbedding( + num_virtual_tokens, hidden_dim, init_by_real_tokens, + model.get_input_embeddings(), model.config.vocab_size + ) + model.prompt_tuning_original_forward = model.forward + + if not hasattr(embedding_module_device_refer, "device"): + raise ValueError(f"Cannot find device attribute in {embedding_module_device_refer.__class__.__name__}") + + forward_hook_kwargs = { + "embedding_module": embedding_module, + "embedding_module_device_refer": embedding_module_device_refer, + "hide_virtual_token_logits": hide_virtual_token_logits, + } + model.forward = partial( + _model_forward_hook.__get__(model, type(model)), + **forward_hook_kwargs + ) + + for n, p in model.named_parameters(): + if "prompt_encoder" not in n: + p.requires_grad = False + + +def test_roberta(): + from transformers import AutoTokenizer, RobertaModel + model = RobertaModel.from_pretrained("roberta-base") + tokenizer = AutoTokenizer.from_pretrained("roberta-base") + + PromptTuning(model, num_virtual_tokens=5, init_by_real_tokens=True) + + inputs = tokenizer("in heissem Liebesstreben", return_tensors="pt") + outputs = model(**inputs) + + +def test_opt(): + from transformers import AutoTokenizer, OPTModel + model = OPTModel.from_pretrained("facebook/opt-125m") + tokenizer = AutoTokenizer.from_pretrained("facebook/opt-125m") + + PromptTuning(model, num_virtual_tokens=5, init_by_real_tokens=True) + + inputs = tokenizer("werd ich entschweben", return_tensors="pt") + outputs = model(**inputs) + + +if __name__ == "__main__": + test_roberta() + test_opt() diff --git a/baselines/agzo/zo-bench/run.py b/baselines/agzo/zo-bench/run.py new file mode 100644 index 0000000..0d2e62c --- /dev/null +++ b/baselines/agzo/zo-bench/run.py @@ -0,0 +1,939 @@ +import warnings +# Suppress NPU import-time warnings before any imports that may trigger them +# 1) Hide the long ImportWarning from torch_npu.contrib.transfer_to_npu +warnings.filterwarnings("ignore", category=ImportWarning, message=".*torch_npu.*") +# 2) Hide RuntimeWarning regarding torch.jit being disabled by transfer_to_npu +warnings.filterwarnings( + "ignore", + category=RuntimeWarning, + message=r".*torch\.jit\.script.*", +) + +import argparse +import os +import random + +import wandb +import torch +from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP +from torch.utils.data import Dataset +from tqdm import tqdm +import types +import sys as _sys +from transformers import ( + AutoConfig, + AutoTokenizer, + AutoModelForCausalLM, + AutoModel, + HfArgumentParser, + TrainingArguments, + DataCollatorForTokenClassification +) + +from metrics import calculate_metric +from modeling_mistral import ( + MistralForCausalLM, + MistralConfig +) +from tasks import get_task +from trainer import OurTrainer +from utils import * +# NPU/CUDA compat helpers +import npu_compat as DeviceLoader + + +os.environ["TRANSFORMERS_CACHE"] = "./cache" + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +# (warnings filters are configured at the very top to catch import-time emissions) + +def _ensure_transformers_masking_utils(): + """Provide a shim for `transformers.masking_utils.create_causal_mask` when absent. + + Some external models (e.g., ModelScope Pangu Embedded) import + `transformers.masking_utils.create_causal_mask`. Newer Transformers versions + may not expose this module, causing ModuleNotFoundError. We inject a minimal + compatible implementation at runtime. + """ + try: + import transformers.masking_utils # type: ignore + return + except Exception: + pass + try: + import torch + mod = types.ModuleType("transformers.masking_utils") + + def create_causal_mask(input_ids_shape=None, dtype=torch.float32, device=None, past_key_values_length=0, *args, **kwargs): + # Support both signatures: (input_shape, dtype, past_len) or (bsz, tgt_len,...) + try: + if input_ids_shape is None: + return None + if isinstance(input_ids_shape, (tuple, list)): + if len(input_ids_shape) >= 2: + bsz, tgt_len = int(input_ids_shape[0]), int(input_ids_shape[1]) + else: + # fallback assume (tgt_len,) + bsz, tgt_len = 1, int(input_ids_shape[0]) + else: + # unknown, fallback to scalar length + bsz, tgt_len = 1, int(input_ids_shape) + except Exception: + bsz, tgt_len = 1, 1 + + dev = device if device is not None else (torch.npu.current_device() if hasattr(torch, "npu") and hasattr(torch.npu, "current_device") else (torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu"))) + # Build upper-triangular mask: allow current and past positions, mask future with -inf + attn_shape = (bsz, 1, tgt_len, tgt_len + int(past_key_values_length)) + mask = torch.zeros(attn_shape, dtype=dtype, device=dev) + # Positions to mask (future): indices where j > i + past + future = torch.triu(torch.ones((tgt_len, tgt_len + int(past_key_values_length)), device=dev), diagonal=1 + int(past_key_values_length)) + future = future.bool() + mask[:, :, :, :] = mask[:, :, :, :].masked_fill(future.expand(bsz, 1, tgt_len, tgt_len + int(past_key_values_length)), float("-inf")) + return mask + + mod.create_causal_mask = create_causal_mask + # Register under sys.modules so import works for remote code + _sys.modules["transformers.masking_utils"] = mod + logger.info("Injected shim for transformers.masking_utils.create_causal_mask") + except Exception as e: + logger.warning(f"Failed to inject masking_utils shim: {e}") + + +try: + AutoConfig.register("mistral", MistralConfig) +except ValueError: + pass + +try: + AutoModelForCausalLM.register(MistralConfig, MistralForCausalLM) +except ValueError: + pass + + +@dataclass +class OurArguments(TrainingArguments): + # dataset and sampling strategy + task_name: str = "SST2" # task name should match the string before Dataset in the Dataset class name. We support the following task_name: SST2, RTE, CB, BoolQ, WSC, WIC, MultiRC, Copa, ReCoRD, SQuAD, DROP + + # Number of examples + num_train: int = 0 # ICL mode: number of demonstrations; training mode: number of training samples + num_dev: int = None # (only enabled with training) number of development samples + num_eval: int = None # number of evaluation samples + num_train_sets: int = None # how many sets of training samples/demos to sample; if None and train_set_seed is None, then we will sample one set for each evaluation sample + train_set_seed: int = 0 # designated seed to sample training samples/demos + result_file: str = None # file name for saving performance; if None, then use the task name, model name, and config + + # Model loading + model_name: str = "FreedomIntelligence/openPangu-Embedded-1B" # HuggingFace model name + load_float16: bool = False # load model parameters as float16 + load_bfloat16: bool = True # load model parameters as bfloat16 + load_int8: bool = False # load model parameters as int8 + max_length: int = 2048 # max length the model can take + no_auto_device: bool = False # do not load model by auto device; should turn this on when using FSDP + + # Calibration + sfc: bool = False # whether to use SFC calibration + icl_sfc: bool = False # whether to use SFC calibration for ICL samples + + template_ver: int = 0 # template. For some tasks (SST2, RTE, Copa), we add template ver=1 as the empty template. + + # Training + trainer: str = "none" + ## options + ## - none: no training -- for zero-shot or in-context learning (ICL) + ## - regular: regular huggingface trainer -- for fine-tuning + ## - zo_sgd: zeroth-order SGD (MeZO) training + ## - zo_conserv: zeroth-order SGD conservative training + ## - zo_adam: zeroth-order Adam training + ## - zo_sign_opt: zeroth-order sign sgd training + ## - agzo: activation-guided zeroth-order training # AGZO: 新增trainer选项 + ## - lozo: low-rank zeroth-order training with adjustable rank r # LOZO: 新增trainer选项 + ## - forward_grad: forward gradient + optimizer: str = "adamw" + ## options + ## - sgd + ## - adam + ## - adamw # this is huggingface default + only_train_option: bool = True # whether to only train the option part of the input + train_as_classification: bool = False # take the log likelihood of all options and train as classification + momentum: float = 0.0 # only work for SGD optimizer + + # MeZO + zo_eps: float = 1e-3 # eps in MeZO + perturbation_mode: str = "two_side" + q: int = 1 # number of Gaussian samples for zeroth-order trainers + + # Prefix tuning + prefix_tuning: bool = False # whether to use prefix tuning + num_prefix: int = 5 # number of prefixes to use + no_reparam: bool = True # do not use reparameterization trick + prefix_init_by_real_act: bool = True # initialize prefix by real activations of random words + + # prompt tuning hyperparameters + prompt_tuning: bool = False # whether to use prompt tuning + num_virtual_tokens: int = 10 # number of prompt tokens to use + prompt_init_by_real_tokens: bool = False # whether to sample random tokens from Embedding layer + + # LoRA + lora: bool = False # whether to use LoRA + lora_alpha: int = 16 # alpha in LoRA + lora_r: int = 8 # r in LoRA + + # Generation + sampling: bool = False # whether to use sampling + temperature: float = 1.0 # temperature for generation + num_beams: int = 1 # number of beams for generation + top_k: int = None # top-k for generation + top_p: float = 0.95 # top-p for generation + max_new_tokens: int = 50 # max number of new tokens to generate + eos_token: str = "\n" # end of sentence token + + # Saving + save_model: bool = False # whether to save the model + no_eval: bool = False # whether to skip evaluation + tag: str = "" # saving tag + + # Linear probing + linear_probing: bool = False # whether to do linear probing + lp_early_stopping: bool = False # whether to do early stopping in linear probing + head_tuning: bool = False # head tuning: only tune the LM head + + # Untie emb/lm_head weights + untie_emb: bool = False # untie the embeddings and LM head + + # Display + verbose: bool = False # verbose output + + # Non-diff objective + non_diff: bool = False # use non-differentiable objective (only support F1 for SQuAD for now) + + # Auto saving when interrupted + save_on_interrupt: bool = False # save model when interrupted (useful for long training) + + clean_model_at_end: bool = True # remove everthing at the end. + + # sparse gradient pruning + gradient_sparsity: float = None + sparse_gradient_resample_steps: int = 1 + sparse_gradient_group: str = "layer" + """ + Options + ## - global: global sparsity will assign different sparsity to each layer, based on the pretrained weight magnitude + ## - layer: each layer has the same sparsity + """ + + # module-wise perturbation + module_wise_perturbation: bool = False + perturbed_module_level: str = "transformer-block" + coordinate_perturbation: bool = True # If True, will update weight right after the gradient is computed + """ + Options + ## - transformer-block: perturb one transformer block at a time + ## - mlp-attn: perturb one mlp/attention layer at a time + ## - linear: perturb one linear layer at a time + """ + + # AGZO: power iteration steps for computing activation principal direction + agzo_power_iter_steps: int = 5 + # AGZO: number of guided directions (rank) per layer + agzo_rank: int = 1 + # AGZO: empty CUDA cache every N steps (0=disable) + agzo_empty_cache_steps: int = 1 + # AGZO: debug flag to log per-layer memory usage during basis collection + agzo_debug_memory: bool = False + + # LOZO: rank (r) for low-rank perturbation; r<=min(out_dim,in_dim) + lozo_rank: int = 4 + + # Device selection + npu_device: Optional[int] = 0 # which npu to use + + # Save-best options + save_best: bool = True # whether to save the best model during training + best_metric_name: str = "accuracy" # metric name to compare (default: accuracy) + best_split: str = "val" # prefer validation set (val); fallback to test if no validation set + +def parse_args(): + parser = argparse.ArgumentParser() + parser = HfArgumentParser(OurArguments) + args = parser.parse_args_into_dataclasses()[0] + print(args) + return args + + +def set_seed(seed: int): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.npu.manual_seed_all(seed) + + +class Framework: + + def __init__(self, args, task): + self.args = args + self.task = task + self.model, self.tokenizer = self.load_model() + + def load_model(self): + """ + Load HuggingFace models + """ + model_name = self.args.model_name + + dev_type = None + dev_idx = None + total_gb = None + device_name = None + + # 从 npu_compat 统一获取设备信息 + dev_type, dev_idx, total_gb, device_name = DeviceLoader.get_active_device_info() + + + if self.args.load_float16: + dtype = torch.float16 + elif self.args.load_bfloat16: + dtype = torch.bfloat16 + elif self.args.load_int8: + dtype = torch.int8 + else: + dtype = torch.float32 + # 显示模型以及加载模型的设备 + # Print MODEL and DEVICE on separate, clearly marked lines + if model_name: + logger.info(f"=== MODEL === {model_name}") + if dev_type is not None: + dev_line = f"=== DEVICE === {dev_type}:{dev_idx}" + if total_gb is not None: + dev_line += f" total_mem={total_gb}GB" + if device_name: + dev_line += f" chip={device_name}" + logger.info(dev_line) + + with count_time(f"Loading model with {dtype}"): + free_in_GB = int(DeviceLoader.mem_get_info()[0] / 1024 ** 3) + max_memory_gb = max(1, free_in_GB - 5) + logging.info(f"Free memory per device: {free_in_GB} GB, setting max_memory to {max_memory_gb} GB per device.") + model_name_lower = self.args.model_name.lower() + is_qwen = "qwen" in model_name_lower + is_pangu_emb = "openpangu-embedded" in model_name_lower + + # # If using ModelScope-only model, download snapshot first + # base_model_path = self.args.model_name + # if is_pangu_emb: + # try: + # from modelscope.hub.snapshot_download import snapshot_download + # base_model_path = snapshot_download( + # model_id=self.args.model_name, + # cache_dir=os.path.join(os.path.dirname(__file__), "..", ".modelscope_cache"), + # ) + # logging.info(f"ModelScope snapshot downloaded to: {base_model_path}") + # # Ensure remote code can import masking_utils + # _ensure_transformers_masking_utils() + # except Exception as e: + # print(f"Warning: ModelScope snapshot_download failed: {e}. Fallback to using {self.args.model_name} directly.") + # base_model_path = self.args.model_name + + config_kwargs = {} + if is_pangu_emb or is_qwen: + config_kwargs["trust_remote_code"] = True + config = AutoConfig.from_pretrained(self.args.model_name, **config_kwargs) + else: + config = AutoConfig.from_pretrained(self.args.model_name, **config_kwargs) + + + if self.args.untie_emb: + # Untie embeddings/LM head + logger.warn("Untie embeddings and LM head") + config.tie_word_embeddings = False + if self.args.head_tuning: + if is_qwen or is_pangu_emb: + raise NotImplementedError("Head tuning is not supported for Qwen and Pangumodels yet.") + torch_dtype = torch.float32 + if self.args.load_float16: + torch_dtype = torch.float16 + elif self.args.load_bfloat16: + torch_dtype = torch.bfloat16 + # Head tuning + if "opt" in model_name_lower: + from modeling_opt import OPTForCausalLM + model = OPTForCausalLM.from_pretrained( + self.args.model_name, + config=config, + device_map='auto', + torch_dtype=torch_dtype, + max_memory={i: f'{max_memory_gb}GB' for i in + range(torch.npu.device_count())}, + ) + elif "llama" in model_name_lower: + from modeling_llama import LlamaForCausalLMWithHeadTuning + model = LlamaForCausalLMWithHeadTuning.from_pretrained( + self.args.model_name, + config=config, + device_map='auto', + torch_dtype=torch_dtype, + max_memory={i: f'{max_memory_gb}GB' for i in + range(torch.npu.device_count())}, + ) + elif "mistral" in model_name_lower: + from modeling_mistral import MistralForCausalLMWithHeadTuning + model = MistralForCausalLMWithHeadTuning.from_pretrained( + self.args.model_name, + config=config, + device_map='auto', + torch_dtype=torch_dtype, + max_memory={i: f'{max_memory_gb}GB' for i in + range(torch.npu.device_count())}, + ) + else: + raise NotImplementedError(f"Head tuning is not supported for {self.args.model_name}") + elif self.args.no_auto_device: + # No auto device (use for FSDP) + model = AutoModelForCausalLM.from_pretrained( + self.args.model_name, + config=config, + trust_remote_code=is_qwen or is_pangu_emb, + ) + else: + # Auto device loading + torch_dtype = torch.float32 + if self.args.load_float16: + torch_dtype = torch.float16 + elif self.args.load_bfloat16: + torch_dtype = torch.bfloat16 + model = AutoModelForCausalLM.from_pretrained( + self.args.model_name, + config=config, + device_map='auto' if DeviceLoader.is_npu_available() else None, + torch_dtype=torch_dtype, + max_memory={i: f'{max_memory_gb}GB' for i in range(DeviceLoader.device_count())}, + load_in_8bit=self.args.load_int8, + trust_remote_code=is_qwen or is_pangu_emb, + ) + DeviceLoader.safe_set_device(self.args.npu_device) + model.eval() + + # Load tokenizer + # In mezo, use_fast is set to False. But TypeError will occur when running SQuaD. Setting to be True can fix. + tokenizer_kwargs = {"use_fast": True} + if is_qwen or is_pangu_emb: + tokenizer_kwargs["trust_remote_code"] = True + tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, **tokenizer_kwargs) + + # HF tokenizer bug fix + if "opt" in self.args.model_name: + tokenizer.bos_token_id = 0 + + if ("llama" in self.args.model_name) or ("mistral" in self.args.model_name.lower()): + # LLaMA padding token + tokenizer.pad_token_id = 0 # technically + + if is_qwen: + if tokenizer.pad_token is None and tokenizer.eos_token is not None: + tokenizer.pad_token = tokenizer.eos_token + if tokenizer.pad_token_id is None: + tokenizer.pad_token_id = tokenizer.eos_token_id + + # Prefix tuning/LoRA + if self.args.prefix_tuning: + from prefix_tuning import PrefixTuning + PrefixTuning(model, num_prefix=self.args.num_prefix, reparam=not self.args.no_reparam, + float16=self.args.load_float16, init_by_real_act=self.args.prefix_init_by_real_act) + if self.args.lora: + from lora import LoRA + LoRA(model, r=self.args.lora_r, alpha=self.args.lora_alpha, float16=self.args.load_float16) + + if self.args.prompt_tuning: + from prompt_tuning import PromptTuning + print("Adding Prompt Tuning to model...") + PromptTuning( + model, + num_virtual_tokens=self.args.num_virtual_tokens, + init_by_real_tokens=self.args.prompt_init_by_real_tokens, + hide_virtual_token_logits=True, # a workaround for the other loss/prediction functions + ) + print("Total/Trainable number of parameters: {}/{}".format( + sum(p.numel() for p in model.parameters()), + sum(p.numel() for p in model.parameters() if p.requires_grad), + )) + + if self.args.head_tuning: + if model.config.model_type in ["opt", "llama", "mistral"]: + head_name = "lm_head" if self.args.untie_emb else "embed_tokens" + else: + raise NotImplementedError + for n, p in model.named_parameters(): + if head_name not in n: + p.requires_grad = False + else: + logger.info(f"Only tuning {n}") + + return model, tokenizer + + def forward(self, input_ids, option_len=None, generation=False): + """ + Given input_ids and the length of the option, return the log-likelihood of each token in the option. + For generation tasks, return the generated text. + This function is only for inference + """ + input_ids = torch.tensor([input_ids]).to(self.model.device) + + if generation: + args = self.args + # Autoregressive generation + outputs = self.model.generate(input_ids, do_sample=args.sampling, temperature=args.temperature, + num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, + max_new_tokens=min(args.max_new_tokens, args.max_length - input_ids.size(1)), + num_return_sequences=1, + eos_token_id=[ + self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], + self.tokenizer.eos_token_id], ) + # For generation, directly return the text output + output_text = self.tokenizer.decode(outputs[0][input_ids.size(1):], skip_special_tokens=True).strip() + return output_text + else: + with torch.inference_mode(): + self.model.eval() + logits = self.model(input_ids=input_ids).logits + labels = input_ids[0, 1:] + logits = logits[0, :-1] + log_probs = F.log_softmax(logits, dim=-1) + + selected_log_probs = log_probs[torch.arange(len(labels)).to(labels.device), labels] + selected_log_probs = selected_log_probs.cpu().detach() + # Only return the option (candidate) part + return selected_log_probs[-option_len:] + + def one_step_pred(self, train_samples, eval_sample, verbose=False): + """ + Return the prediction on the eval sample. In ICL, use train_samples as demonstrations + """ + verbose = verbose or self.args.verbose + # if verbose: + # logger.info("========= Example =========") + # logger.info(f"Candidate: {eval_sample.candidates}") + # logger.info(f"Correct candidate: {eval_sample.correct_candidate}") + + # Encode (add prompt and tokenize) the sample; if multiple-choice/classification, encode all candidates (options) + encoded_candidates, option_lens = encode_prompt(self.task, + self.task.get_template(template_version=self.args.template_ver), + train_samples, eval_sample, + self.tokenizer, max_length=self.args.max_length, + generation=self.task.generation, + max_new_tokens=self.args.max_new_tokens) + + # Calibration + if self.args.sfc or self.args.icl_sfc: + sfc_encoded_candidates, sfc_option_lens = encode_prompt(self.task, self.task.get_template( + template_version=self.args.template_ver), train_samples, + eval_sample, self.tokenizer, + max_length=self.args.max_length, sfc=self.args.sfc, + icl_sfc=self.args.icl_sfc, + generation=self.task.generation, + max_new_tokens=self.args.max_new_tokens) + + outputs = [] + if self.task.generation: + # For generation tasks, return the autoregressively-generated text + output_text = self.forward(encoded_candidates[0], generation=True) + # if verbose: + # logger.info("=== Prompt ===") + # logger.info(self.tokenizer.decode(encoded_candidates[0])) + # logger.info(f"Output: {output_text}") + return Prediction(correct_candidate=eval_sample.correct_candidate, predicted_candidate=output_text) + else: + # For classification/multiple-choice, calculate the probabilities of all candidates + for candidate_id, encoded_candidate in enumerate(encoded_candidates): + selected_log_probs = self.forward(encoded_candidate, option_len=option_lens[candidate_id]) + if verbose: + # if candidate_id == 0: + # logger.info("=== Candidate %d ===" % candidate_id) + # logger.info(self.tokenizer.decode(encoded_candidate)) + # else: + # logger.info("=== Candidate %d (without context)===" % candidate_id) + # logger.info(self.tokenizer.decode(encoded_candidate).split(self.task.train_sep)[-1]) + logger.info(f"Log probabilities of the option tokens: {selected_log_probs}") + + if self.args.sfc or self.args.icl_sfc: + sfc_selected_log_probs = self.forward(sfc_encoded_candidates[candidate_id], + option_len=sfc_option_lens[ + candidate_id]) # if verbose: # logger.info("=== Candidate %d (without context) SFC ===" % candidate_id) # logger.info( # self.tokenizer.decode(sfc_encoded_candidates[candidate_id]).split(self.task.train_sep)[-1]) # logger.info(f"Log probabilities of the option tokens: {sfc_selected_log_probs}") + + outputs.append({"log_probs": selected_log_probs, + "sfc_log_probs": sfc_selected_log_probs if self.args.sfc or self.args.icl_sfc else None}) + + if self.args.sfc or self.args.icl_sfc: + # Calibrated probabilities (surface form competition; https://arxiv.org/pdf/2104.08315.pdf) + # log p(candidate | input) = log p_lm(candidate | input) - log p_lm(candidate | sfc prompt) + scores = [x['log_probs'].sum().item() - x['sfc_log_probs'].sum().item() for x in outputs] + else: + # (Default) length-normalized log probabilities + # log p(candidate | input) = log p_lm(candidate | input) / |candidate #tokens| + scores = [x['log_probs'].mean().item() for x in outputs] + + if verbose: + logger.info(f"Prediction scores: {scores}") + + if isinstance(eval_sample.correct_candidate, list): + # For some datasets there are multiple correct answers + correct_candidate_id = [eval_sample.candidates.index(c) for c in eval_sample.correct_candidate] + else: + correct_candidate_id = eval_sample.candidates.index(eval_sample.correct_candidate) + + return Prediction(correct_candidate=correct_candidate_id, predicted_candidate=int(np.argmax(scores))) + + def evaluate(self, train_samples, eval_samples, one_train_set_per_eval_sample=False, description=None): + """ + Evaluate function. + Here, train_samples are used for demonstrations for ICL. + If one_train_set_per_eval_sample is True, then each eval sample has its own training (demonstration) set. + Otherwise, the same training set is used for all eval samples. + """ + if one_train_set_per_eval_sample: + logger.info(f"There are {len(eval_samples)} validation samples and one train set per eval sample") + else: + logger.info(f"There are {len(train_samples)} training samples and {len(eval_samples)} validation samples") + + # Prediction loop + predictions = [] + for eval_id, eval_sample in enumerate(tqdm(eval_samples, desc=description)): + predictions.append( + self.one_step_pred(train_samples[eval_id] if one_train_set_per_eval_sample else train_samples, + eval_sample, verbose=False)) + + # Calculate metrics + metric_name = getattr(self.task, "metric_name", "accuracy") + metrics = {metric_name: calculate_metric(predictions, metric_name)} + return metrics + + def train(self, train_samples, dev_samples, eval_samples): + """ + Training function + if self.num_dev is not None, eval_samples are dev_samples + """ + logger.info(f"Eval sample length is {len(eval_samples)}") + # Set tokenizer to left padding (so that all the options are right aligned) + self.tokenizer.padding_side = "left" + + class HFDataset(Dataset): + + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __getitem__(self, idx): + return self.data[idx] + + def _convert(samples): + """ + Convert samples to HF-compatible dataset + """ + data = [] + for sample in samples: + encoded_candidates, option_lens = encode_prompt(self.task, self.task.get_template( + template_version=self.args.template_ver), [], sample, + self.tokenizer, max_length=self.args.max_length, + generation=self.task.generation, + generation_with_gold=True, + max_new_tokens=self.args.max_new_tokens) + if self.task.generation: + correct_candidate_id = 0 + elif isinstance(sample.correct_candidate, list): + correct_candidate_id = sample.candidates.index(sample.correct_candidate[0]) + else: + correct_candidate_id = sample.candidates.index(sample.correct_candidate) + + if self.args.non_diff: + # For non-differentiable objective, there is no teacher forcing thus the + # current answer part is removed + encoded_candidates[correct_candidate_id] = encoded_candidates[correct_candidate_id][ + :-option_lens[correct_candidate_id]] + + if self.args.train_as_classification: + # For classification, we provide the label as the correct candidate id + data.append([{"input_ids": encoded_candidates[_i], "labels": correct_candidate_id, + "option_len": option_lens[_i], "num_options": len(sample.candidates)} for _i in + range(len(encoded_candidates))]) + elif self.args.only_train_option: + # Otherwise, it is just LM-style teacher forcing + if self.args.non_diff: + # For non-differentiable objective, we need to provide the gold answer to calculate F1/acc + data.append({"input_ids": encoded_candidates[correct_candidate_id], + "labels": encoded_candidates[correct_candidate_id], + "option_len": option_lens[correct_candidate_id], "gold": sample.correct_candidate}) + else: + data.append({"input_ids": encoded_candidates[correct_candidate_id], + "labels": encoded_candidates[correct_candidate_id], + "option_len": option_lens[correct_candidate_id]}) + else: + data.append({"input_ids": encoded_candidates[correct_candidate_id], + "labels": encoded_candidates[correct_candidate_id]}) + return data + + with count_time("Tokenizing training samples"): + train_dataset = HFDataset(_convert(train_samples)) + eval_dataset = HFDataset(_convert(eval_samples)) + dev_dataset = HFDataset(_convert(dev_samples)) + + if self.args.only_train_option and not self.args.non_diff: + # If --only_train_option and not with a non-differentiable objective, we wrap the forward function + self.model.original_forward = self.model.forward + self.model.forward = forward_wrap_with_option_len.__get__(self.model, type(self.model)) + + if self.args.non_diff: + collator = NondiffCollator + else: + collator = DataCollatorForTokenClassification + + if self.args.gradient_sparsity is not None: + logger.info( + f"[Sparse gradient] sparsity is {self.args.gradient_sparsity}, resampling per {self.args.sparse_gradient_resample_steps} steps" + ) + + if self.args.sparse_gradient_group == "global": + logger.info(f"[Sparse gradient] global-ratio random pruning is enabled, " + f"sparsity of each layer is computed based on the pretrained weight magnitude.") + elif self.args.sparse_gradient_group == "layer": + logger.info(f"[Sparse gradient] layer-wise random pruning is enabled, " + f"sparsity of each layer is the same.") + else: + raise NotImplementedError(f"Unknown sparse gradient group: {self.args.sparse_gradient_group}") + + perturb_module_regex = None + if self.args.module_wise_perturbation: + if "opt" in self.args.model_name: + assert self.args.perturbed_module_level in OPT_PERTURBATION_LEVEL_TO_REGEX.keys(), f"Unknown perturbed module group {self.args.perturbed_module_level}" + perturb_module_regex = OPT_PERTURBATION_LEVEL_TO_REGEX[self.args.perturbed_module_level] + else: + raise NotImplementedError(f"Unimplemented model {self.args.model_name} for module-wise perturbation") + + trainer = OurTrainer(model=self.model, + args=self.args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + tokenizer=self.tokenizer, + data_collator=DataCollatorWithPaddingAndNesting(self.tokenizer, + pad_to_multiple_of=8) if self.args.train_as_classification else collator( + self.tokenizer, pad_to_multiple_of=8), + eval_samples=eval_samples, + dev_samples=dev_samples, + evaluate_func=self.evaluate, + perturb_module_regex=perturb_module_regex, + ) + if self.args.save_on_interrupt: + trainer.add_callback(SIGUSR1Callback()) + + # Resume training from a last checkpoint + last_checkpoint = None + from transformers.trainer_utils import get_last_checkpoint + if os.path.isdir(self.args.output_dir) and not self.args.overwrite_output_dir: + last_checkpoint = get_last_checkpoint(self.args.output_dir) + if last_checkpoint is not None and self.args.resume_from_checkpoint is None: + logger.info(f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch.") + if self.args.resume_from_checkpoint is not None: + last_checkpoint = self.args.resume_from_checkpoint + + # This calls the trainer._inner_training_loop() + trainer.train(resume_from_checkpoint=last_checkpoint) + + # Explicitly save the model + if self.args.save_model: + logger.info("Save model..") + trainer.save_model() + + # FSDP compatibility + self.model = trainer.model + + # Reset the forward function for evaluation + if self.args.only_train_option and not self.args.non_diff: + if type(self.model) == FSDP: + logger.info("This is an FSDP model now. Be careful when assigning back the original forward function") + self.model._fsdp_wrapped_module.forward = self.model._fsdp_wrapped_module.original_forward + else: + self.model.forward = self.model.original_forward + + def delete_checkpoints(self): + import shutil + print(f"\nWARNING: Removing everything at end: {self.args.output_dir}") + deleted_folders = [folder for folder in os.listdir(self.args.output_dir) + if os.path.isdir(os.path.join(self.args.output_dir, folder)) + and folder.startswith("checkpoint-")] + for f in deleted_folders: + shutil.rmtree(os.path.join(self.args.output_dir, f)) + print(f"deleted folders: ", deleted_folders) + + +def result_file_tag(args): + """ + Get the result file tag + """ + save_model_name = args.model_name.split("/")[-1] + sfc_tag = "-sfc" if args.sfc else "" + icl_sfc_tag = "-icl_sfc" if args.icl_sfc else "" + sample_eval_tag = "-sampleeval%d" % args.num_eval if args.num_eval is not None else "" + sample_train_tag = "-ntrain%d" % args.num_train if args.num_train > 0 else "" + sample_dev_tag = "-ndev%d" % args.num_dev if args.num_dev is not None else "" + customized_tag = f"-{args.tag}" if len(args.tag) > 0 else "" + return f"{args.task_name}-{save_model_name}" + sfc_tag + icl_sfc_tag + sample_eval_tag + sample_train_tag + sample_dev_tag + customized_tag + + +def main(): + args = parse_args() + if args.prefix_tuning: + args.mode = "prefix" + elif args.lora: + args.mode = "lora" + elif args.prompt_tuning: + args.mode = "prompt" + else: + args.mode = "ft" + args.tag = f"{args.trainer}-{args.task_name}-{args.template_ver}-{args.model_name.split('/')[-1]}-OPTIM_{args.mode}-STEP{args.max_steps}-{args.optimizer}-LR{args.learning_rate}-{args.lr_scheduler_type}-ZOEPS{args.zo_eps}-Q{args.q}" + if args.trainer == "agzo": + args.tag += f"-AGZO_PI{args.agzo_power_iter_steps}" # AGZO: 记录power iteration次数 + if getattr(args, "agzo_rank", 1) > 1: + args.tag += f"-AGZO_R{args.agzo_rank}" + if args.agzo_empty_cache_steps > 0: + args.tag += f"-AGZO_EC{args.agzo_empty_cache_steps}" # AGZO: 记录缓存清理频率 + if args.agzo_debug_memory: + args.tag += "-AGZO_DBG" + args.tag = "momen" + args.tag if args.momentum > 0 else args.tag + args.tag = f"sparse_grad-{args.gradient_sparsity}-{args.sparse_gradient_group}-{args.sparse_gradient_resample_steps}-" + args.tag if args.gradient_sparsity is not None else args.tag + args.tag = f"module_perturb-{args.perturbed_module_level}-" + args.tag if args.module_wise_perturbation else args.tag + args.run_name = args.tag + args.output_dir = f"result/{args.tag}" + args.result_file = f"result/{args.tag}/results.json" + os.makedirs(args.output_dir, exist_ok=True) + args.logging_dir = os.path.join(args.output_dir, "logs") + os.makedirs(args.logging_dir, exist_ok=True) + + # If user only needs metrics, disable checkpoint saving + args.save_strategy = "no" # user requests no checkpoints to save disk usage + args.save_model = False + args.save_total_limit = 0 + args.load_best_model_at_end = False + + try: + wandb.init(project='zo-bench', name=args.tag, config=args) + except Exception as e: + # If running in a non-interactive environment without WANDB API key, + # wandb raises a UsageError prompting for an API key. Fall back to + # offline mode so the script can continue. + logger.warning("W&B init failed (%s). Falling back to offline mode.", e) + os.environ.setdefault("WANDB_MODE", "offline") + try: + wandb.init(project='zo-bench', name=args.tag, config=args, mode="offline") + except Exception: + # If still failing, continue without wandb (user can disable reporting via args) + logger.warning("W&B offline init also failed; continuing without wandb.") + + set_seed(args.seed) + task = get_task(args.task_name) + + # This function samples both training and validation samples. The validation (dev) samples are also stored in "train_sets" + # Later the train_samples and dev_samples are separated + train_sets = task.sample_train_sets(num_train=args.num_train, num_dev=args.num_dev, num_eval=args.num_eval, + num_train_sets=args.num_train_sets, seed=args.train_set_seed) + + # Initialize trainer and load model + framework = Framework(args, task) + + # ZO-Bench Added + # We add these parameters to evaluate the model during the training. + # These two parameters will be used in the training loop + # args.task = task + # args.framework = framework + + metrics = {} + + if args.train_set_seed is not None or args.num_train_sets is not None: + + # Training goes to this way + + # Eval samples share one (or multiple) training set(s) + for train_set_id, train_samples in enumerate(train_sets): + train_set_seed = train_set_id if args.train_set_seed is None else args.train_set_seed + + # Sample eval samples + if args.num_eval is not None: + eval_samples = task.sample_subset(data_split="valid", seed=train_set_seed, num=args.num_eval) + else: + eval_samples = task.valid_samples + + metrics = {} + + if args.trainer != "none": + # Here the training samples are seperated + if args.num_dev is not None: + # Dev samples + # assert args.num_dev + args.num_train <= len(train_samples), f"num_dev({args.num_dev})+num_train({args.num_train}) is more than actual num of training samples ({len(train_samples)})." + dev_samples = train_samples[-args.num_dev:] + train_samples = train_samples[:-args.num_dev] + logger.info("Dev samples: %d" % len(dev_samples)) + logger.info("Train samples: %d" % len(train_samples)) + else: + dev_samples = None + logger.info("Train samples: %d" % len(train_samples)) + logger.info("No dev samples") + + args.dev_samples = dev_samples + args.eval_samples = eval_samples + + # Training + framework.train(train_samples, dev_samples if dev_samples is not None else eval_samples, eval_samples) + + if not args.no_eval: # This is True + metrics = framework.evaluate([], eval_samples, description="Evaluating on the Test Set") + _keys = list(metrics.keys()) + for m in _keys: + metrics["test_" + m] = metrics[m] + if dev_samples is not None: + dev_metrics = framework.evaluate( + [], dev_samples, description="Evaluating on the Validation Set" + ) + _keys = list(dev_metrics.keys()) + for m in _keys: + metrics["val_" + m] = dev_metrics[m] + else: + assert args.num_dev is None + # Zero-shot / in-context learning + metrics = framework.evaluate(train_samples, eval_samples) + logger.info(metrics) + wandb.log( + metrics, + step=framework.trainer.state.global_step if hasattr(framework, "trainer") else None, + ) + + if not args.no_eval: + logger.info("===== Train set %d =====" % train_set_seed) + logger.info(metrics) + wandb.log(metrics, step=framework.trainer.state.global_step if hasattr(framework, "trainer") else None) + if args.local_rank <= 0: + write_metrics_to_file(metrics, "result/" + result_file_tag( + args) + f"-trainset{train_set_id}.json" if args.result_file is None else args.result_file) + if args.trainer != "none" and args.clean_model_at_end: + framework.delete_checkpoints() + + else: + # For each eval sample, there is a training set. no training is allowed + # This is for in-context learning (ICL) + assert args.trainer == "none" + if args.num_eval is not None: + eval_samples = task.sample_subset(data_split="valid", seed=0, num=args.num_eval) + else: + eval_samples = task.valid_samples + metrics = framework.evaluate(train_sets, eval_samples, one_train_set_per_eval_sample=True) + logger.info(metrics) + wandb.log(metrics, step=framework.trainer.state.global_step if hasattr(framework, "trainer") else None) + if args.local_rank <= 0: + write_metrics_to_file(metrics, "result/" + result_file_tag( + args) + "-onetrainpereval.json" if args.result_file is None else args.result_file) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_ft.yml new file mode 100644 index 0000000..fa2cc35 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_ft.yml @@ -0,0 +1,56 @@ +name: adam_copa_ft +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=epoch" +- "--save_strategy=epoch" +- "--save_total_limit=1" +- "--eval_steps=500" +# - "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +- "--fp16" +- "--per device train batch size=8" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + #- 1e-4 + #- 1e-5 + - 1e-6 + - 1e-7 + # - 1e-8 + zo_eps: + values: + - 1e-3 + # - 1e-4 + # - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_lora.yml new file mode 100644 index 0000000..564bae1 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_lora.yml @@ -0,0 +1,54 @@ +name: adam_copa_lora +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +# - "--max_steps=20000" +- "--load_float16" +- "--per device train batch size=8" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_prefix.yml new file mode 100644 index 0000000..860c8a8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_prefix.yml @@ -0,0 +1,53 @@ +name: adam_copa_prefix +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + # - "--max_steps=20000" + - "--fp16" + - "--per device train batch size=8" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_prompt.yml new file mode 100644 index 0000000..c5dbfb7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_prompt.yml @@ -0,0 +1,52 @@ +name: adam_copa_prompt +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + # - "--max_steps=20000" + - "--fp16" + - "--per device train batch size=8" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_ft.yml new file mode 100644 index 0000000..e907e14 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_ft.yml @@ -0,0 +1,47 @@ +name: forward_grad_copa_ft +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +- "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_lora.yml new file mode 100644 index 0000000..a9e559c --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_lora.yml @@ -0,0 +1,49 @@ +name: forward_grad_copa_lora +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--optimizer=sgd" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_prefix.yml new file mode 100644 index 0000000..2907064 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_prefix.yml @@ -0,0 +1,50 @@ +name: forward_grad_copa_prefix +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_prompt.yml new file mode 100644 index 0000000..af8a510 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_prompt.yml @@ -0,0 +1,49 @@ +name: forward_grad_copa_prompt +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_ft.yml new file mode 100644 index 0000000..44b3563 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_ft.yml @@ -0,0 +1,56 @@ +name: sgd_copa_ft +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=epoch" +- "--save_strategy=epoch" +- "--save_total_limit=1" +- "--eval_steps=500" +# - "--max_steps=20000" +- "--fp16" +- "--per device train batch size=8" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + # - 1e-8 + zo_eps: + values: + - 1e-3 + # - 1e-4 + # - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_lora.yml new file mode 100644 index 0000000..ea5c628 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_lora.yml @@ -0,0 +1,54 @@ +name: sgd_copa_lora +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +# - "--max_steps=20000" +- "--fp16" +- "--per device train batch size=8" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_prefix.yml new file mode 100644 index 0000000..62c9482 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_prefix.yml @@ -0,0 +1,53 @@ +name: sgd_copa_prefix +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + # - "--max_steps=20000" + - "--fp16" + - "--per device train batch size=8" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_prompt.yml new file mode 100644 index 0000000..a77438b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_prompt.yml @@ -0,0 +1,52 @@ +name: sgd_copa_prompt +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + # - "--max_steps=20000" + - "--fp16" + - "--per device train batch size=8" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_ft.yml new file mode 100644 index 0000000..48c2583 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_ft.yml @@ -0,0 +1,52 @@ +name: sign_opt_copa_ft +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=300" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sign_opt" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_lora.yml new file mode 100644 index 0000000..e2dbc33 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_lora.yml @@ -0,0 +1,51 @@ +name: zo_sign_sgd_copa_lora +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sign_opt" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_prefix.yml new file mode 100644 index 0000000..f3ab2ec --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_prefix.yml @@ -0,0 +1,54 @@ +name: sign_sgd_copa_prefix +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_prompt.yml new file mode 100644 index 0000000..8dee427 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_prompt.yml @@ -0,0 +1,54 @@ +name: sign_sgd_copa_prompt +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_ft.yml new file mode 100644 index 0000000..f86f0ee --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_ft.yml @@ -0,0 +1,52 @@ +name: zo_adam_copa_ft +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_lora.yml new file mode 100644 index 0000000..2706675 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_lora.yml @@ -0,0 +1,52 @@ +name: zo_adam_copa_lora +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +- "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_prefix.yml new file mode 100644 index 0000000..07cd9b0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_prefix.yml @@ -0,0 +1,55 @@ +name: zo_adam_copa_prefix +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_prompt.yml new file mode 100644 index 0000000..2d2a947 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_prompt.yml @@ -0,0 +1,54 @@ +name: zo_adam_copa_prompt +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_ft.yml new file mode 100644 index 0000000..80c2008 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_ft.yml @@ -0,0 +1,52 @@ +name: zo_sgd_copa_ft +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_lora.yml new file mode 100644 index 0000000..2924fa8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_lora.yml @@ -0,0 +1,52 @@ +name: zo_sgd_copa_lora +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_prefix.yml new file mode 100644 index 0000000..2cc82b6 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_prefix.yml @@ -0,0 +1,55 @@ +name: zo_sgd_copa_prefix +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_prompt.yml new file mode 100644 index 0000000..5a026de --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_prompt.yml @@ -0,0 +1,54 @@ +name: zo_sgd_copa_prompt +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml new file mode 100644 index 0000000..9877cbc --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml @@ -0,0 +1,52 @@ +name: zo_sgd_conserv_copa_ft +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_conserv" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml new file mode 100644 index 0000000..c3badf8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml @@ -0,0 +1,52 @@ +name: zo_sgd_conserv_copa_lora +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_conserv" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +- "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml new file mode 100644 index 0000000..33f6bd9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_copa_prefix +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml new file mode 100644 index 0000000..48f530d --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_copa_prompt +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml new file mode 100644 index 0000000..48fbd25 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_copa_ft +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-momen_$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=300" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml new file mode 100644 index 0000000..936a365 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml @@ -0,0 +1,54 @@ +name: zo_sgd_momen_copa_lora +project: zo_bench_Copa_llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml new file mode 100644 index 0000000..2ebf01c --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml @@ -0,0 +1,57 @@ +name: zo_sgd_momen_copa_prefix +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml new file mode 100644 index 0000000..b2e628f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml @@ -0,0 +1,56 @@ +name: zo_sgd_momen_copa_prompt +project: zo_bench_Copa_llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_ft.yml new file mode 100644 index 0000000..2986b87 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_ft.yml @@ -0,0 +1,54 @@ +name: adam_copa_ft +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=epoch" +- "--save_strategy=epoch" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + #- 1e-4 + #- 1e-5 + - 1e-6 + - 1e-7 + # - 1e-8 + zo_eps: + values: + - 1e-3 + # - 1e-4 + # - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_lora.yml new file mode 100644 index 0000000..6ef306a --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_lora.yml @@ -0,0 +1,52 @@ +name: adam_copa_lora +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_prefix.yml new file mode 100644 index 0000000..8d83d8c --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_prefix.yml @@ -0,0 +1,51 @@ +name: adam_copa_prefix +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_prompt.yml new file mode 100644 index 0000000..8b71f1b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_prompt.yml @@ -0,0 +1,50 @@ +name: adam_copa_prompt +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_ft.yml new file mode 100644 index 0000000..ff6ece1 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_ft.yml @@ -0,0 +1,47 @@ +name: forward_grad_copa_ft +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +- "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_lora.yml new file mode 100644 index 0000000..4d4ddf4 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_lora.yml @@ -0,0 +1,48 @@ +name: forward_grad_copa_lora +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_prefix.yml new file mode 100644 index 0000000..05b8e65 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_prefix.yml @@ -0,0 +1,50 @@ +name: forward_grad_copa_prefix +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_prompt.yml new file mode 100644 index 0000000..42208d8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_prompt.yml @@ -0,0 +1,49 @@ +name: forward_grad_copa_prompt +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_ft.yml new file mode 100644 index 0000000..fbfeeb6 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_ft.yml @@ -0,0 +1,54 @@ +name: sgd_copa_ft +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=epoch" +- "--save_strategy=epoch" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + # - 1e-8 + zo_eps: + values: + - 1e-3 + # - 1e-4 + # - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_lora.yml new file mode 100644 index 0000000..3983c46 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_lora.yml @@ -0,0 +1,52 @@ +name: sgd_copa_lora +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_prefix.yml new file mode 100644 index 0000000..4312189 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_prefix.yml @@ -0,0 +1,51 @@ +name: sgd_copa_prefix +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_prompt.yml new file mode 100644 index 0000000..1c9be18 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_prompt.yml @@ -0,0 +1,50 @@ +name: sgd_copa_prompt +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_ft.yml new file mode 100644 index 0000000..25f4b4f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_ft.yml @@ -0,0 +1,52 @@ +name: sign_opt_copa_ft +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=300" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sign_opt" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_lora.yml new file mode 100644 index 0000000..22f6972 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_lora.yml @@ -0,0 +1,51 @@ +name: zo_sign_sgd_copa_lora +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sign_opt" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_prefix.yml new file mode 100644 index 0000000..56879e4 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_prefix.yml @@ -0,0 +1,54 @@ +name: sign_sgd_copa_prefix +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_prompt.yml new file mode 100644 index 0000000..f6e3147 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_prompt.yml @@ -0,0 +1,54 @@ +name: sign_sgd_copa_prompt +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_ft.yml new file mode 100644 index 0000000..6687f4f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_ft.yml @@ -0,0 +1,52 @@ +name: zo_adam_copa_ft +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_lora.yml new file mode 100644 index 0000000..bb649df --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_lora.yml @@ -0,0 +1,51 @@ +name: zo_adam_copa_lora +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_prefix.yml new file mode 100644 index 0000000..9ee3963 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_prefix.yml @@ -0,0 +1,55 @@ +name: zo_adam_copa_prefix +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_prompt.yml new file mode 100644 index 0000000..1153eb3 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_prompt.yml @@ -0,0 +1,54 @@ +name: zo_adam_copa_prompt +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_ft.yml new file mode 100644 index 0000000..9ad78b8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_ft.yml @@ -0,0 +1,52 @@ +name: zo_sgd_copa_ft +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_lora.yml new file mode 100644 index 0000000..ff3c618 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_lora.yml @@ -0,0 +1,52 @@ +name: zo_sgd_copa_lora +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_prefix.yml new file mode 100644 index 0000000..dc25801 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_prefix.yml @@ -0,0 +1,55 @@ +name: zo_sgd_copa_prefix +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_prompt.yml new file mode 100644 index 0000000..e59fdf7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_prompt.yml @@ -0,0 +1,54 @@ +name: zo_sgd_copa_prompt +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml new file mode 100644 index 0000000..832f4fd --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml @@ -0,0 +1,52 @@ +name: zo_sgd_conserv_copa_ft +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_conserv" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml new file mode 100644 index 0000000..744d09f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_copa_lora +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_conserv" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml new file mode 100644 index 0000000..13eabd8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_copa_prefix +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml new file mode 100644 index 0000000..3696bdf --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_copa_prompt +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml new file mode 100644 index 0000000..e98d92e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_copa_ft +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-momen_$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=300" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml new file mode 100644 index 0000000..f9715b6 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml @@ -0,0 +1,54 @@ +name: zo_sgd_momen_copa_lora +project: zo_bench_Copa_llama-2-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml new file mode 100644 index 0000000..4e63662 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml @@ -0,0 +1,57 @@ +name: zo_sgd_momen_copa_prefix +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml new file mode 100644 index 0000000..73d3a44 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml @@ -0,0 +1,56 @@ +name: zo_sgd_momen_copa_prompt +project: zo_bench_Copa_llama-2-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_ft.yml new file mode 100644 index 0000000..5fedd39 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: adam_copa_ft +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_lora.yml new file mode 100644 index 0000000..4427e7c --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_lora.yml @@ -0,0 +1,46 @@ +name: adam_copa_lora +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_prefix.yml new file mode 100644 index 0000000..8130d4a --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: adam_copa_prefix +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_prompt.yml new file mode 100644 index 0000000..54c74e8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: adam_copa_prompt +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_ft.yml new file mode 100644 index 0000000..4c537c3 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: forward_grad_copa_ft +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--save_model" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_lora.yml new file mode 100644 index 0000000..ef1d644 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_lora.yml @@ -0,0 +1,46 @@ +name: forward_grad_copa_lora +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_prefix.yml new file mode 100644 index 0000000..6b98b88 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_prefix.yml @@ -0,0 +1,49 @@ +name: forward_grad_copa_prefix +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_prompt.yml new file mode 100644 index 0000000..2df5011 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_prompt.yml @@ -0,0 +1,48 @@ +name: forward_grad_copa_prompt +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_ft.yml new file mode 100644 index 0000000..0840f28 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: sgd_copa_ft +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_lora.yml new file mode 100644 index 0000000..557a3f2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: sgd_copa_lora +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_prefix.yml new file mode 100644 index 0000000..5ecd044 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: sgd_copa_prefix +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_prompt.yml new file mode 100644 index 0000000..a3cf95b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: sgd_copa_prompt +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_ft.yml new file mode 100644 index 0000000..2719f50 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sign_sgd_copa_ft +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_lora.yml new file mode 100644 index 0000000..0f6fc06 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sign_sgd_copa_lora +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..6e39a4b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sign_sgd_copa_prefix +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..9665087 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sign_sgd_copa_prompt +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_ft.yml new file mode 100644 index 0000000..5130598 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_copa_ft +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_lora.yml new file mode 100644 index 0000000..0351b9e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_adam_copa_lora +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_prefix.yml new file mode 100644 index 0000000..9762489 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_adam_copa_prefix +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_prompt.yml new file mode 100644 index 0000000..05dac88 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_adam_copa_prompt +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_ft.yml new file mode 100644 index 0000000..9e0d4f8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_copa_ft +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_lora.yml new file mode 100644 index 0000000..ea2d9dd --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_copa_lora +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..a556ed6 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_copa_prefix +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..b9625f5 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_copa_prompt +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml new file mode 100644 index 0000000..42d41df --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_copa_ft +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml new file mode 100644 index 0000000..a48a549 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sgd_conserv_copa_lora +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml new file mode 100644 index 0000000..27bafca --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_copa_prefix +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml new file mode 100644 index 0000000..24222ea --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_conserv_copa_prompt +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml new file mode 100644 index 0000000..f15894b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_copa_ft +project: zo_bench_copa_mistral-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=mistralai/Mistral-7B-v0.1" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml new file mode 100644 index 0000000..391361f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_copa_lora +project: zo_bench_copa_mistral-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=mistralai/Mistral-7B-v0.1" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml new file mode 100644 index 0000000..1a4d7fe --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml @@ -0,0 +1,59 @@ +name: zo_sgd_momen_copa_prefix +project: zo_bench_copa_mistral-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=mistralai/Mistral-7B-v0.1" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml new file mode 100644 index 0000000..e3a5048 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml @@ -0,0 +1,57 @@ +name: zo_sgd_copa_prompt +project: zo_bench_copa_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_ft.yml new file mode 100644 index 0000000..89b4729 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_ft.yml @@ -0,0 +1,54 @@ +name: adam_copa_ft +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=epoch" +- "--save_strategy=epoch" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + #- 1e-4 + #- 1e-5 + - 1e-6 + - 1e-7 + # - 1e-8 + zo_eps: + values: + - 1e-3 + # - 1e-4 + # - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_lora.yml new file mode 100644 index 0000000..f4543fb --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_lora.yml @@ -0,0 +1,52 @@ +name: adam_copa_lora +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_prefix.yml new file mode 100644 index 0000000..1cf90a1 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_prefix.yml @@ -0,0 +1,51 @@ +name: adam_copa_prefix +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_prompt.yml new file mode 100644 index 0000000..346aed9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_prompt.yml @@ -0,0 +1,50 @@ +name: adam_copa_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_ft-ablation.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_ft-ablation.yml new file mode 100644 index 0000000..23e8b79 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_ft-ablation.yml @@ -0,0 +1,48 @@ +name: forward_grad_copa_ft +project: zo_bench_Copa +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--save_model" + - "--optimizer=sgd" + - "--template_ver=1" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_ft.yml new file mode 100644 index 0000000..04302fc --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_ft.yml @@ -0,0 +1,49 @@ +name: forward_grad_copa_ft +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +- "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + values: + - 1e-5 + - 5e-6 + - 1e-6 + - 5e-7 + - 1e-7 + - 5e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_lora.yml new file mode 100644 index 0000000..33e137c --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_lora.yml @@ -0,0 +1,48 @@ +name: forward_grad_copa_lora +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_prefix.yml new file mode 100644 index 0000000..b6bc386 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_prefix.yml @@ -0,0 +1,50 @@ +name: forward_grad_copa_prefix +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_prompt.yml new file mode 100644 index 0000000..2018b20 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_prompt.yml @@ -0,0 +1,49 @@ +name: forward_grad_copa_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_ft-ablation.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_ft-ablation.yml new file mode 100644 index 0000000..ca737c9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_ft-ablation.yml @@ -0,0 +1,55 @@ +name: sgd_copa_ft +project: zo_bench_Copa +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=epoch" + - "--save_strategy=epoch" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" + - "--save_model" + - "--template_ver=1" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 # best +# - 1e-5 +# - 1e-6 +# - 1e-7 +# - 1e-8 + zo_eps: + values: + - 1e-3 # best +# - 1e-4 +# - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_ft.yml new file mode 100644 index 0000000..fb7f0f7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_ft.yml @@ -0,0 +1,54 @@ +name: sgd_copa_ft +project: zo_bench_Copa +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=epoch" + - "--save_strategy=epoch" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 # best + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 # best + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_lora.yml new file mode 100644 index 0000000..cb0160f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_lora.yml @@ -0,0 +1,52 @@ +name: sgd_copa_lora +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_prefix.yml new file mode 100644 index 0000000..10f2872 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_prefix.yml @@ -0,0 +1,51 @@ +name: sgd_copa_prefix +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_prompt.yml new file mode 100644 index 0000000..6cf05aa --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_prompt.yml @@ -0,0 +1,50 @@ +name: sgd_copa_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_ft.yml new file mode 100644 index 0000000..7915a65 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_ft.yml @@ -0,0 +1,52 @@ +name: sign_opt_copa_ft +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=300" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sign_opt" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_lora.yml new file mode 100644 index 0000000..f232c23 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_lora.yml @@ -0,0 +1,51 @@ +name: zo_sign_sgd_copa_lora +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sign_opt" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_prefix.yml new file mode 100644 index 0000000..29a0ef6 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_prefix.yml @@ -0,0 +1,54 @@ +name: sign_sgd_copa_prefix +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_prompt.yml new file mode 100644 index 0000000..b2bb54e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_prompt.yml @@ -0,0 +1,54 @@ +name: sign_sgd_copa_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_ft.yml new file mode 100644 index 0000000..2f6892e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_ft.yml @@ -0,0 +1,52 @@ +name: zo_adam_copa_ft +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_lora.yml new file mode 100644 index 0000000..fe855d7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_lora.yml @@ -0,0 +1,51 @@ +name: zo_adam_copa_lora +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_prefix.yml new file mode 100644 index 0000000..97e4663 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_prefix.yml @@ -0,0 +1,55 @@ +name: zo_adam_copa_prefix +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_prompt.yml new file mode 100644 index 0000000..f481ad9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_prompt.yml @@ -0,0 +1,54 @@ +name: zo_adam_copa_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_ft-ablation.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_ft-ablation.yml new file mode 100644 index 0000000..105a01d --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_ft-ablation.yml @@ -0,0 +1,54 @@ +name: zo_sgd_copa_ft +project: zo_bench_Copa +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" + - "--save_model" + - "--template_ver=1" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_ft.yml new file mode 100644 index 0000000..f85fa93 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_ft.yml @@ -0,0 +1,53 @@ +name: zo_sgd_copa_ft +project: zo_bench_Copa +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lora.yml new file mode 100644 index 0000000..6245902 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lora.yml @@ -0,0 +1,54 @@ +name: zo_sgd_copa_lora +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-3 + - 5e-4 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lp-ablation.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lp-ablation.yml new file mode 100644 index 0000000..b9d2614 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lp-ablation.yml @@ -0,0 +1,54 @@ +name: zo_sgd_copa_lp-abl +project: zo_bench_lp +command: + - ${interpreter} + - ${program} + - ${args} + - "--head_tuning" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--template_ver=1" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lp.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lp.yml new file mode 100644 index 0000000..faca806 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lp.yml @@ -0,0 +1,53 @@ +name: zo_sgd_copa_lp +project: zo_bench_lp +command: + - ${interpreter} + - ${program} + - ${args} + - "--head_tuning" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_prefix.yml new file mode 100644 index 0000000..11eee2e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_prefix.yml @@ -0,0 +1,55 @@ +name: zo_sgd_copa_prefix +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_prompt.yml new file mode 100644 index 0000000..c9a5edd --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_prompt.yml @@ -0,0 +1,54 @@ +name: zo_sgd_copa_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml new file mode 100644 index 0000000..58140e4 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml @@ -0,0 +1,52 @@ +name: zo_sgd_conserv_copa_ft +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_conserv" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_bfloat16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml new file mode 100644 index 0000000..11b6c35 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_copa_lora +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_conserv" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml new file mode 100644 index 0000000..d9f7288 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_copa_prefix +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml new file mode 100644 index 0000000..4c2950f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_copa_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml new file mode 100644 index 0000000..2af673a --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_copa_ft +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-momen_$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=300" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml new file mode 100644 index 0000000..a89c90e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml @@ -0,0 +1,54 @@ +name: zo_sgd_momen_copa_lora +project: zo_bench_Copa +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-13b" +- "--task_name=Copa" +- "--output_dir=result/Copa-lora-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-4 + - 5e-5 + - 1e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml new file mode 100644 index 0000000..1f873cf --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml @@ -0,0 +1,57 @@ +name: zo_sgd_momen_copa_prefix +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml new file mode 100644 index 0000000..27b8c21 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml @@ -0,0 +1,56 @@ +name: zo_sgd_momen_copa_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_ft.yml new file mode 100644 index 0000000..9547f35 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: adam_copa_ft +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +# - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_lora.yml new file mode 100644 index 0000000..c294ca9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_lora.yml @@ -0,0 +1,46 @@ +name: adam_copa_lora +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_prefix.yml new file mode 100644 index 0000000..9263320 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: adam_copa_prefix +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_prompt.yml new file mode 100644 index 0000000..ea040a0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: adam_copa_prompt +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_ft.yml new file mode 100644 index 0000000..d5dc71e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: forward_grad_copa_ft +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--save_model" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_lora.yml new file mode 100644 index 0000000..7010289 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_lora.yml @@ -0,0 +1,46 @@ +name: forward_grad_copa_lora +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_prefix.yml new file mode 100644 index 0000000..a938df7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_prefix.yml @@ -0,0 +1,49 @@ +name: forward_grad_copa_prefix +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_prompt.yml new file mode 100644 index 0000000..ede99f0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_prompt.yml @@ -0,0 +1,48 @@ +name: forward_grad_copa_prompt +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_ft.yml new file mode 100644 index 0000000..7895fac --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: sgd_copa_ft +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_lora.yml new file mode 100644 index 0000000..50fbdb2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: sgd_copa_lora +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_prefix.yml new file mode 100644 index 0000000..9c9e4d0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: sgd_copa_prefix +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_prompt.yml new file mode 100644 index 0000000..d60f8e0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: sgd_copa_prompt +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_ft.yml new file mode 100644 index 0000000..0fece0b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sign_sgd_copa_ft +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_lora.yml new file mode 100644 index 0000000..8e828eb --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sign_sgd_copa_lora +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..79397b0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sign_sgd_copa_prefix +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..f5e1c6a --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sign_sgd_copa_prompt +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_ft.yml new file mode 100644 index 0000000..b38716e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_copa_ft +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_lora.yml new file mode 100644 index 0000000..d0648a0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_adam_copa_lora +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_prefix.yml new file mode 100644 index 0000000..3aa9b3a --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_adam_copa_prefix +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_prompt.yml new file mode 100644 index 0000000..96f0701 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_adam_copa_prompt +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_ft.yml new file mode 100644 index 0000000..1c8ad84 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_copa_ft +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_lora.yml new file mode 100644 index 0000000..a2037c7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_copa_lora +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..db0955c --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_copa_prefix +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..1a71ea2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_copa_prompt +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml new file mode 100644 index 0000000..86598c9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_copa_ft +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml new file mode 100644 index 0000000..26d53de --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sgd_conserv_copa_lora +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml new file mode 100644 index 0000000..6a09a8d --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_copa_prefix +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml new file mode 100644 index 0000000..23338d7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_conserv_copa_prompt +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml new file mode 100644 index 0000000..579e039 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_copa_ft +project: zo_bench_copa_vicuna-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=lmsys/vicuna-7b-v1.5" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml new file mode 100644 index 0000000..92bee8f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_copa_lora +project: zo_bench_copa_vicuna-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=lmsys/vicuna-7b-v1.5" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml new file mode 100644 index 0000000..68417ea --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml @@ -0,0 +1,59 @@ +name: zo_sgd_momen_copa_prefix +project: zo_bench_copa_vicuna-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=lmsys/vicuna-7b-v1.5" +- "--task_name=Copa" +- "--output_dir=result/Copa-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml new file mode 100644 index 0000000..798e994 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml @@ -0,0 +1,57 @@ +name: zo_sgd_copa_prompt +project: zo_bench_copa_vicuna-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=Copa" + - "--output_dir=result/Copa-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_ft.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_ft.yml new file mode 100644 index 0000000..a77a0e3 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_cls_prefix +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +# - "--prefix_tuning" +# - "--num_prefix=5" +# - "--no_reparam" +# - "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + # - 1e-3 + - 1e-4 + # - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + - 1e-3 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_lora.yml new file mode 100644 index 0000000..a29234a --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_lora.yml @@ -0,0 +1,47 @@ +name: zo_sgd_cls_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_prefix.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_prefix.yml new file mode 100644 index 0000000..592e613 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_prefix.yml @@ -0,0 +1,50 @@ +name: zo_sgd_cls_prefix +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_prompt.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_prompt.yml new file mode 100644 index 0000000..278595a --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_prompt.yml @@ -0,0 +1,49 @@ +name: adam_cls_prompt_toto +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prompt_tuning" +- "--num_virtual_tokens=10" +- "--prompt_init_by_real_tokens" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + # - 1e-3 + - 1e-4 + # - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_ft-ablation.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_ft-ablation.yml new file mode 100644 index 0000000..30c2b6f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_ft-ablation.yml @@ -0,0 +1,45 @@ +name: forward_grad_cls_ft-abl +project: zo_bench_SST2 +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=SST2" + - "--output_dir=result/SST2-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=500" + - "--train_as_classification" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--optimizer=sgd" + - "--weight_decay=0" + - "--template_ver=1" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 5e-7 # This is the best + - 1e-8 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_ft.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_ft.yml new file mode 100644 index 0000000..0167da2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_ft.yml @@ -0,0 +1,44 @@ +name: forward_grad_cls_ft +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--optimizer=sgd" +- "--weight_decay=0" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 5e-7 # This is the best + - 1e-8 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_lora.yml new file mode 100644 index 0000000..e7d6e10 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_lora.yml @@ -0,0 +1,46 @@ +name: forward_grad_cls_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--optimizer=sgd" +- "--weight_decay=0" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 # Best + - 5e-5 + - 1e-6 + - 5e-6 + - 1e-7 + - 5e-7 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_prefix.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_prefix.yml new file mode 100644 index 0000000..ca36d31 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_prefix.yml @@ -0,0 +1,45 @@ +name: forward_grad_cls_prefix +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2/" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--optimizer=sgd" +- "--weight_decay=0" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 5e-3 + - 1e-3 + - 5e-4 # Best +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_prompt.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_prompt.yml new file mode 100644 index 0000000..2571b21 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_prompt.yml @@ -0,0 +1,47 @@ +name: forward_grad_cls_prompt_coco +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prompt_tuning" +- "--num_virtual_tokens=10" +- "--prompt_init_by_real_tokens" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2/" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--optimizer=sgd" +- "--weight_decay=0" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + # - 5e-3 + - 1e-3 + # - 5e-4 + - 1e-4 + - 5e-5 +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_ft.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_ft.yml new file mode 100644 index 0000000..333e2b7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_ft.yml @@ -0,0 +1,48 @@ +name: forward_grad_cls_ft +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--optimizer=adam" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-6 + - 1e-7 + - 1e-8 + - 1e-9 + - 1e-10 + - 1e-11 + - 1e-12 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_lora.yml new file mode 100644 index 0000000..9501cdc --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_lora.yml @@ -0,0 +1,49 @@ +name: forward_grad_cls_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--optimizer=adam" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-6 + - 1e-7 + - 1e-8 + - 1e-9 + - 1e-10 + - 1e-11 + - 1e-12 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_prefix.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_prefix.yml new file mode 100644 index 0000000..0d599dc --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_prefix.yml @@ -0,0 +1,52 @@ +name: forward_grad_cls_prefix +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2/" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--optimizer=adam" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-6 + - 1e-7 + - 1e-8 + - 1e-9 + - 1e-10 + - 1e-11 + - 1e-12 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_ft.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_ft.yml new file mode 100644 index 0000000..db2b687 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_ft.yml @@ -0,0 +1,51 @@ +name: forward_grad_cls_ft +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--eval_steps=500" +- "--save_steps=500" +- "--weight_decay=0" +- "--warmup_ratio=0.2" +- "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 3e-9 + - 1e-10 + - 5e-11 + - 3e-11 + lr_scheduler_type: + values: + - linear + - cosine + - cosine_with_restarts + - polynomial + - constant + - constant_with_warmup + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_lora.yml new file mode 100644 index 0000000..d02846b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_lora.yml @@ -0,0 +1,51 @@ +name: forward_grad_cls_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--eval_steps=500" +- "--save_steps=500" +- "--weight_decay=0" +- "--warmup_ratio=0.2" +- "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 3e-5 + - 5e-5 + lr_scheduler_type: + values: + - linear + - cosine + - cosine_with_restarts + - polynomial + - constant + - constant_with_warmup + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_prefix.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_prefix.yml new file mode 100644 index 0000000..c4fcc46 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_prefix.yml @@ -0,0 +1,53 @@ +name: forward_grad_cls_prefix +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2/" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--eval_steps=500" +- "--save_steps=500" +- "--weight_decay=0" +- "--warmup_ratio=0.2" +- "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 3e-3 + - 1e-3 + - 5e-4 + lr_scheduler_type: + values: + - linear + - cosine + - cosine_with_restarts + - polynomial + - constant + - constant_with_warmup +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_q_number/forward_grad_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_q_number/forward_grad_cls_lora.yml new file mode 100644 index 0000000..17867f9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_q_number/forward_grad_cls_lora.yml @@ -0,0 +1,55 @@ +name: forward_grad_cls_lora_q_study +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--eval_steps=500" +- "--save_steps=500" +- "--weight_decay=0" +- "--warmup_ratio=0.2" +- "--optimizer=sgd" +- "--learning_rate=3e-5" +- "--lr_scheduler_type=cosine" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + q: + values: + - 2 + - 3 + - 4 + - 5 + learning_rate: + values: + - 5e-5 + - 5e-5 + - 3e-5 + - 1e-5 + - 5e-6 + - 3e-6 + - 1e-6 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_q_number/forward_grad_cls_prefix.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_q_number/forward_grad_cls_prefix.yml new file mode 100644 index 0000000..b8a6676 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_q_number/forward_grad_cls_prefix.yml @@ -0,0 +1,55 @@ +name: forward_grad_cls_prefix_q_study +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2/" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=forward_grad" +- "--train_set_seed=0" +- "--eval_steps=500" +- "--save_steps=500" +- "--weight_decay=0" +- "--warmup_ratio=0.2" +- "--optimizer=sgd" +- "--lr_scheduler_type=constant_with_warmup" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + q: + values: + - 2 + - 3 + - 4 + - 5 + learning_rate: + values: + - 1e-2 + - 5e-3 + - 3e-3 + - 1e-3 + - 5e-4 + - 3e-4 +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_ft.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_ft.yml new file mode 100644 index 0000000..6738853 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_ft.yml @@ -0,0 +1,48 @@ +name: sgd_ft_meme +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-1.3b" + - "--task_name=SST2" + - "--output_dir=result/SST2-ft-$TAG" + - "--num_train_epochs=5" + # - "--per_device_train_batch_size=16" # TODO this one should be smaller. + - "--load_best_model_at_end" + - "--evaluation_strategy=epoch" + - "--save_strategy=epoch" + - "--save_total_limit=1" + # - "--max_steps=20000" # TODO this one should remove + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=500" + - "--train_as_classification" + - "--perturbation_mode=two_side" + - "--trainer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + # params that were missing. I added according to finetune.sh. All FO methods should follow to update. + - "--fp16" + - "--load_float16" + - "--per_device_train_batch_size=8" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_lora.yml new file mode 100644 index 0000000..48a9af3 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_lora.yml @@ -0,0 +1,47 @@ +name: zo_sgd_cls_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=regular" +- "--optimizer=sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_prompt.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_prompt.yml new file mode 100644 index 0000000..efce015 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_prompt.yml @@ -0,0 +1,52 @@ +name: sgd_cls_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + # Ref run according to `MODEL=facebook/opt-1.3b TASK=SST2 MODE=prompt LR=1e-2 bash finetune.sh` + # python run.py --model_name facebook/opt-1.3b --task_name SST2 --output_dir result/SST2-opt-1.3b-prompt-5-8-1e-2-0 --tag prompt-5-8-1e-2-0 --train_set_seed 0 --num_train 1000 --num_dev 500 --num_eval 1000 --logging_steps 10 --trainer regular --fp16 --learning_rate 1e-2 --num_train_epochs 5 --per_device_train_batch_size 8 --load_best_model_at_end --evaluation_strategy epoch --save_strategy epoch --save_total_limit 1 --train_as_classification --prompt_tuning --num_virtual_tokens 10 --prompt_init_by_real_tokens" + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-1.3b" + - "--task_name=SST2" + - "--output_dir=result/SST2-ft-$TAG" + - "--num_train_epochs=5" + # - "--per_device_train_batch_size=16" # TODO this one should be smaller. + - "--load_best_model_at_end" + - "--evaluation_strategy=epoch" + - "--save_strategy=epoch" + - "--save_total_limit=1" + # - "--max_steps=20000" # TODO this one should remove + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=500" + - "--train_as_classification" + - "--perturbation_mode=two_side" + - "--trainer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + # params that were missing. I added according to finetune.sh. All FO methods should follow to update. + - "--fp16" + - "--per_device_train_batch_size=8" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_ft_wjan.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_ft_wjan.yml new file mode 100644 index 0000000..f4e3870 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_ft_wjan.yml @@ -0,0 +1,50 @@ +name: sign_opt_cls_ft_dudu +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_sign_opt" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + # - 1e-5 + - 1e-6 + # - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + # - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_lora.yml new file mode 100644 index 0000000..63cb482 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_lora.yml @@ -0,0 +1,50 @@ +name: sign_opt_cls_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-lora-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_sign_opt" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_prefix.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_prefix.yml new file mode 100644 index 0000000..8186f52 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_prefix.yml @@ -0,0 +1,50 @@ +name: sign_opt_cls_prefix +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_sign_opt" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + zo_eps: + values: + - 1e-1 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_prompt.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_prompt.yml new file mode 100644 index 0000000..06985ec --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_prompt.yml @@ -0,0 +1,53 @@ +name: sign_opt_cls_prompt_gygy +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prompt_tuning" +- "--num_virtual_tokens=10" +- "--prompt_init_by_real_tokens" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_sign_opt" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + # - 1e-5 + - 1e-6 + # - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + # - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_ft.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_ft.yml new file mode 100644 index 0000000..974675f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_ft.yml @@ -0,0 +1,50 @@ +name: zo_adam_cls_ft +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_lora.yml new file mode 100644 index 0000000..a3351dd --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_lora.yml @@ -0,0 +1,50 @@ +name: zo_adam_cls_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_prefix.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_prefix.yml new file mode 100644 index 0000000..4a88887 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_prefix.yml @@ -0,0 +1,54 @@ +name: zo_adam_cls_prefix +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_prompt.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_prompt.yml new file mode 100644 index 0000000..99aa444 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_prompt.yml @@ -0,0 +1,53 @@ +name: zo_adam_cls_prompt +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prompt_tuning" +- "--num_virtual_tokens=10" +- "--prompt_init_by_real_tokens" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_adam" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_ft-ablation.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_ft-ablation.yml new file mode 100644 index 0000000..c8ce0cf --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_ft-ablation.yml @@ -0,0 +1,51 @@ +name: zo_sgd_cls_ft_abl +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=SST2" + - "--output_dir=result/SST2-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=500" + - "--train_as_classification" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--template_ver=1" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_ft.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_ft.yml new file mode 100644 index 0000000..ffacfef --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_ft.yml @@ -0,0 +1,50 @@ +name: zo_sgd_cls_ft +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-1.3b" + - "--task_name=SST2" + - "--output_dir=result/SST2-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=500" + - "--train_as_classification" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lora.yml new file mode 100644 index 0000000..b7f6cf0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lora.yml @@ -0,0 +1,50 @@ +name: zo_sgd_cls_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lp-ablation.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lp-ablation.yml new file mode 100644 index 0000000..2ca404d --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lp-ablation.yml @@ -0,0 +1,53 @@ +name: zo_sgd_cls_lp_abl +project: zo_bench_lp +command: + - ${interpreter} + - ${program} + - ${args} + - "--head_tuning" + - "--model_name=facebook/opt-13b" + - "--task_name=SST2" + - "--output_dir=result/SST2-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=500" + - "--train_as_classification" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--template_ver=1" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lp.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lp.yml new file mode 100644 index 0000000..2d410e1 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lp.yml @@ -0,0 +1,52 @@ +name: zo_sgd_cls_lp +project: zo_bench_lp +command: + - ${interpreter} + - ${program} + - ${args} + - "--head_tuning" + - "--model_name=facebook/opt-13b" + - "--task_name=SST2" + - "--output_dir=result/SST2-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=500" + - "--train_as_classification" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_prefix.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_prefix.yml new file mode 100644 index 0000000..efa79f3 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_prefix.yml @@ -0,0 +1,50 @@ +name: zo_sgd_cls_prefix +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + zo_eps: + values: + - 1e-1 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_prompt.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_prompt.yml new file mode 100644 index 0000000..1a85fe3 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_prompt.yml @@ -0,0 +1,52 @@ +name: zo_sgd_cls_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-1.3b" + - "--task_name=SST2" + - "--output_dir=result/SST2-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=500" + - "--train_as_classification" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_squad_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_squad_lora.yml new file mode 100644 index 0000000..e1773be --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_squad_lora.yml @@ -0,0 +1,48 @@ +name: zo_sgd_SQuAD_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-13b" +- "--task_name=SQuAD" +- "--output_dir=result/SQuAD-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_f1 +parameters: + learning_rate: + values: + - 1e-4 + - 5e-5 + zo_eps: + values: + - 1e-2 + - 1e-3 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_ft.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_ft.yml new file mode 100644 index 0000000..60ebe06 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_ft.yml @@ -0,0 +1,49 @@ +name: zo_sgd_conserv_cls_ft +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_conserv" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_lora.yml new file mode 100644 index 0000000..3daae6a --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_lora.yml @@ -0,0 +1,50 @@ +name: zo_sgd_cls_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_conserv" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_prefix.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_prefix.yml new file mode 100644 index 0000000..eb07fab --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_prefix.yml @@ -0,0 +1,53 @@ +name: zo_sgd_cls_prefix +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_conserv" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_prompt.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_prompt.yml new file mode 100644 index 0000000..64fc67e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_prompt.yml @@ -0,0 +1,52 @@ +name: zo_sgd_conserv_cls_prompt_ruru +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prompt_tuning" +- "--num_virtual_tokens=10" +- "--prompt_init_by_real_tokens" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_conserv" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_ft.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_ft.yml new file mode 100644 index 0000000..d369663 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_ft.yml @@ -0,0 +1,52 @@ +name: zo_sgd_cls_ft +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_lora.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_lora.yml new file mode 100644 index 0000000..8d578dd --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_lora.yml @@ -0,0 +1,53 @@ +name: zo_sgd_cls_lora +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_prefix.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_prefix.yml new file mode 100644 index 0000000..6134297 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_prefix.yml @@ -0,0 +1,53 @@ +name: zo_sgd_cls_prefix +project: zo_bench +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-1.3b" +- "--task_name=SST2" +- "--output_dir=result/SST2-ft-$TAG" +- "--num_train_epochs=5" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=1000" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=500" +- "--train_as_classification" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--eval_steps=500" +- "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + zo_eps: + values: + - 1e-1 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_prompt.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_prompt.yml new file mode 100644 index 0000000..279539b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_prompt.yml @@ -0,0 +1,55 @@ +name: zo_sgd_cls_prompt +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-1.3b" + - "--task_name=SST2" + - "--output_dir=result/SST2-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=500" + - "--train_as_classification" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_sparse_grad/zo_sgd_sparse_grad_cls_ft.yml b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_sparse_grad/zo_sgd_sparse_grad_cls_ft.yml new file mode 100644 index 0000000..28d97a1 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_sparse_grad/zo_sgd_sparse_grad_cls_ft.yml @@ -0,0 +1,70 @@ +name: zo_sgd_sparse_grad_cls_ft +project: zo_bench +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-1.3b" + - "--task_name=SST2" + - "--output_dir=result/SST2-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=1000" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=500" + - "--train_as_classification" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--eval_steps=500" + - "--save_steps=500" + - "--load_float16" + - "--save_model" + - "--sparse_gradient_group=global" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-6 + zo_eps: + values: + - 1e-3 + weight_decay: + values: + - 0 + gradient_sparsity: + values: + - 0.1 + - 0.2 + - 0.3 + - 0.4 + - 0.5 + - 0.6 + - 0.7 + - 0.8 + - 0.9 + sparse_gradient_resample_steps: + values: + - 1 + - 10 + - 100 + - 500 + - 1000 + - 5000 + - 10000 + - 20000 + + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_ft.yml new file mode 100644 index 0000000..6ca92f7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: adam_winogrande_ft +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_lora.yml new file mode 100644 index 0000000..2c0dbdc --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: adam_winogrande_lora +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_prefix.yml new file mode 100644 index 0000000..2b824f5 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: adam_winogrande_prefix +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_prompt.yml new file mode 100644 index 0000000..80d0a2f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: adam_winogrande_prompt +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_ft.yml new file mode 100644 index 0000000..d785bed --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: forward_grad_winogrande_ft +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--save_model" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_lora.yml new file mode 100644 index 0000000..6572a68 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: forward_grad_winogrande_lora +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_prefix.yml new file mode 100644 index 0000000..faf1e42 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_prefix.yml @@ -0,0 +1,49 @@ +name: forward_grad_winogrande_prefix +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_prompt.yml new file mode 100644 index 0000000..1749701 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_prompt.yml @@ -0,0 +1,48 @@ +name: forward_grad_winogrande_prompt +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_ft.yml new file mode 100644 index 0000000..a2c6611 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: sgd_winogrande_ft +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_lora.yml new file mode 100644 index 0000000..1abe835 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: sgd_winogrande_lora +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_prefix.yml new file mode 100644 index 0000000..c46b44e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: sgd_winogrande_prefix +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_prompt.yml new file mode 100644 index 0000000..ee45668 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: sgd_winogrande_prompt +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_ft.yml new file mode 100644 index 0000000..2851af7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sign_sgd_winogrande_ft +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_lora.yml new file mode 100644 index 0000000..662f40e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sign_sgd_winogrande_lora +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..dffb3ed --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sign_sgd_winogrande_prefix +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..41efc15 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sign_sgd_winogrande_prompt +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_ft.yml new file mode 100644 index 0000000..4fbbebe --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_ft +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_lora.yml new file mode 100644 index 0000000..b11c09d --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_adam_winogrande_lora +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_prefix.yml new file mode 100644 index 0000000..0916400 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_adam_winogrande_prefix +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_prompt.yml new file mode 100644 index 0000000..4486654 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_adam_winogrande_prompt +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_ft.yml new file mode 100644 index 0000000..c59c63b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_ft +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_lora.yml new file mode 100644 index 0000000..39f56b7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_lora +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..93c109d --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_winogrande_prefix +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..a6f951b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_winogrande_prompt +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml new file mode 100644 index 0000000..8847cac --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_winogrande_ft +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml new file mode 100644 index 0000000..bd652ee --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_winogrande_lora +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml new file mode 100644 index 0000000..d8f5a55 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_winogrande_prefix +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml new file mode 100644 index 0000000..e9a8355 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_conserv_winogrande_prompt +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml new file mode 100644 index 0000000..06647b1 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_winogrande_ft +project: zo_bench_winogrande_Llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml new file mode 100644 index 0000000..78163fe --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_winogrande_lora +project: zo_bench_winogrande_Llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml new file mode 100644 index 0000000..7960161 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml @@ -0,0 +1,59 @@ +name: zo_sgd_momen_winogrande_prefix +project: zo_bench_winogrande_Llama-2-13b +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=meta-llama/Llama-2-13b-hf" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml new file mode 100644 index 0000000..993fec2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml @@ -0,0 +1,57 @@ +name: zo_sgd_winogrande_prompt +project: zo_bench_winogrande_Llama-2-13b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-13b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_ft.yml new file mode 100644 index 0000000..b3a676b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: adam_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_lora.yml new file mode 100644 index 0000000..da9db8b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_lora.yml @@ -0,0 +1,46 @@ +name: adam_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_prefix.yml new file mode 100644 index 0000000..4e05beb --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: adam_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_prompt.yml new file mode 100644 index 0000000..f5d0593 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: adam_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_ft.yml new file mode 100644 index 0000000..921c7ca --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: forward_grad_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--save_model" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_lora.yml new file mode 100644 index 0000000..bb77e5b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_lora.yml @@ -0,0 +1,46 @@ +name: forward_grad_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_prefix.yml new file mode 100644 index 0000000..58c0da8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_prefix.yml @@ -0,0 +1,49 @@ +name: forward_grad_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_prompt.yml new file mode 100644 index 0000000..0083e4e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_prompt.yml @@ -0,0 +1,48 @@ +name: forward_grad_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_ft.yml new file mode 100644 index 0000000..daa5528 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: sgd_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_lora.yml new file mode 100644 index 0000000..91201f6 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: sgd_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +# - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_prefix.yml new file mode 100644 index 0000000..3d384a8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: sgd_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_prompt.yml new file mode 100644 index 0000000..1cd12e4 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: sgd_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_ft.yml new file mode 100644 index 0000000..e470262 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sign_sgd_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_lora.yml new file mode 100644 index 0000000..79dea02 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sign_sgd_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..94e66b9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sign_sgd_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..16eecae --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sign_sgd_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_ft.yml new file mode 100644 index 0000000..5a16cf9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_lora.yml new file mode 100644 index 0000000..117a986 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_adam_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_prefix.yml new file mode 100644 index 0000000..e4a2d6b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_adam_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_prompt.yml new file mode 100644 index 0000000..357e49c --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_adam_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_ft.yml new file mode 100644 index 0000000..bdded7e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_lora.yml new file mode 100644 index 0000000..c975b30 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +# - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..06c0b30 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..23df844 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml new file mode 100644 index 0000000..d84b839 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml new file mode 100644 index 0000000..d02a8de --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sgd_conserv_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml new file mode 100644 index 0000000..94591cf --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml new file mode 100644 index 0000000..6865205 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_conserv_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml new file mode 100644 index 0000000..c9675d8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_winogrande_ft +project: zo_bench_winogrande +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml new file mode 100644 index 0000000..9042937 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_winogrande_lora +project: zo_bench_winogrande +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml new file mode 100644 index 0000000..014357e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml @@ -0,0 +1,59 @@ +name: zo_sgd_momen_winogrande_prefix +project: zo_bench_winogrande +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=meta-llama/Llama-2-7b-hf" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml new file mode 100644 index 0000000..5b9dbfe --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml @@ -0,0 +1,57 @@ +name: zo_sgd_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=meta-llama/Llama-2-7b-hf" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_ft.yml new file mode 100644 index 0000000..e462268 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: adam_winogrande_ft +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_lora.yml new file mode 100644 index 0000000..41fcbe5 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_lora.yml @@ -0,0 +1,46 @@ +name: adam_winogrande_lora +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_prefix.yml new file mode 100644 index 0000000..f023e7c --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: adam_winogrande_prefix +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_prompt.yml new file mode 100644 index 0000000..5250452 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: adam_winogrande_prompt +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_ft.yml new file mode 100644 index 0000000..18687f4 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: forward_grad_winogrande_ft +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--save_model" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_lora.yml new file mode 100644 index 0000000..75bccde --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_lora.yml @@ -0,0 +1,46 @@ +name: forward_grad_winogrande_lora +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_prefix.yml new file mode 100644 index 0000000..bcc7bfd --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_prefix.yml @@ -0,0 +1,49 @@ +name: forward_grad_winogrande_prefix +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_prompt.yml new file mode 100644 index 0000000..a244f71 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_prompt.yml @@ -0,0 +1,48 @@ +name: forward_grad_winogrande_prompt +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_ft.yml new file mode 100644 index 0000000..c8bf0d2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: sgd_winogrande_ft +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_lora.yml new file mode 100644 index 0000000..49a1b77 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: sgd_winogrande_lora +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_prefix.yml new file mode 100644 index 0000000..2469527 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: sgd_winogrande_prefix +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_prompt.yml new file mode 100644 index 0000000..e7ddbb2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: sgd_winogrande_prompt +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_ft.yml new file mode 100644 index 0000000..8f9d1cf --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sign_sgd_winogrande_ft +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_lora.yml new file mode 100644 index 0000000..108df01 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sign_sgd_winogrande_lora +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..87b84e2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sign_sgd_winogrande_prefix +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..e07e155 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sign_sgd_winogrande_prompt +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_ft.yml new file mode 100644 index 0000000..79c1ba9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_ft +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_lora.yml new file mode 100644 index 0000000..7565ef0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_adam_winogrande_lora +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_prefix.yml new file mode 100644 index 0000000..d7a7237 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_adam_winogrande_prefix +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_prompt.yml new file mode 100644 index 0000000..75082b2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_adam_winogrande_prompt +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_ft.yml new file mode 100644 index 0000000..af52685 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_ft +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_lora.yml new file mode 100644 index 0000000..bf8e5d5 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_lora +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..4297833 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_winogrande_prefix +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..9169014 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_winogrande_prompt +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml new file mode 100644 index 0000000..1676743 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_winogrande_ft +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml new file mode 100644 index 0000000..e05479f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sgd_conserv_winogrande_lora +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml new file mode 100644 index 0000000..b7cfc97 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_winogrande_prefix +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml new file mode 100644 index 0000000..12461e2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_conserv_winogrande_prompt +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml new file mode 100644 index 0000000..2c1edbd --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_winogrande_ft +project: zo_bench_winogrande_mistral-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=mistralai/Mistral-7B-v0.1" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml new file mode 100644 index 0000000..ee32687 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_winogrande_lora +project: zo_bench_winogrande_mistral-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=mistralai/Mistral-7B-v0.1" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml new file mode 100644 index 0000000..4ea4e0c --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml @@ -0,0 +1,59 @@ +name: zo_sgd_momen_winogrande_prefix +project: zo_bench_winogrande_mistral-7b +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=mistralai/Mistral-7B-v0.1" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml new file mode 100644 index 0000000..d969d9f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml @@ -0,0 +1,57 @@ +name: zo_sgd_winogrande_prompt +project: zo_bench_winogrande_mistral-7b +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=mistralai/Mistral-7B-v0.1" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_ft.yml new file mode 100644 index 0000000..3bff140 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: adam_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_lora.yml new file mode 100644 index 0000000..2fdfc2f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_lora.yml @@ -0,0 +1,46 @@ +name: adam_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_prefix.yml new file mode 100644 index 0000000..859ea99 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: adam_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_prompt.yml new file mode 100644 index 0000000..5d9c6e7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: adam_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_ft.yml new file mode 100644 index 0000000..4d39550 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_ft.yml @@ -0,0 +1,48 @@ +name: forward_grad_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--save_model" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 5e-6 + - 1e-6 + - 5e-7 + - 1e-7 + - 5e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_lora.yml new file mode 100644 index 0000000..eb076f0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_lora.yml @@ -0,0 +1,46 @@ +name: forward_grad_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_prefix.yml new file mode 100644 index 0000000..6e0641f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_prefix.yml @@ -0,0 +1,49 @@ +name: forward_grad_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_prompt.yml new file mode 100644 index 0000000..6d0b33e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_prompt.yml @@ -0,0 +1,48 @@ +name: forward_grad_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_ft.yml new file mode 100644 index 0000000..a6820d2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: sgd_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_lora.yml new file mode 100644 index 0000000..a606117 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: sgd_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_prefix.yml new file mode 100644 index 0000000..c4fd1cc --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: sgd_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_prompt.yml new file mode 100644 index 0000000..eca6cdf --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: sgd_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_ft.yml new file mode 100644 index 0000000..501703f --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sign_sgd_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_lora.yml new file mode 100644 index 0000000..745e665 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sign_sgd_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..2fa9b2c --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sign_sgd_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..2b4e2ab --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sign_sgd_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_ft.yml new file mode 100644 index 0000000..d899d1b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_lora.yml new file mode 100644 index 0000000..b581d18 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_adam_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_prefix.yml new file mode 100644 index 0000000..b4ada6e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_adam_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_prompt.yml new file mode 100644 index 0000000..c949924 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_adam_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_ft.yml new file mode 100644 index 0000000..5841e6d --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_ft.yml @@ -0,0 +1,52 @@ +name: zo_sgd_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-1.3b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_lora.yml new file mode 100644 index 0000000..ca25aa2 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..2eed983 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..6856db1 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml new file mode 100644 index 0000000..fb8c522 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_winogrande_ft +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml new file mode 100644 index 0000000..9eaa787 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sgd_conserv_winogrande_lora +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml new file mode 100644 index 0000000..6286ac4 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_winogrande_prefix +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml new file mode 100644 index 0000000..5fc07ae --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_conserv_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml new file mode 100644 index 0000000..8128cb0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_winogrande_ft +project: zo_bench_winogrande +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=facebook/opt-13b" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml new file mode 100644 index 0000000..cb3bd81 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_winogrande_lora +project: zo_bench_winogrande +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=facebook/opt-13b" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml new file mode 100644 index 0000000..c0b6d65 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml @@ -0,0 +1,59 @@ +name: zo_sgd_momen_winogrande_prefix +project: zo_bench_winogrande +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=facebook/opt-13b" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml new file mode 100644 index 0000000..86d72a9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml @@ -0,0 +1,57 @@ +name: zo_sgd_momen_winogrande_prompt +project: zo_bench_winogrande +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=facebook/opt-13b" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_ft.yml new file mode 100644 index 0000000..9cb4824 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: adam_winogrande_ft +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_lora.yml new file mode 100644 index 0000000..7fa0413 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: adam_winogrande_lora +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +# - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_prefix.yml new file mode 100644 index 0000000..ed11c19 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: adam_winogrande_prefix +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_prompt.yml new file mode 100644 index 0000000..debbf72 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: adam_winogrande_prompt +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_ft.yml new file mode 100644 index 0000000..02a1fec --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: forward_grad_winogrande_ft +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--save_model" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_lora.yml new file mode 100644 index 0000000..a75a60e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: forward_grad_winogrande_lora +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +# - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_prefix.yml new file mode 100644 index 0000000..ad899ce --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_prefix.yml @@ -0,0 +1,49 @@ +name: forward_grad_winogrande_prefix +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_prompt.yml new file mode 100644 index 0000000..e0d7819 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_prompt.yml @@ -0,0 +1,48 @@ +name: forward_grad_winogrande_prompt +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=forward_grad" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--optimizer=sgd" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_ft.yml new file mode 100644 index 0000000..313939b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_ft.yml @@ -0,0 +1,47 @@ +name: sgd_winogrande_ft +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_lora.yml new file mode 100644 index 0000000..31edee9 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_lora.yml @@ -0,0 +1,47 @@ +name: sgd_winogrande_lora +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +# - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_prefix.yml new file mode 100644 index 0000000..81b4bfb --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_prefix.yml @@ -0,0 +1,50 @@ +name: sgd_winogrande_prefix +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_prompt.yml new file mode 100644 index 0000000..5f3c7c7 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_prompt.yml @@ -0,0 +1,49 @@ +name: sgd_winogrande_prompt +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=regular" + - "--optimizer=sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-2 + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_ft.yml new file mode 100644 index 0000000..951d49b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sign_sgd_winogrande_ft +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_lora.yml new file mode 100644 index 0000000..77f7bb8 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_lora.yml @@ -0,0 +1,50 @@ +name: zo_sign_sgd_winogrande_lora +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..f110d86 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sign_sgd_winogrande_prefix +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..a431be5 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sign_sgd_winogrande_prompt +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sign_opt" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_ft.yml new file mode 100644 index 0000000..cd50ea4 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_ft +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_lora.yml new file mode 100644 index 0000000..a705a51 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_adam_winogrande_lora +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +# - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_prefix.yml new file mode 100644 index 0000000..37cc387 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_adam_winogrande_prefix +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_prompt.yml new file mode 100644 index 0000000..7e4156b --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_adam_winogrande_prompt +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_adam" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_ft.yml new file mode 100644 index 0000000..3c73634 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_ft +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_lora.yml new file mode 100644 index 0000000..251311e --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_winogrande_lora +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +# - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_prefix.yml new file mode 100644 index 0000000..d4f1dc6 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_winogrande_prefix +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_prompt.yml new file mode 100644 index 0000000..04dc2d0 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_winogrande_prompt +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml new file mode 100644 index 0000000..70cf107 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_winogrande_ft +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml new file mode 100644 index 0000000..e33bc8a --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml @@ -0,0 +1,51 @@ +name: zo_sgd_conserv_winogrande_lora +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--lora" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" +# - "--load_float16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml new file mode 100644 index 0000000..bd4667d --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml @@ -0,0 +1,54 @@ +name: zo_sgd_conserv_winogrande_prefix +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prefix_tuning" + - "--num_prefix=5" + - "--no_reparam" + - "--prefix_init_by_real_act" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml new file mode 100644 index 0000000..a3c0225 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml @@ -0,0 +1,53 @@ +name: zo_sgd_conserv_winogrande_prompt +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_conserv" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_bfloat16" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml new file mode 100644 index 0000000..3593fa6 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_winogrande_ft +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: +- ${interpreter} +- ${program} +- ${args} +- "--model_name=lmsys/vicuna-7b-v1.5" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + - 1e-8 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml new file mode 100644 index 0000000..7882aa5 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml @@ -0,0 +1,55 @@ +name: zo_sgd_momen_winogrande_lora +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: +- ${interpreter} +- ${program} +- ${args} +- "--lora" +- "--model_name=lmsys/vicuna-7b-v1.5" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml new file mode 100644 index 0000000..3da5617 --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml @@ -0,0 +1,59 @@ +name: zo_sgd_momen_winogrande_prefix +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: +- ${interpreter} +- ${program} +- ${args} +- "--prefix_tuning" +- "--num_prefix=5" +- "--no_reparam" +- "--prefix_init_by_real_act" +- "--model_name=lmsys/vicuna-7b-v1.5" +- "--task_name=WinoGrande" +- "--output_dir=result/WinoGrande-ft-$TAG" +- "--num_train_epochs=5" +- "--no_reparam" +- "--per_device_train_batch_size=16" +- "--load_best_model_at_end" +- "--evaluation_strategy=steps" +- "--save_strategy=steps" +- "--save_total_limit=1" +- "--eval_steps=500" +- "--max_steps=20000" +- "--logging_steps=10" +- "--num_eval=1000" +- "--num_train=1000" +- "--num_dev=100" +- "--train_as_classification=False" +- "--perturbation_mode=two_side" +- "--trainer=zo_sgd" +- "--train_set_seed=0" +- "--lr_scheduler_type=constant" +- "--save_steps=500" +- "--load_float16" +- "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + - 1e-7 + zo_eps: + values: + - 1e-3 + - 1e-4 + - 1e-5 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml new file mode 100644 index 0000000..26c239a --- /dev/null +++ b/baselines/agzo/zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml @@ -0,0 +1,57 @@ +name: zo_sgd_winogrande_prompt +project: zo_bench_winogrande_vicuna-7b-v1.5 +command: + - ${interpreter} + - ${program} + - ${args} + - "--prompt_tuning" + - "--num_virtual_tokens=10" + - "--prompt_init_by_real_tokens" + - "--model_name=lmsys/vicuna-7b-v1.5" + - "--task_name=WinoGrande" + - "--output_dir=result/WinoGrande-ft-$TAG" + - "--num_train_epochs=5" + - "--no_reparam" + - "--per_device_train_batch_size=16" + - "--load_best_model_at_end" + - "--evaluation_strategy=steps" + - "--save_strategy=steps" + - "--save_total_limit=1" + - "--eval_steps=500" + - "--max_steps=20000" + - "--logging_steps=10" + - "--num_eval=1000" + - "--num_train=1000" + - "--num_dev=100" + - "--train_as_classification=False" + - "--perturbation_mode=two_side" + - "--trainer=zo_sgd" + - "--train_set_seed=0" + - "--lr_scheduler_type=constant" + - "--save_steps=500" + - "--load_float16" + - "--save_model" +method: grid +metric: + goal: maximize + name: test_acc +parameters: + learning_rate: + values: + - 1e-3 + - 1e-4 + - 1e-5 + - 1e-6 + zo_eps: + values: + - 1e-2 + - 1e-3 + - 1e-4 + momentum: + values: + - 0.9 + weight_decay: + values: + - 0 + +program: run.py \ No newline at end of file diff --git a/baselines/agzo/zo-bench/tasks.py b/baselines/agzo/zo-bench/tasks.py new file mode 100644 index 0000000..0824d35 --- /dev/null +++ b/baselines/agzo/zo-bench/tasks.py @@ -0,0 +1,501 @@ +import logging +import sys +from dataclasses import dataclass +from typing import List, Union + +import numpy as np +from datasets import load_dataset +from datasets import load_from_disk +import os +import glob + +from templates import * +from utils import temp_seed + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +def safe_load_dataset(name, *args, **kwargs): + """ + Try to load a dataset from the Hub, but on network failure try loading from a local disk cache + at ./data/{name}/{config} or ./data/{name}. + """ + try: + return load_dataset(name, *args, **kwargs) + except Exception as e: + logger.warning("Failed to download dataset %s (%s). Attempting to load from local disk cache.", name, e) + # Try a few sensible local paths + subset = args[0] if len(args) > 0 else kwargs.get("name") or kwargs.get("subset") + candidates = [] + if subset: + candidates.append(f"./data/{name}/{subset}") + candidates.append(f"./data/{name}-{subset}") + candidates.append(f"./data/{name}") + for p in candidates: + try: + logger.info("Trying local dataset path: %s", p) + return load_from_disk(p) + except Exception: + continue + # Try HuggingFace local cache paths (~/.cache/huggingface/datasets or HF_DATASETS_CACHE) + hf_cache = os.environ.get("HF_DATASETS_CACHE") or os.path.expanduser("~/.cache/huggingface/datasets") + try: + pattern = os.path.join(hf_cache, f"**/{name}*", "*") + for candidate in glob.glob(pattern, recursive=True): + try: + logger.info("Trying HF cache dataset path: %s", candidate) + return load_from_disk(candidate) + except Exception: + continue + except Exception: + pass + # nothing worked, re-raise the original exception for visibility + raise + + +def get_task(task_name): + aa = task_name.split("__") + if len(aa) == 2: + task_group, subtask = aa + else: + task_group = aa[0] + subtask = None + class_ = getattr(sys.modules[__name__], f"{task_group}Dataset") + instance = class_(subtask) + return instance + + +@dataclass +class Sample: + id: int = None + data: dict = None + correct_candidate: Union[str, List[str]] = None + candidates: List[str] = None + + +class Dataset: + mixed_set = False + train_sep = "\n\n" + generation = False # whether this is a generation task + + def __init__(self, subtask=None, **kwargs) -> None: + self.samples = None + self.subtask = subtask + + def get_task_name(self): + return self.subtask + + def load_dataset(self, path, **kwargs): + raise NotImplementedError + + def get_template(self, template_version=0): + templates = {0: Template} + return templates[template_version] + + def build_sample(self, example): + return + + def sample_train_sets(self, num_train=32, num_dev=None, num_eval=None, num_train_sets=None, seed=None): + if seed is not None: + # one train/demo set using the designated seed + seeds = [seed] + elif num_train_sets is not None: + # num_train_sets train/demo sets + seeds = list(range(num_train_sets)) + else: + # one train/demo set per evaluation sample + assert num_dev is None # not supported + len_valid_samples = len(self.samples["valid"]) if num_eval is None else num_eval + with temp_seed(0): + seeds = np.random.randint(0, 10000, len_valid_samples) + + train_samples = [] + for i, set_seed in enumerate(seeds): + if self.mixed_set: # This is always False for now + raise NotImplementedError + train_samples.append(self.sample_subset(data_split="valid", seed=set_seed, num=num_train, exclude=i)) + else: + if num_dev is not None: + train_samples.append(self.sample_subset(data_split="train", seed=set_seed, + num=num_train + num_dev)) # dev set is included at the end of train set + if num_train + num_dev > len(self.samples["train"]): + logger.warn("num_train + num_dev > available training examples") + else: + train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train)) + if num_dev is not None: + logger.info(f"Sample train set {len(train_samples[-1])}/{len(self.samples['train'])}") + logger.info(f"... including dev set {num_dev} samples") + return train_samples + + def sample_subset(self, data_split="train", seed=0, num=100, exclude=None): + with temp_seed(seed): + samples = self.samples[data_split] + lens = len(samples) + index = np.random.permutation(lens).tolist()[:num if exclude is None else num + 1] + if exclude is not None and exclude in index: + index.remove(exclude) + else: + index = index[:num] + return [samples[i] for i in index] + + @property + def valid_samples(self): + return self.samples["valid"] + + +class SST2Dataset(Dataset): + train_sep = "\n\n" + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = safe_load_dataset('glue', 'sst2') + train_d = d["train"] + validation_d = d["validation"] + + train_samples = [self.build_sample(example) for example in train_d] + valid_samples = [self.build_sample(example) for example in validation_d] + + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example): + label = int(example["label"]) + return Sample(id=example["idx"], data=example, correct_candidate=label, candidates=[0, 1]) + + def get_template(self, template_version=0): + return {0: SST2Template, 1: SST2TemplateEmpty}[template_version]() + + +class CopaDataset(Dataset): + train_sep = "\n\n" + mixed_set = False + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = safe_load_dataset('super_glue', "copa") + train_examples = d["train"] + valid_examples = d["validation"] + + train_samples = [self.build_sample(example) for example in train_examples] + valid_samples = [self.build_sample(example) for example in valid_examples] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example): + sample = \ + Sample( + id=example["idx"], + data=example, + candidates=[example["choice1"], example["choice2"]], + correct_candidate=example[f"choice{example['label'] + 1}"], + ) + + return sample + + def get_template(self, template_version=0): + return {0: CopaTemplate, 1: CopaTemplateEmpty}[template_version]() + + +class BoolQDataset(Dataset): + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = safe_load_dataset("boolq") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=["Yes", "No"], + correct_candidate="Yes" if example["answer"] else "No", + ) + + return sample + + def get_template(self, template_version=2): + return {0: BoolQTemplate, 1: BoolQTemplateV2, 2: BoolQTemplateV3}[template_version]() + + +class MultiRCDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = safe_load_dataset("super_glue", "multirc") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: MultiRCTemplate}[template_version]() + + +class CBDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = safe_load_dataset("super_glue", "cb") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1, 2], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: CBTemplate}[template_version]() + + +class WICDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = safe_load_dataset("super_glue", "wic") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: WICTemplate}[template_version]() + + +class WSCDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = safe_load_dataset("super_glue", "wsc.fixed") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: WSCTemplate}[template_version]() + + +class ReCoRDDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = safe_load_dataset("super_glue", "record") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=example['entities'], + correct_candidate=example['answers'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: ReCoRDTemplateGPT3}[template_version]() + + +class RTEDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = safe_load_dataset("super_glue", "rte") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: RTETemplate, 1: RTETemplateEmpty}[template_version]() + + +class SQuADDataset(Dataset): + metric_name = "f1" + generation = True + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset() + + def load_dataset(self): + dataset = safe_load_dataset("squad") + train_examples = dataset["train"] + valid_examples = dataset["validation"] + + train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)] + valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example, idx): + answers = example['answers']['text'] + assert len(answers) > 0 + return Sample( + id=idx, + data={ + "title": example['title'], + "context": example['context'], + "question": example['question'], + "answers": answers + }, + candidates=None, + correct_candidate=answers + ) + + def get_template(self, template_version=0): + return {0: SQuADv2Template}[template_version]() + + +class DROPDataset(Dataset): + metric_name = "f1" + generation = True + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset() + + def load_dataset(self): + dataset = safe_load_dataset("drop") + train_examples = dataset["train"] + valid_examples = dataset["validation"] + + train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)] + valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example, idx): + answers = example['answers_spans']['spans'] + assert len(answers) > 0 + return Sample( + id=idx, + data={ + "context": example['passage'], + "question": example['question'], + "answers": answers + }, + candidates=None, + correct_candidate=answers + ) + + def get_template(self, template_version=0): + return {0: DROPTemplate}[template_version]() + + +class WinoGrandeDataset(Dataset): + def __init__(self, subtask=None, **kwargs) -> None: + super().__init__(subtask, **kwargs) + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = safe_load_dataset('winogrande', 'winogrande_m') + train_set = d['train'] if 'train' in d else safe_load_dataset('winogrande', 'winogrande_m', split='train') + valid_set = d['validation'] if 'validation' in d else safe_load_dataset('winogrande', 'winogrande_m', split='validation') + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + """ + Prompt adapted from https://arxiv.org/pdf/2110.08207.pdf + """ + sentence = example["sentence"] + context, target = sentence.split("_") + sample = Sample( + data=example, + candidates=[example['option1'] + target, example['option2'] + target], + correct_candidate=example[f'option{example["answer"]}'] + target, + ) + return sample + + def get_template(self, template_version=0): + if template_version == 0: + return WinoGrandeTemplate() + else: + raise NotImplementedError(f"Template version {template_version} not implemented for WinoGrande") diff --git a/baselines/agzo/zo-bench/templates.py b/baselines/agzo/zo-bench/templates.py new file mode 100644 index 0000000..51f2df5 --- /dev/null +++ b/baselines/agzo/zo-bench/templates.py @@ -0,0 +1,499 @@ +class Template: + def encode(self, sample): + """ + Return prompted version of the example (without the answer/candidate) + """ + raise NotImplementedError + + def verbalize(self, sample, candidate): + """ + Return the prompted version of the example (with the answer/candidate) + """ + return candidate + + def encode_sfc(self, sample): + """ + Same as encode, but for SFC (calibration) -- this usually means the input is not included + """ + return "" + + def verbalize_sfc(self, sample, candidate): + """ + Same as verbalize, but for SFC (calibration) -- this usually means the input is not included + """ + return candidate + + +class SST2Template(Template): + verbalizer = {0: "terrible", 1: "great"} + + def encode(self, sample): + text = sample.data["sentence"].strip() + return f"{text} It was" + + def verbalize(self, sample, candidate): + text = sample.data["sentence"].strip() + return f"{text} It was {self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f" It was" + + def verbalize_sfc(self, sample, candidate): + return f" It was {self.verbalizer[candidate]}" + +class SST2TemplateEmpty(Template): + verbalizer = {0: "terrible", 1: "great"} + + def encode(self, sample): + text = sample.data["sentence"].strip() + return f"{text} " + + def verbalize(self, sample, candidate): + text = sample.data["sentence"].strip() + return f"{text} {self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f" " + + def verbalize_sfc(self, sample, candidate): + return f" {self.verbalizer[candidate]}" + + +class CopaTemplate(Template): + capitalization: str = "correct" + effect_conj: str = " so " + cause_conj: str = " because " + + def get_conjucture(self, sample): + if sample.data["question"] == "effect": + conjunction = self.effect_conj + elif sample.data["question"] == "cause": + conjunction = self.cause_conj + else: + raise NotImplementedError + return conjunction + + def get_prompt(self, sample): + premise = sample.data["premise"].rstrip() + if premise.endswith("."): # TODO Add other scripts with different punctuation + premise = premise[:-1] + conjunction = self.get_conjucture(sample) + prompt = premise + conjunction + if self.capitalization == "upper": + prompt = prompt.upper() + elif self.capitalization == "lower": + prompt = prompt.lower() + return prompt + + def encode(self, sample): + prompt = self.get_prompt(sample) + return prompt + + def capitalize(self, c): + if self.capitalization == "correct": + words = c.split(" ") + if words[0] != "I": + words[0] = words[0].lower() + return " ".join(words) + elif self.capitalization == "bug": + return c + elif self.capitalization == "upper": + return c.upper() + elif self.capitalization == "lower": + return c.lower() + else: + raise NotImplementedError + + def verbalize(self, sample, candidate): + prompt = self.get_prompt(sample) + return prompt + self.capitalize(candidate) + + def encode_sfc(self, sample): + conjunction = self.get_conjucture(sample) + return conjunction.strip() + + def verbalize_sfc(self, sample, candidate): + conjunction = self.get_conjucture(sample) + sfc_prompt = conjunction.strip() + " " + self.capitalize(candidate) + return sfc_prompt + + +class CopaTemplateEmpty(Template): + capitalization: str = "correct" + effect_conj: str = " " + cause_conj: str = " " + + def get_conjucture(self, sample): + if sample.data["question"] == "effect": + conjunction = self.effect_conj + elif sample.data["question"] == "cause": + conjunction = self.cause_conj + else: + raise NotImplementedError + return conjunction + + def get_prompt(self, sample): + premise = sample.data["premise"].rstrip() + if premise.endswith("."): # TODO Add other scripts with different punctuation + premise = premise[:-1] + conjunction = self.get_conjucture(sample) + prompt = premise + conjunction + if self.capitalization == "upper": + prompt = prompt.upper() + elif self.capitalization == "lower": + prompt = prompt.lower() + return prompt + + def encode(self, sample): + prompt = self.get_prompt(sample) + return prompt + + def capitalize(self, c): + if self.capitalization == "correct": + words = c.split(" ") + if words[0] != "I": + words[0] = words[0].lower() + return " ".join(words) + elif self.capitalization == "bug": + return c + elif self.capitalization == "upper": + return c.upper() + elif self.capitalization == "lower": + return c.lower() + else: + raise NotImplementedError + + def verbalize(self, sample, candidate): + prompt = self.get_prompt(sample) + return prompt + self.capitalize(candidate) + + def encode_sfc(self, sample): + conjunction = self.get_conjucture(sample) + return conjunction.strip() + + def verbalize_sfc(self, sample, candidate): + conjunction = self.get_conjucture(sample) + sfc_prompt = conjunction.strip() + " " + self.capitalize(candidate) + return sfc_prompt + + +class BoolQTemplate(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question} {candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class BoolQTemplateV2(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\\n\\n" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\\n\\n{candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class BoolQTemplateV3(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\n" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\n{candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class MultiRCTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + paragraph = sample.data["paragraph"] + question = sample.data["question"] + answer = sample.data["answer"] + return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n" + + def verbalize(self, sample, candidate): + paragraph = sample.data["paragraph"] + question = sample.data["question"] + answer = sample.data["answer"] + return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class CBTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "Yes", 1: "No", 2: "Maybe"} + + def encode(self, sample): + premise = sample.data["premise"] + hypothesis = sample.data["hypothesis"] + return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n" + + def verbalize(self, sample, candidate): + premise = sample.data["premise"] + hypothesis = sample.data["hypothesis"] + return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class WICTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + sent1 = sample.data["sentence1"] + sent2 = sample.data["sentence2"] + word = sample.data["word"] + return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n" + + def verbalize(self, sample, candidate): + sent1 = sample.data["sentence1"] + sent2 = sample.data["sentence2"] + word = sample.data["word"] + return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class WSCTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + text = sample.data['text'] + span1 = sample.data['span1_text'] + span2 = sample.data['span2_text'] + return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n" + + def verbalize(self, sample, candidate): + text = sample.data['text'] + span1 = sample.data['span1_text'] + span2 = sample.data['span2_text'] + return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class ReCoRDTemplate(Template): + # From PromptSource 1 but modified + + def encode(self, sample): + passage = sample.data['passage'] + query = sample.data['query'] + return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer:" + + def verbalize(self, sample, candidate): + passage = sample.data['passage'] + query = sample.data['query'] + return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}" + + def encode_sfc(self, sample): + return f"Answer:" + + def verbalize_sfc(self, sample, candidate): + return f"Answer: {candidate}" + + +class ReCoRDTemplateGPT3(Template): + # From PromptSource 1 but modified + + def encode(self, sample): + passage = sample.data['passage'].replace("@highlight\n", "- ") + return f"{passage}\n-" + + def verbalize(self, sample, candidate): + passage = sample.data['passage'].replace("@highlight\n", "- ") + query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate) + return f"{passage}\n- {query}" + + # passage = sample.data['passage'] + # query = sample.data['query'] + # return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}" + + def encode_sfc(self, sample): + return f"-" + + def verbalize_sfc(self, sample, candidate): + query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate) + return f"- {query}" + + +class RTETemplate(Template): + # From PromptSource 1 + verbalizer = {0: "Yes", 1: "No"} + + def encode(self, sample): + premise = sample.data['premise'] + hypothesis = sample.data['hypothesis'] + return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n" + + def verbalize(self, sample, candidate): + premise = sample.data['premise'] + hypothesis = sample.data['hypothesis'] + return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + +class RTETemplateEmpty(Template): + # From PromptSource 1 + verbalizer = {0: "Yes", 1: "No"} + + def encode(self, sample): + premise = sample.data['premise'] + hypothesis = sample.data['hypothesis'] + return f"{premise}\n\"{hypothesis}\"\n" + + def verbalize(self, sample, candidate): + premise = sample.data['premise'] + hypothesis = sample.data['hypothesis'] + return f"{premise}\n\"{hypothesis}\"\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class SQuADv2Template(Template): + + def encode(self, sample): + question = sample.data['question'].strip() + title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer:" + + def verbalize(self, sample, candidate): + question = sample.data['question'].strip() + title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer: {answer}\n" + + def encode_sfc(self, sample): + raise NotImplementedError + + def verbalize_sfc(self, sample, candidate): + raise NotImplementedError + + +class DROPTemplate(Template): + + def encode(self, sample): + question = sample.data['question'].strip() + # title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Passage: {context}\nQuestion: {question}\nAnswer:" + + def verbalize(self, sample, candidate): + question = sample.data['question'].strip() + # title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Passage: {context}\nQuestion: {question}\nAnswer: {answer}\n" + + def encode_sfc(self, sample): + raise NotImplementedError + + def verbalize_sfc(self, sample, candidate): + raise NotImplementedError + + +class WinoGrandeTemplate(Template): + @staticmethod + def get_prompt(sample): + """ + Prompt adapted from https://arxiv.org/pdf/2110.08207.pdf + """ + sentence = sample.data["sentence"] + context, target = sentence.split("_") + return context + + def encode(self, sample): + prompt = self.get_prompt(sample) + return prompt + + def verbalize(self, sample, candidate): + prompt = self.get_prompt(sample) + return prompt + candidate + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate diff --git a/baselines/agzo/zo-bench/test_fake_text_memory.py b/baselines/agzo/zo-bench/test_fake_text_memory.py new file mode 100644 index 0000000..1a295d9 --- /dev/null +++ b/baselines/agzo/zo-bench/test_fake_text_memory.py @@ -0,0 +1,256 @@ +# -*- coding: utf-8 -*- +# @Author: pingzhili +# @Time: 2024/2/8 +import numpy as np +import torch +import npu_compat as npu +from fire import Fire +from torch.optim import SGD +from transformers import AutoModelForCausalLM + +zo_eps = 1e-3 + + +def zo_perturb_parameters(named_parameters_to_optim, random_seed=None, scaling_factor=1): + """ + Perturb the parameters with random vector z. + Input: + - random_seed: random seed for MeZO in-place perturbation (if it's None, we will use self.zo_random_seed) + - scaling_factor: theta = theta + scaling_factor * z * eps + """ + + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(random_seed if random_seed is not None else 0) + + for _, param in named_parameters_to_optim: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * zo_eps + + +def zo_forward(model, inputs): + """ + Get (no gradient) loss from the model. Dropout is turned off too. + """ + model.eval() + with torch.inference_mode(): + input_ids = inputs["input_ids"] + + # Prepare labels for loss calculation (shifted input ids) + labels = input_ids.clone() + labels[:, :-1] = labels[:, 1:].clone() + labels[:, -1] = -100 # We don't need to compute loss for the last token + + # Step 5: Perform a forward pass and compute loss + outputs = model(input_ids=input_ids, labels=labels) + loss = outputs.loss + return loss.detach() + + +@torch.no_grad() +def zo_step(model, inputs, optimizer, is_sign_opt=False): + """ + Estimate gradient by MeZO. Return the loss from f(theta + z) + """ + named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + named_parameters_to_optim.append((name, param)) + # # TODO avoid init the memory for grad. + # param.grad = torch.zeros_like(param.data) + param.grad = None # Make sure the grad is empty and will not be updated. + + # Sample the random seed for sampling z + zo_random_seed = np.random.randint(1000000000) + + # First function evaluation + zo_perturb_parameters(named_parameters_to_optim, scaling_factor=1) + loss1 = zo_forward(model, inputs) + + # Second function evaluation + zo_perturb_parameters(named_parameters_to_optim, scaling_factor=-2) + loss2 = zo_forward(model, inputs) + projected_grad = ((loss1 - loss2) / (2 * zo_eps)).item() + + # Reset model back to its parameters at start of step + zo_perturb_parameters(named_parameters_to_optim, scaling_factor=1) + + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(zo_random_seed) + for name, param in named_parameters_to_optim: + # Resample z + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, + dtype=param.data.dtype) + + if is_sign_opt: + # ----signOpt_orig + # TODo why do we multiply lr here? We will multiply lr twice? + graddiff_times_z = np.sign(projected_grad) * z + # ----signOpt_mul_sign + # graddiff_times_z = self._get_learning_rate() * torch.sign(self.projected_grad * z) + else: + # ----mezo original + graddiff_times_z = projected_grad * z + + # param.grad += graddiff_times_z.detach() + # more mem-efficient: + # run optimizer.step here to avoid caching all grad. + param.grad = graddiff_times_z + optimizer.step() # will only update grad that is not None. + # param.data = param.data - graddiff_times_z / args.q # NOTE this q division does not work for q>1. + param.grad = None # avoid further update. + + return loss1 + + +def fo_step(model, inputs, optimizer): + input_ids = inputs["input_ids"] + + # Prepare labels for loss calculation (shifted input ids) + labels = input_ids.clone() + labels[:, :-1] = labels[:, 1:].clone() + labels[:, -1] = -100 # We don't need to compute loss for the last token + + # Perform a forward pass and compute loss + outputs = model(input_ids=input_ids, labels=labels) + loss = outputs.loss + + # first order step + loss.backward() + optimizer.step() + model.no_grad() + return loss.detach() + + +from functools import partial +from torch.func import functional_call, jvp + +lr = 1e-6 + + +# @staticmethod +@torch.no_grad() +def functional_call_loss(params, names, buffers, model, batch): + params = {k: v for k, v in zip(names, params)} + outputs = functional_call(model, (params, buffers), tuple(), kwargs=batch) + return outputs[0] # only need the loss + # return outputs + + +def forward_gradient_step(model, inputs, optimizer): + named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + named_parameters_to_optim.append((name, param)) + param.grad = None + # this is not memory efficient. + # param.grad = torch.zeros_like(param.data) + + # Sample the random seed for sampling vs + zo_random_seed = np.random.randint(1000000000) + torch.manual_seed(zo_random_seed) + + cur_mem = npu.max_memory_allocated() / (1024 ** 3) + + loss = 0 + print(f"Init MEM: {cur_mem:.2f} GB") + vs = [torch.randn_like(p) for _, p in named_parameters_to_optim] + + # fixme: this is a workaround for device map error when using jvp + inputs = { + k: v.to(device=model.device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items() + } + f = partial( + functional_call_loss, + names=[n for n, _ in named_parameters_to_optim], buffers=dict(model.named_buffers()), + model=model, batch=inputs + ) + print(f"MEM increase for vs: {npu.max_memory_allocated() / 1024 ** 3 - cur_mem:.2f} GB") + cur_mem = npu.max_memory_allocated() / 1024 ** 3 + + # jvp profiling + loss_, jvp_ = jvp(f, (list([p for _, p in named_parameters_to_optim]),), (vs,)) + + print(f"MEM increase for jvp: {npu.max_memory_allocated() / 1024 ** 3 - cur_mem:.2f} GB") + + if isinstance(jvp_, tuple): + jvp_ = jvp_[0] + print("WARNING: jvp return useless tensors, which may consume a lot of memory.") + with torch.no_grad(): + for v, (n, p) in zip(vs, named_parameters_to_optim): + p.data.sub_(lr * (v * jvp_.to(p.device))) + loss += loss_.item() + + return torch.tensor(loss) + + +def main_test( + batch_size: int, + sequence_length: int, + use_amp: bool = False, + load_float16: bool = True, +): + model_name = "facebook/opt-13b" + model = AutoModelForCausalLM.from_pretrained( + model_name, + device_map="auto", + torch_dtype=torch.float16 if load_float16 else torch.float32, + ) + + max_memory_allocated = 0 + for device_id in range(npu.device_count()): + max_memory_allocated += npu.max_memory_allocated(device_id) + print(f"[bsz={batch_size} | seq_len={sequence_length}]" + f"init peak mem (model weight): {max_memory_allocated / 1024 ** 3:.2f} GB") + + scaler = npu.amp_grad_scaler(enabled=use_amp) + optimizer = SGD(model.parameters(), lr=1e-5) # , momentum=0.9) + + # Step 4: Preprocess the input + # text = "Replace this with your text." + inputs = { + "input_ids": npu.to_device(torch.randint(5000, 10000, (batch_size, sequence_length), dtype=torch.long)), + "attention_mask": npu.to_device(torch.zeros(batch_size, sequence_length, dtype=torch.long)) + } + for _ in range(1): + for device_id in range(npu.device_count()): + npu.reset_max_memory_allocated(device_id) + # loss = zo_step(model, inputs, optimizer) + with npu.autocast(dtype=torch.float16, enabled=use_amp): + input_ids = inputs["input_ids"] + labels = input_ids.clone() + labels[:, :-1] = labels[:, 1:].clone() + labels[:, -1] = -100 # We don't need to compute loss for the last token + outputs = model(input_ids=input_ids, labels=labels) + loss = outputs.loss + + max_memory_allocated = 0 + for device_id in range(npu.device_count()): + max_memory_allocated += npu.max_memory_allocated(device_id) + print(f"[bsz={batch_size} | seq_len={sequence_length}]" + f"step peak mem (during fwd): {max_memory_allocated / 1024 ** 3:.2f} GB") + for device_id in range(npu.device_count()): + npu.reset_max_memory_allocated(device_id) + + scaler.scale(loss).backward() + + max_memory_allocated = 0 + for device_id in range(npu.device_count()): + max_memory_allocated += npu.max_memory_allocated(device_id) + print(f"[bsz={batch_size} | seq_len={sequence_length}]" + f"step peak mem (during bwd): {max_memory_allocated / 1024 ** 3:.2f} GB") + for device_id in range(npu.device_count()): + npu.reset_max_memory_allocated(device_id) + + scaler.step(optimizer) + scaler.update() + optimizer.zero_grad() + + max_memory_allocated = 0 + for device_id in range(npu.device_count()): + max_memory_allocated += npu.max_memory_allocated(device_id) + print(f"[bsz={batch_size} | seq_len={sequence_length}]" + f"step peak mem (during optim): {max_memory_allocated / 1024 ** 3:.2f} GB") + + +if __name__ == "__main__": + Fire(main_test) diff --git a/baselines/agzo/zo-bench/trainer.py b/baselines/agzo/zo-bench/trainer.py new file mode 100644 index 0000000..ad5943e --- /dev/null +++ b/baselines/agzo/zo-bench/trainer.py @@ -0,0 +1,2140 @@ +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. +""" + +import inspect +import math +import os +import re +import shutil +import sys +import time +from functools import partial +from pathlib import Path +from typing import Dict, Union, Any +from typing import TYPE_CHECKING, Optional, Iterable +import json +import numpy as np +import torch +import torch.distributed as dist +from packaging import version +from sklearn.linear_model import LogisticRegressionCV +from torch import nn +from torch.func import functional_call, jvp +from torch.optim import SGD, Adam +from torch.utils.data import DataLoader, RandomSampler +from torch.utils.data.distributed import DistributedSampler +from tqdm.auto import tqdm +from transformers import Trainer +from transformers.debug_utils import DebugOption, DebugUnderflowOverflow +try: + from transformers.deepspeed import deepspeed_init, is_deepspeed_zero3_enabled +except ModuleNotFoundError: + from transformers.integrations.deepspeed import deepspeed_init, is_deepspeed_zero3_enabled +from transformers.dependency_versions_check import dep_version_check +# Integrations must be imported before ML frameworks: +from transformers.integrations import ( # isort: split + hp_params, +) +try: + from transformers.integrations import is_fairscale_available +except ImportError: + import importlib.util + + + def is_fairscale_available(): + return importlib.util.find_spec("fairscale") is not None +from transformers.trainer_callback import ( + DefaultFlowCallback, + ProgressCallback, + TrainerState, +) +from transformers.trainer_pt_utils import ( + IterableDatasetShard, +) +from transformers.trainer_utils import ( + IntervalStrategy, + HPSearchBackend, + TrainOutput, + has_length, + speed_metrics, +) +try: + from transformers.trainer_utils import ShardedDDPOption +except ImportError: + + class ShardedDDPOption: + SIMPLE = "simple" + ZERO_DP_2 = "zero_dp_2" + ZERO_DP_3 = "zero_dp_3" +from transformers.utils import ( + WEIGHTS_NAME, + is_apex_available, + is_in_notebook, + is_sagemaker_mp_enabled, + logging, +) + + +def is_torch_tpu_available(*args, **kwargs): # noqa: D401 + """Conservative fallback: TPU is not available.""" + + return False + + +def is_torch_greater_or_equal_than_1_10(): + return version.parse(torch.__version__.split("+")[0]) >= version.parse("1.10") + + +def is_torch_less_than_1_11(): + return version.parse(torch.__version__.split("+")[0]) < version.parse("1.11") + +# from torch.optim.optimizer import StateDict, params_t +import wandb +from gradient_pruning.pruning_utils import ( + fast_random_mask_like, + estimate_pretrained_model_magnitude_pruning_threshold, + compute_named_parameters_to_sparsity, +) +from metrics import f1 +from utils import OPT_PERTURBATION_LEVEL_TO_REGEX +import npu_compat as DeviceLoader + +_is_native_cpu_amp_available = is_torch_greater_or_equal_than_1_10 + +DEFAULT_CALLBACKS = [DefaultFlowCallback] +DEFAULT_PROGRESS_CALLBACK = ProgressCallback + +if is_in_notebook(): + from .utils.notebook import NotebookProgressCallback + + DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback + +if is_apex_available(): + from apex import amp + +if is_torch_tpu_available(check_device=False): + import torch_xla.core.xla_model as xm + import torch_xla.debug.metrics as met + import torch_xla.distributed.parallel_loader as pl + +if is_fairscale_available(): + dep_version_check("fairscale") + +if is_sagemaker_mp_enabled(): + import smdistributed.modelparallel.torch as smp + from smdistributed.modelparallel import __version__ as SMP_VERSION + + IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse("1.10") +else: + IS_SAGEMAKER_MP_POST_1_10 = False + +if TYPE_CHECKING: + pass + +logger = logging.get_logger(__name__) + +# Name of the files used for checkpointing +TRAINING_ARGS_NAME = "training_args.bin" +TRAINER_STATE_NAME = "trainer_state.json" +OPTIMIZER_NAME = "optimizer.pt" +SCHEDULER_NAME = "scheduler.pt" +SCALER_NAME = "scaler.pt" + + +class OurTrainer(Trainer): + + # ZO-Bench added: new parameters to our traininer + def __init__(self, evaluate_func, dev_samples, eval_samples, perturb_module_regex, *args, **kwargs): + super().__init__(*args, **kwargs) # Initialize the base class + + # transformers>=4.45.0 移除了 `Trainer.do_grad_scaling`,为了兼容旧版逻辑,这里显式补充 + if not hasattr(self, "do_grad_scaling"): + accelerator = getattr(self, "accelerator", None) + scaler = None + if accelerator is not None: + scaler = getattr(accelerator, "scaler", None) + if scaler is None: + scaler = getattr(getattr(accelerator, "state", None), "grad_scaler", None) + self.do_grad_scaling = scaler is not None + if not hasattr(self, "scaler"): + self.scaler = scaler + elif not hasattr(self, "scaler"): + # 新版 Trainer 仍可能拥有 grad scaler,但属性名不同,这里保持旧逻辑所需字段 + accelerator = getattr(self, "accelerator", None) + scaler = None + if accelerator is not None: + scaler = getattr(accelerator, "scaler", None) + if scaler is None: + scaler = getattr(getattr(accelerator, "state", None), "grad_scaler", None) + self.scaler = scaler + self.evaluate_func = evaluate_func + self.dev_samples = dev_samples + self.eval_samples = eval_samples + self.perturb_module_regex = perturb_module_regex + + if not hasattr(self, "sharded_ddp"): + self.sharded_ddp = None + if not hasattr(self, "fsdp"): + self.fsdp = None + + # AGZO: initialize bookkeeping structures when使用新的激活引导Zeroth-Order训练器 + self.agzo_enabled = getattr(self.args, "trainer", "") == "agzo" + self.lozo_enabled = getattr(self.args, "trainer", "") == "lozo" + if self.agzo_enabled: + self._agzo_hooks_registered = False + self.agzo_hooks = [] + self.agzo_layer_inputs = {} + self.agzo_u = {} + self.agzo_collecting = False + self._agzo_missing_activation_warned = False + + self._loss_buffer = 0.0 + self._loss_buffer_steps = 0 + + # Best-checkpoint tracking + self._save_best_enabled = bool(getattr(self.args, "save_best", False)) + self._best_metric_name = getattr(self.args, "best_metric_name", "accuracy") + self._best_split_pref = getattr(self.args, "best_split", "val") + self._best_value = None + try: + self._best_dir = os.path.join(self.args.output_dir, "best") + except Exception: + self._best_dir = None + + def _prepare_inputs(self, inputs: Dict[str, Union[torch.Tensor, Any]]) -> Dict[str, Union[torch.Tensor, Any]]: + """ + 重写 Trainer 的数据准备函数。 + 强制将输入数据移动到模型权重所在的设备,解决 NPU DDP 环境下 args.device 不准确导致设备不匹配的问题。 + """ + # 尝试获取模型当前的真实设备 + target_device = self.args.device # 默认回退值 + try: + # 处理 DDP/FSDP 封装的情况,module 属性可能才是真模型 + if hasattr(self.model, "module"): + target_device = next(self.model.module.parameters()).device + else: + target_device = next(self.model.parameters()).device + except Exception: + pass + + # 将所有 Tensor 类型的输入移动到目标设备 + for k, v in inputs.items(): + if isinstance(v, torch.Tensor): + inputs[k] = v.to(target_device) + + # 处理 Transformer-XL 风格的 memory (如果有) + if self.args.past_index >= 0 and getattr(self, "_past", None) is not None: + inputs["mems"] = self._past + + return inputs + + # === Utility: NPU-safe random normal generation === + @staticmethod + def _safe_normal(size, device, dtype, mean=0.0, std=1.0): + """Generate normal random tensor. On NPU with BF16, generate in FP32 then cast to BF16.""" + try: + # if device is None: + # # Fallback to CPU if device is None + # return torch.normal(mean=mean, std=std, size=size, dtype=dtype) + + # if getattr(device, "type", None) == "npu" and dtype == torch.bfloat16: + # return torch.normal(mean=mean, std=std, size=size, device=device, dtype=torch.float32).to(dtype) + return torch.normal(mean=mean, std=std, size=size, device=device, dtype=dtype) + except Exception: + # As a last resort, generate on CPU in float32 and cast/move + return torch.normal(mean=mean, std=std, size=size, dtype=torch.float32).to(device=device, dtype=dtype) + + def _collect_npu_memory_metrics(self): + """Gather NPU memory stats via DeviceLoader for logging.""" + return DeviceLoader.collect_npu_memory_metrics() + + def _inner_training_loop( + self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None + ): + """ + We overload the original training loop to add linear probing and MeZO. Search key word "MeZO added" + for those updates. + """ + self._train_batch_size = batch_size + # Data loader and number of training steps + train_dataloader = self.get_train_dataloader() + eval_dataloader = self.get_eval_dataloader() # ----newly-added + + # MeZO added: Linear probing + if self.args.linear_probing: + + def _get_token_prediction_layer(model): + if model.config.model_type in ["opt", "llama", "mistral"]: + return model.lm_head + else: + raise NotImplementedError(model.config.model_type) + + def _extract_features(model, *args, **kwargs): + """some magic for getting features pre last layer""" + features = {} + + def __hook(model_, input_, output_): + features["features"] = input_[0].detach() + + _get_token_prediction_layer(model).register_forward_hook(__hook) + model.forward(*args, **kwargs) + return features["features"] + + logger.info("Linear probing") + logger.info("Starting to get features for training dataset") + targets = [] + features = [] + with torch.inference_mode(): + for step, inputs in enumerate(tqdm(train_dataloader)): + for k, v in inputs.items(): + if isinstance(v, torch.Tensor): + inputs[k] = v.to(self.model.device) + + feature = _extract_features(self.model, **inputs) + target = inputs["labels"] + + # Shift the target (bc it's autoregressive LM) and add the corresponding part + assert not self.args.train_as_classification and self.args.only_train_option + feature, target = feature[:, :-1], target[:, 1:] + for _i, _len in enumerate(inputs["option_len"]): + features.append(feature[_i, -_len:]) + targets.append(target[_i, -_len:]) + + logger.info("Finished getting features for training dataset") + + features = torch.cat(features, dim=0).cpu().numpy() + targets = torch.cat(targets, dim=0).cpu().numpy() + # Whether to use bias + if self.model.config.model_type in ["opt", "gpt2", "llama", "mistral"]: + use_bias = False + else: + raise NotImplementedError + # Set early stopping + tol = 0.01 if self.args.lp_early_stopping else 1e-4 # 1e-4 is scipy default + max_iter = 1000 if self.args.lp_early_stopping else 5000 + + logger.info("Fitting logistic regression...") + reg = LogisticRegressionCV(max_iter=max_iter, fit_intercept=use_bias, multi_class="multinomial", + random_state=0, tol=tol, n_jobs=-1).fit(features, targets) + logger.info("Done") + + logger.info("Assigning weights to model") + decoder = _get_token_prediction_layer(self.model) + coef_torch = torch.tensor(reg.coef_, device=decoder.weight.device, dtype=decoder.weight.dtype) + if use_bias: + bias_torch = torch.tensor(reg.intercept_, device=decoder.weight.device, dtype=decoder.weight.dtype) + if coef_torch.shape[0] == 1: # The regressor only detects two classes + assert len(reg.classes_) == 2 + coef_torch = torch.cat([-coef_torch / 2, coef_torch / 2], dim=0) + if use_bias: + bias_torch = torch.cat([-bias_torch / 2, bias_torch / 2], dim=0) + + for _i, token_id in enumerate(reg.classes_): + decoder.weight.data[token_id] = coef_torch[_i] + if use_bias: + decoder.bias.data[token_id] = bias_torch[_i] + + return None + + # Setting up training control variables: + # number of training epochs: num_train_epochs + # number of training steps per epoch: num_update_steps_per_epoch + # total number of training steps to execute: max_steps + total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size + + len_dataloader = None + if has_length(train_dataloader): + len_dataloader = len(train_dataloader) + num_update_steps_per_epoch = len_dataloader // args.gradient_accumulation_steps + num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) + num_examples = self.num_examples(train_dataloader) + if args.max_steps > 0: + max_steps = args.max_steps + num_train_epochs = args.max_steps // num_update_steps_per_epoch + int( + args.max_steps % num_update_steps_per_epoch > 0 + ) + # May be slightly incorrect if the last batch in the training dataloader has a smaller size but it's + # the best we can do. + num_train_samples = args.max_steps * total_train_batch_size + else: + max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch) + num_train_epochs = math.ceil(args.num_train_epochs) + num_train_samples = self.num_examples(train_dataloader) * args.num_train_epochs + elif args.max_steps > 0: # Rely on max_steps when dataloader does not have a working size + max_steps = args.max_steps + # Setting a very large number of epochs so we go as many times as necessary over the iterator. + num_train_epochs = sys.maxsize + num_update_steps_per_epoch = max_steps + num_examples = total_train_batch_size * args.max_steps + num_train_samples = args.max_steps * total_train_batch_size + else: + raise ValueError( + "args.max_steps must be set to a positive value if dataloader does not have a length, was" + f" {args.max_steps}" + ) + + if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug: + if self.args.n_gpu > 1: + # nn.DataParallel(model) replicates the model, creating new variables and module + # references registered here no longer work on other gpus, breaking the module + raise ValueError( + "Currently --debug underflow_overflow is not supported under DP. Please use DDP" + " (torch.distributed.launch)." + ) + else: + debug_overflow = DebugUnderflowOverflow(self.model) # noqa + + delay_optimizer_creation = ( + self.sharded_ddp is not None + and self.sharded_ddp != ShardedDDPOption.SIMPLE + or is_sagemaker_mp_enabled() + or self.fsdp is not None + ) + if args.deepspeed: + deepspeed_engine, optimizer, lr_scheduler = deepspeed_init( + self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint + ) + self.model = deepspeed_engine.module + self.model_wrapped = deepspeed_engine + self.deepspeed = deepspeed_engine + self.optimizer = optimizer + self.lr_scheduler = lr_scheduler + elif not delay_optimizer_creation: + self.create_optimizer_and_scheduler(num_training_steps=max_steps) + + self.state = TrainerState() + self.state.is_hyper_param_search = trial is not None + + # Activate gradient checkpointing if needed + if args.gradient_checkpointing: + self.model.gradient_checkpointing_enable() + + model = self._wrap_model(self.model_wrapped) + + if is_sagemaker_mp_enabled() and resume_from_checkpoint is not None: + self._load_from_checkpoint(resume_from_checkpoint, model) + + # for the rest of this function `model` is the outside model, whether it was wrapped or not + if model is not self.model: + self.model_wrapped = model + + if delay_optimizer_creation: + self.create_optimizer_and_scheduler(num_training_steps=max_steps) + + # Check if saved optimizer or scheduler states exist + self._load_optimizer_and_scheduler(resume_from_checkpoint) + + # # 在NPU上使用融合优化器时,torch_npu仅支持 fp32/fp16 参数;若模型为bf16需先转换 + # try: + # if DeviceLoader.is_npu_available(): + # needs_cast = False + # for p in self.model.parameters(): + # if p.dtype == torch.bfloat16: + # needs_cast = True + # break + # if needs_cast: + # logger.info("Detected bf16 params on NPU; casting model to fp16 for fused optimizer compatibility") + # # 将整模型参数类型转为fp16以适配NPU融合优化器(注意:Attention内核不支持fp32输入) + # self.model.to(dtype=torch.float16) + # except Exception: + # # 若转换失败,不阻断训练流程;后续优化器若仍不兼容会显式报错 + # pass + + if DeviceLoader.is_npu_available(): + from torch_npu import optim as npu_optim + # overload the optimizer here + if args.trainer == "zo_adam": + self.optimizer = Adam(self.model.parameters(), lr=args.learning_rate) + # self.optimizer = {name: Adam([param], lr=args.learning_rate) for name, param in self.model.named_parameters()} + # assert args.lr_scheduler + assert args.lr_scheduler_type == 'constant', "we did not implement lr_schedule." + elif args.trainer == "zo_sgd": + # if DeviceLoader.is_npu_available(): + # self.optimizer = npu_optim.NpuFusedSGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + # else: + # self.optimizer = SGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + self.optimizer = SGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + # self.optimizer = {name: SGD([param], lr=args.learning_rate) for name, param in self.model.named_parameters()} + # print(f"### args.lr_scheduler: {args.lr_scheduler_type}") + assert args.lr_scheduler_type == 'constant', "we did not implement lr_schedule." + elif args.trainer == "lozo": + # if DeviceLoader.is_npu_available(): + # self.optimizer = npu_optim.NpuFusedSGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + # else: + # self.optimizer = SGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + self.optimizer = SGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + assert args.lr_scheduler_type == 'constant', "we did not implement lr_schedule." + else: + assert args.lr_scheduler_type == 'constant', "we did not implement lr_schedule." + if args.optimizer == "adam": + # if DeviceLoader.is_npu_available(): + # self.optimizer = npu_optim.NpuFusedAdam(self.model.parameters(), lr=args.learning_rate) + # else: + # self.optimizer = Adam(self.model.parameters(), lr=args.learning_rate) + self.optimizer = Adam(self.model.parameters(), lr=args.learning_rate) + elif args.optimizer == "sgd": + # if DeviceLoader.is_npu_available(): + # self.optimizer = npu_optim.NpuFusedSGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + # else: + # self.optimizer = SGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + self.optimizer = SGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + if args.trainer == "agzo": + # if DeviceLoader.is_npu_available(): + # self.optimizer = npu_optim.NpuFusedSGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + # else: + # self.optimizer = SGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + self.optimizer = SGD(self.model.parameters(), lr=args.learning_rate, momentum=args.momentum) + + # important: at this point: + # self.model is the Transformers Model + # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc. + + # Train! + logger.info("***** Running training *****") + logger.info(f" Num examples = {num_examples}") + logger.info(f" Num Epochs = {num_train_epochs}") + logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") + logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}") + logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") + logger.info(f" Total optimization steps = {max_steps}") + logger.info( + f" Number of trainable parameters = {sum(p.numel() for p in model.parameters() if p.requires_grad)}" + ) + logger.info(f" Trainer = {args.trainer}") + + self.state.epoch = 0 + start_time = time.time() + epochs_trained = 0 + steps_trained_in_current_epoch = 0 + steps_trained_progress_bar = None + + # Check if continuing training from a checkpoint + if resume_from_checkpoint is not None and os.path.isfile( + os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME) + ): + self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)) + epochs_trained = self.state.global_step // num_update_steps_per_epoch + if not args.ignore_data_skip: + steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch) + steps_trained_in_current_epoch *= args.gradient_accumulation_steps + else: + steps_trained_in_current_epoch = 0 + + logger.info(" Continuing training from checkpoint, will skip to saved global_step") + logger.info(f" Continuing training from epoch {epochs_trained}") + logger.info(f" Continuing training from global step {self.state.global_step}") + if not args.ignore_data_skip: + logger.info( + f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} " + "batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` " + "flag to your launch command, but you will resume the training on data already seen by your model." + ) + if self.is_local_process_zero() and not args.disable_tqdm: + steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch) + steps_trained_progress_bar.set_description("Skipping the first batches") + + # Update the references + self.callback_handler.model = self.model + self.callback_handler.optimizer = self.optimizer + self.callback_handler.lr_scheduler = self.lr_scheduler + self.callback_handler.train_dataloader = train_dataloader + if self.hp_name is not None and self._trial is not None: + # use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial + # parameter to Train when using DDP. + self.state.trial_name = self.hp_name(self._trial) + if trial is not None: + assignments = trial.assignments if self.hp_search_backend == HPSearchBackend.SIGOPT else trial + self.state.trial_params = hp_params(assignments) + else: + self.state.trial_params = None + # This should be the same if the state has been saved but in case the training arguments changed, it's safer + # to set this after the load. + self.state.max_steps = max_steps + self.state.num_train_epochs = num_train_epochs + self.state.is_local_process_zero = self.is_local_process_zero() + self.state.is_world_process_zero = self.is_world_process_zero() + + # tr_loss is a tensor to avoid synchronization of TPUs through .item() + tr_loss = torch.tensor(0.0).to(args.device) + # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses + self._total_loss_scalar = 0.0 + self._globalstep_last_logged = self.state.global_step + model.zero_grad() + + self.control = self.callback_handler.on_train_begin(args, self.state, self.control) + + # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. + if not args.ignore_data_skip: + for epoch in range(epochs_trained): + is_random_sampler = hasattr(train_dataloader, "sampler") and isinstance( + train_dataloader.sampler, RandomSampler + ) + if is_torch_less_than_1_11 or not is_random_sampler: + # We just need to begin an iteration to create the randomization of the sampler. + # That was before PyTorch 1.11 however... + for _ in train_dataloader: + break + else: + # Otherwise we need to call the whooooole sampler cause there is some random operation added + # AT THE VERY END! + _ = list(train_dataloader.sampler) + + # Main training loop + total_steps = 0 + self.sparse_grad_rng = torch.Generator(device='npu' if DeviceLoader.is_npu_available() else 'cpu') + self.gradient_sparsity = None # None, float, or dict + + if self.args.sparse_gradient_group == "layer" or self.args.gradient_sparsity is None: + self.gradient_sparsity = self.args.gradient_sparsity + print(f"### layer-wise gradient sparsity = {self.gradient_sparsity}") + elif self.args.sparse_gradient_group == "global": + threshold = estimate_pretrained_model_magnitude_pruning_threshold(model, self.args.gradient_sparsity) + self.gradient_sparsity = compute_named_parameters_to_sparsity(model, threshold) + print(f"### global gradient sparsity, weight magnitude threshold = {threshold}") + + for epoch in range(epochs_trained, num_train_epochs): + print(f"-------------------------- Training Epoch {epoch} --------------------------") + if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): + train_dataloader.sampler.set_epoch(epoch) + elif hasattr(train_dataloader, "dataset") and isinstance(train_dataloader.dataset, IterableDatasetShard): + train_dataloader.dataset.set_epoch(epoch) + + if is_torch_tpu_available(): + parallel_loader = pl.ParallelLoader(train_dataloader, [args.device]).per_device_loader(args.device) + epoch_iterator = parallel_loader + else: + epoch_iterator = train_dataloader + + # Reset the past mems state at the beginning of each epoch if necessary. + if args.past_index >= 0: + self._past = None + + steps_in_epoch = ( + len(epoch_iterator) + if len_dataloader is not None + else args.max_steps * args.gradient_accumulation_steps + ) + self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control) + + if epoch == epochs_trained and resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0: + self._load_rng_state(resume_from_checkpoint) + + step = -1 + # Start one epoch training + for step, inputs in enumerate(epoch_iterator): + + if total_steps % self.args.sparse_gradient_resample_steps == 0: + self.sparse_grad_random_seed = np.random.randint(1000000000) + + total_steps += 1 + + # torch device synchronize (NPU/CUDA) + # torch.cuda.synchronize() # original + # DeviceLoader.synchronize() # optional + step_start_time = time.time() + + # Skip past any already trained steps if resuming training + if steps_trained_in_current_epoch > 0: + steps_trained_in_current_epoch -= 1 + if steps_trained_progress_bar is not None: + steps_trained_progress_bar.update(1) + if steps_trained_in_current_epoch == 0: + self._load_rng_state(resume_from_checkpoint) + continue + elif steps_trained_progress_bar is not None: + steps_trained_progress_bar.close() + steps_trained_progress_bar = None + + if step % args.gradient_accumulation_steps == 0: + self.control = self.callback_handler.on_step_begin(args, self.state, self.control) + + # MeZO added: estimate gradient + if args.trainer in ["zo_sgd", "zo_adam", "zo_sign_opt"]: + if args.module_wise_perturbation: + assert args.q == 1, "module-wise perturbation only supports q=1" + if args.coordinate_perturbation: + tr_loss_step = self.zo_step_with_module_wise_perturbation_coordinate(model, inputs) + else: + tr_loss_step = self.zo_step_with_module_wise_perturbation(model, inputs) + elif args.q == 1: + tr_loss_step = self.zo_step(model, inputs) + elif args.q > 1: + tr_loss_step = self.zo_step_v1(model, inputs) + else: + raise ValueError(f"q={args.q} is not supported.") + elif args.trainer == "lozo": + tr_loss_step = self.lozo_step(model, inputs) + elif args.trainer == "agzo": # AGZO: 新增训练流程 + tr_loss_step = self.agzo_step(model, inputs) + elif args.trainer == "zo_conserv": + tr_loss_step = self.zo_conserv_step(model, inputs) + elif args.trainer == "forward_grad": + tr_loss_step = self.forward_grad_step(model, inputs) + else: + if ( + ((step + 1) % args.gradient_accumulation_steps != 0) + and args.local_rank != -1 + and args._no_sync_in_gradient_accumulation + ): + # Avoid unnecessary DDP synchronization since there will be no backward pass on this example. + with model.no_sync(): + tr_loss_step = self.training_step(model, inputs) + else: + tr_loss_step = self.training_step(model, inputs) + + if ( + args.logging_nan_inf_filter + and not is_torch_tpu_available() + and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step)) + ): + # if loss is nan or inf simply add the average of previous logged losses + tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged) + else: + tr_loss += tr_loss_step + self._loss_buffer += tr_loss_step.detach().float().item() + self._loss_buffer_steps += 1 + + self.current_flos += float(self.floating_point_ops(inputs)) + + # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps + if self.deepspeed: + self.deepspeed.step() + + if (step + 1) % args.gradient_accumulation_steps == 0 or ( + # last step in epoch but step is always smaller than gradient_accumulation_steps + steps_in_epoch <= args.gradient_accumulation_steps + and (step + 1) == steps_in_epoch + ): + # MeZO added: update model with the estimated gradient + if args.trainer in ["zo_sgd", "zo_adam", "zo_sign_opt", "zo_conserv", "agzo", "lozo"]: # AGZO/LOZO: 纳入学习率调度 + self.zo_update(model) + elif args.trainer == "forward_grad": + self.forward_grad_update(model) + else: + self.gradient_update(model) + + self.state.global_step += 1 + self.state.epoch = epoch + (step + 1) / steps_in_epoch + self.control = self.callback_handler.on_step_end(args, self.state, self.control) + current_learning_rate = None + if hasattr(self, "_get_learning_rate"): + try: + current_learning_rate = self._get_learning_rate() + except Exception: + current_learning_rate = None + if ( + args.logging_strategy == IntervalStrategy.STEPS + and args.logging_steps is not None + and args.logging_steps > 0 + and self.state.global_step % args.logging_steps == 0 + and self._loss_buffer_steps > 0 + ): + avg_loss = self._loss_buffer / self._loss_buffer_steps + self.log({"loss": avg_loss, "train/loss": avg_loss}) + self._loss_buffer = 0.0 + self._loss_buffer_steps = 0 + self._maybe_log_save_evaluate( + tr_loss, + None, + model, + trial, + epoch, + ignore_keys_for_eval, + start_time=start_time, + learning_rate=current_learning_rate, + ) + + else: + self.control = self.callback_handler.on_substep_end(args, self.state, self.control) + + # torch.cuda.synchronize() + train_step_duration = time.time() - step_start_time + + if self.control.should_epoch_stop or self.control.should_training_stop: + break + + if self.args.eval_steps is not None and (total_steps + 1) % self.args.eval_steps == 0: + print( + f"=========================> Evaluating at step {total_steps + 1}... <=========================") + val_metrics = self.evaluate_func([], self.dev_samples) + test_metrics = self.evaluate_func([], self.eval_samples) + if "accuracy" in test_metrics: + self.log({"test_acc": test_metrics["accuracy"], "val_acc": val_metrics["accuracy"]}) + else: + keys = list(test_metrics.keys()) + log_dict = {} + for k in keys: + log_dict['test_' + k] = test_metrics[k] + log_dict['val_' + k] = val_metrics[k] + self.log(log_dict) + + # Save best checkpoint based on preferred split + try: + if self._save_best_enabled and self.args.should_save and self._best_dir is not None: + os.makedirs(self._best_dir, exist_ok=True) + chosen = None + if isinstance(val_metrics, dict) and self._best_split_pref == "val": + chosen = val_metrics + elif isinstance(test_metrics, dict): + chosen = test_metrics + if chosen: + metric_name = self._best_metric_name + current_val = chosen.get(metric_name) + if current_val is None and len(chosen) > 0: + # fallback to first metric + metric_name, current_val = next(iter(chosen.items())) + if current_val is not None: + improved = ( + self._best_value is None or float(current_val) > float(self._best_value) + ) + if improved: + self.save_model(self._best_dir) + meta = { + "metric": metric_name, + "value": float(current_val), + "split": "val" if chosen is val_metrics else "test", + "step": int(self.state.global_step), + } + try: + with open(os.path.join(self._best_dir, "best_metric.json"), "w") as f: + json.dump(meta, f) + except Exception: + pass + self._best_value = float(current_val) + except Exception as e: + logger.warning(f"Saving best checkpoint failed: {e}") + + mem_metrics = {"step_consumption": train_step_duration * 1000} + if DeviceLoader.is_npu_available(): + mem_metrics.update(self._collect_npu_memory_metrics()) + self.log(mem_metrics) + + # AGZO: optionally empty device cache to mitigate peak growth + if ( + args.trainer == "agzo" + and getattr(args, "agzo_empty_cache_steps", 0) > 0 + and total_steps % args.agzo_empty_cache_steps == 0 + and (DeviceLoader.is_npu_available()) + ): + DeviceLoader.empty_cache() + DeviceLoader.reset_peak_memory_stats() + + if step < 0: + # Why would this happen? I don't know, but let's be safe. + logger.warning( + "There seems to be not a single sample in your epoch_iterator, stopping training at step" + f" {self.state.global_step}! This is expected if you're using an IterableDataset and set" + f" num_steps ({max_steps}) higher than the number of available samples." + ) + self.control.should_training_stop = True + + self.control = self.callback_handler.on_epoch_end(args, self.state, self.control) + self._maybe_log_save_evaluate( + tr_loss, + None, + model, + trial, + epoch, + ignore_keys_for_eval, + start_time=start_time, + ) + + if DebugOption.TPU_METRICS_DEBUG in self.args.debug: + if is_torch_tpu_available(): + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + else: + logger.warning( + "You enabled PyTorch/XLA debug metrics but you don't have a TPU " + "configured. Check your training configuration if this is unexpected." + ) + if self.control.should_training_stop: + break + + if args.past_index and hasattr(self, "_past"): + # Clean the state at the end of training + delattr(self, "_past") + + logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") + if args.load_best_model_at_end and self.state.best_model_checkpoint is not None: + # Wait for everyone to get here so we are sur the model has been saved by process 0. + if is_torch_tpu_available(): + xm.rendezvous("load_best_model_at_end") + elif args.local_rank != -1: + dist.barrier() + elif is_sagemaker_mp_enabled(): + smp.barrier() + + self._load_best_model() + + # add remaining tr_loss + self._total_loss_scalar += tr_loss.item() + train_loss = self._total_loss_scalar / self.state.global_step + + metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps) + self.store_flos() + metrics["total_flos"] = self.state.total_flos + metrics["train_loss"] = train_loss + + self.is_in_train = False + + self._memory_tracker.stop_and_update_metrics(metrics) + + wandb.log(metrics) + self.log(metrics) + + run_dir = self._get_output_dir(trial) + checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir) + + # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint. + if self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1: + for checkpoint in checkpoints_sorted: + if checkpoint != self.state.best_model_checkpoint: + logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") + shutil.rmtree(checkpoint) + + self.control = self.callback_handler.on_train_end(args, self.state, self.control) + + return TrainOutput(self.state.global_step, train_loss, metrics) + + # Final best save if none captured during training + try: + if self._save_best_enabled and self.args.should_save and self._best_dir is not None and self._best_value is None: + val_metrics = None + if self.dev_samples is not None: + try: + val_metrics = self.evaluate_func([], self.dev_samples) + except Exception: + val_metrics = None + test_metrics = None + try: + test_metrics = self.evaluate_func([], self.eval_samples) + except Exception: + test_metrics = None + chosen = val_metrics if (isinstance(val_metrics, dict) and self._best_split_pref == "val") else test_metrics + if isinstance(chosen, dict) and len(chosen) > 0: + metric_name = self._best_metric_name + current_val = chosen.get(metric_name) + if current_val is None: + metric_name, current_val = next(iter(chosen.items())) + os.makedirs(self._best_dir, exist_ok=True) + self.save_model(self._best_dir) + meta = { + "metric": metric_name, + "value": float(current_val), + "split": "val" if chosen is val_metrics else "test", + "step": int(self.state.global_step), + } + try: + with open(os.path.join(self._best_dir, "best_metric.json"), "w") as f: + json.dump(meta, f) + except Exception: + pass + self._best_value = float(current_val) + except Exception as e: + logger.warning(f"Final best checkpoint save failed: {e}") + + ############## MeZO ############## + + def gradient_update(self, model): + args = self.args + + # Gradient clipping + if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed: + # deepspeed does its own clipping + + if self.do_grad_scaling: + # Reduce gradients first for XLA + if is_torch_tpu_available(): + gradients = xm._fetch_gradients(self.optimizer) + xm.all_reduce("sum", gradients, scale=1.0 / xm.xrt_world_size()) + # AMP: gradients need unscaling + self.scaler.unscale_(self.optimizer) + + if is_sagemaker_mp_enabled() and args.fp16: + self.optimizer.clip_master_grads(args.max_grad_norm) + elif hasattr(self.optimizer, "clip_grad_norm"): + # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping + self.optimizer.clip_grad_norm(args.max_grad_norm) + elif hasattr(model, "clip_grad_norm_"): + # Some models (like FullyShardedDDP) have a specific way to do gradient clipping + model.clip_grad_norm_(args.max_grad_norm) + else: + # Revert to normal clipping otherwise, handling Apex or full precision + nn.utils.clip_grad_norm_( + amp.master_params(self.optimizer) if self.use_apex else model.parameters(), + args.max_grad_norm, + ) + + # Optimizer step + optimizer_was_run = True + if self.deepspeed: + pass # called outside the loop + elif is_torch_tpu_available(): + if self.do_grad_scaling: + self.scaler.step(self.optimizer) + self.scaler.update() + else: + xm.optimizer_step(self.optimizer) + elif self.do_grad_scaling: + scale_before = self.scaler.get_scale() + self.scaler.step(self.optimizer) + self.scaler.update() + scale_after = self.scaler.get_scale() + optimizer_was_run = scale_before <= scale_after + else: + self.optimizer.step() + + if optimizer_was_run and not self.deepspeed: + self.lr_scheduler.step() + model.zero_grad() + + def zo_perturb_parameters(self, random_seed=None, scaling_factor=1): + """ + Perturb the parameters with random vector z. + Input: + - random_seed: random seed for MeZO in-place perturbation (if it's None, we will use self.zo_random_seed) + - scaling_factor: theta = theta + scaling_factor * z * eps + """ + + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(random_seed if random_seed is not None else self.zo_random_seed) + self.sparse_grad_rng.manual_seed(self.sparse_grad_random_seed) + + for name, param in self.named_parameters_to_optim: + grad_sparsity = self.get_grad_sparsity_by_name(name) + # z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + z = self._safe_normal(mean=0, std=1, size=param.data.size(), + device=param.data.device, + dtype=param.data.dtype) + + if grad_sparsity is not None: + z[fast_random_mask_like(z, grad_sparsity, generator=self.sparse_grad_rng)] = 0 + param.data = param.data + scaling_factor * z * self.args.zo_eps + + # AGZO: helper methods for activation-guided perturbations --------------------------------- + def _ensure_agzo_hooks(self): + if not getattr(self, "agzo_enabled", False): + return + if getattr(self, "_agzo_hooks_registered", False): + return + self._register_agzo_hooks() + + def _register_agzo_hooks(self): + """AGZO: register forward hooks to capture layer activations for principal direction.""" + params_dict = dict(self.model.named_parameters()) + self.agzo_param_map = {} + for module_name, module in self.model.named_modules(): + if not isinstance(module, nn.Linear): + continue + param_name = f"{module_name}.weight" if module_name else "weight" + param = params_dict.get(param_name) + if param is None or not param.requires_grad: + continue + hook = module.register_forward_hook(self._make_agzo_hook(param_name)) + self.agzo_hooks.append(hook) + self.agzo_param_map[param_name] = param + self._agzo_hooks_registered = True + + def _make_agzo_hook(self, param_name): + """AGZO: create forward hook that computes u_l on-the-fly.""" + + def _hook(module, inputs, output): + if not self.agzo_collecting: + return + activation = None + for inp in inputs: + if isinstance(inp, torch.Tensor): + activation = inp + break + if activation is None: + return + direction = self._agzo_compute_direction(activation.detach(), param_name) + if direction is not None: + self.agzo_u[param_name] = direction + + return _hook + + def _agzo_compute_direction(self, activation: torch.Tensor, param_name: str): + """AGZO: compute principal subspace using block power iteration on activations.""" + if activation.numel() == 0: + return None + if activation.dim() == 0: + return None + param = self.agzo_param_map.get(param_name) + if param is None: + return None + + activation_shape = activation.shape + if activation_shape[-1] == 0: + return None + + activation_2d = activation.reshape(-1, activation_shape[-1]).float() + if activation_2d.shape[0] == 0: + return None + + hidden_dim = activation_2d.shape[1] + max_rank = hidden_dim + if param.dim() >= 2: + max_rank = min(max_rank, param.shape[0], param.shape[1]) + rank = self._get_agzo_rank(max_rank=max_rank) + + basis = self._agzo_power_iteration( + activation_2d, getattr(self.args, "agzo_power_iter_steps", 5), rank=rank + ) + if basis is None: + return None + + if basis.dim() == 1: + basis = basis.unsqueeze(0) + basis = basis / (basis.norm(p=2, dim=1, keepdim=True) + 1e-12) + return basis.to(device=param.device, dtype=param.dtype) + + def _agzo_power_iteration(self, activation_2d: torch.Tensor, num_steps: int, rank: int): + """AGZO: block power iteration on A^T A for top-r left singular vectors.""" + hidden_dim = activation_2d.shape[1] + if hidden_dim == 0: + return None + num_steps = max(1, int(num_steps)) + rank = max(1, min(int(rank), hidden_dim)) + + q = torch.randn(hidden_dim, rank, device=activation_2d.device, dtype=activation_2d.dtype) + q, _ = torch.linalg.qr(q, mode="reduced") + for _ in range(num_steps): + y = activation_2d.matmul(q) + z = activation_2d.transpose(0, 1).matmul(y) + if not torch.isfinite(z).all(): + break + q, _ = torch.linalg.qr(z, mode="reduced") + return q.transpose(0, 1) + + def agzo_collect_basis(self, model, inputs): + """AGZO: run an additional forward pass to update u_l for each layer.""" + self._ensure_agzo_hooks() + self.agzo_u.clear() + self.agzo_collecting = True + try: + # Reuse zo_forward to ensure identical preprocessing (dropout off, etc.) + _ = self.zo_forward(model, inputs) + finally: + self.agzo_collecting = False + + def _agzo_sample_z(self, name: str, param: torch.nn.Parameter): + """AGZO: sample rank-r perturbation using stored activation-guided basis; fallback to Gaussian if unavailable. + + On NPU with bf16 tensors, sample in float32 then cast for compatibility. + """ + basis = self.agzo_u.get(name) + sample_dtype = param.data.dtype + if basis is None or param.dim() < 2: + z = self._safe_normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=sample_dtype) + else: + basis = basis.to(device=param.data.device, dtype=sample_dtype) + if basis.dim() == 1: + basis = basis.unsqueeze(0) + if basis.shape[1] != param.data.shape[1]: + z = self._safe_normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=sample_dtype) + else: + rank = basis.shape[0] + r = self._safe_normal( + mean=0, + std=1, + size=(param.data.shape[0], rank), + device=param.data.device, + dtype=sample_dtype, + ) + z = torch.matmul(r, basis) / math.sqrt(rank) + z = z.to(dtype=param.data.dtype) + grad_sparsity = self.get_grad_sparsity_by_name(name) + if grad_sparsity is not None: + z[fast_random_mask_like(z, grad_sparsity, generator=self.sparse_grad_rng)] = 0 + return z + + def _get_agzo_rank(self, max_rank: Optional[int] = None): + """Return sanitized AGZO rank (>=1, optionally bounded by max_rank).""" + rank = getattr(self.args, "agzo_rank", 1) + try: + rank = int(rank) + except (TypeError, ValueError): + rank = 1 + rank = max(1, rank) + if max_rank is not None: + rank = min(rank, max_rank) + return rank + + def agzo_perturb_parameters(self, random_seed=None, scaling_factor=1): + """AGZO: apply rank-1 perturbation constructed from r_l and stored u_l.""" + torch.manual_seed(random_seed if random_seed is not None else self.zo_random_seed) + self.sparse_grad_rng.manual_seed(self.sparse_grad_random_seed) + + for name, param in self.named_parameters_to_optim: + z = self._agzo_sample_z(name, param) + perturb = (scaling_factor * z * self.args.zo_eps).to(dtype=param.data.dtype, device=param.data.device) + param.data.add_(perturb) + + @torch.no_grad() + def agzo_step(self, model, inputs): + """AGZO: zeroth-order step with activation-guided perturbations.""" + args = self.args + assert args.q == 1, "AGZO currently supports q=1" + + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + param.grad = None + + self.agzo_collect_basis(model, inputs) + if len(self.agzo_u) == 0: + if not self._agzo_missing_activation_warned: + logger.warn("AGZO: 未捕获到任何激活,回退至MeZO扰动。") + self._agzo_missing_activation_warned = True + # AGZO: 由于未获取到激活,暂时复用原有MeZO逻辑,保留原函数调用以便比较 + return self.zo_step(model, inputs) + + self.zo_random_seed = np.random.randint(1000000000) + self.agzo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + if self.args.perturbation_mode == "one_side": + self.agzo_perturb_parameters(scaling_factor=-1) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / self.args.zo_eps).item() + else: + self.agzo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + self.agzo_perturb_parameters(scaling_factor=1) + + torch.manual_seed(self.zo_random_seed) + self.sparse_grad_rng.manual_seed(self.sparse_grad_random_seed) + for name, param in self.named_parameters_to_optim: + z = self._agzo_sample_z(name, param) + grad = (self.projected_grad * z).to(dtype=param.data.dtype, device=param.data.device) + param.grad = grad + self.optimizer.step() + param.grad = None + + assert self.args.gradient_accumulation_steps == 1 + + return loss1 + + # LOZO: low-rank zeroth-order helper -------------------------------------------------------- + def _get_lozo_rank(self): + """Return sanitized global LOZO rank.""" + rank = getattr(self.args, "lozo_rank", 1) + try: + rank = int(rank) + except (TypeError, ValueError): + rank = 1 + return max(1, rank) + + def _lozo_sample_z(self, name: str, param: torch.nn.Parameter): + """Sample low-rank perturbation for parameter. Uses float32 sampling if param is bf16 on NPU.""" + sample_dtype = param.data.dtype + if param.dim() < 2: + # Bias or vector parameter: fall back to isotropic Gaussian. + z = self._safe_normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=sample_dtype) + else: + max_rank = min(param.data.shape[0], param.data.shape[1]) + rank = min(self._get_lozo_rank(), max_rank) + if rank < 1: + rank = 1 + u = torch.randn(param.data.shape[0], rank, device=param.data.device, dtype=sample_dtype) + v = torch.randn(param.data.shape[1], rank, device=param.data.device, dtype=sample_dtype) + z = torch.matmul(u, v.transpose(0, 1)) / math.sqrt(rank) + z = z.to(dtype=param.data.dtype) + grad_sparsity = self.get_grad_sparsity_by_name(name) + if grad_sparsity is not None: + z[fast_random_mask_like(z, grad_sparsity, generator=self.sparse_grad_rng)] = 0 + return z + + def lozo_perturb_parameters(self, random_seed=None, scaling_factor=1): + """Apply LOZO low-rank perturbation.""" + torch.manual_seed(random_seed if random_seed is not None else self.zo_random_seed) + self.sparse_grad_rng.manual_seed(self.sparse_grad_random_seed) + for name, param in self.named_parameters_to_optim: + z = self._lozo_sample_z(name, param) + param.data = param.data + scaling_factor * z * self.args.zo_eps + + @torch.no_grad() + def lozo_step(self, model, inputs): + """LOZO: low-rank zeroth-order step.""" + args = self.args + assert args.q == 1, "LOZO currently仅支持 q=1 以复用 MeZO 的随机种子机制。" + if args.module_wise_perturbation: + raise NotImplementedError("LOZO 暂未支持 module-wise perturbation。") + + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + param.grad = None + + self.zo_random_seed = np.random.randint(1000000000) + self.lozo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + if self.args.perturbation_mode == "one_side": + self.lozo_perturb_parameters(scaling_factor=-1) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / self.args.zo_eps).item() + else: + self.lozo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + self.lozo_perturb_parameters(scaling_factor=1) + + torch.manual_seed(self.zo_random_seed) + self.sparse_grad_rng.manual_seed(self.sparse_grad_random_seed) + for name, param in self.named_parameters_to_optim: + z = self._lozo_sample_z(name, param) + param.grad = self.projected_grad * z / args.q + self.optimizer.step() + param.grad = None + + assert self.args.gradient_accumulation_steps == 1 + + return loss1 + + def zo_forward(self, model, inputs): + """ + Get (no gradient) loss from the model. Dropout is turned off too. + """ + model.eval() + if self.args.non_diff: + # Non-differentiable objective (may require autoregressive generation) + return self.zo_forward_nondiff(model, inputs) + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + # Warning: this is copied from the original Huggingface Trainer. Untested. + loss = loss.mean() # mean() to average on multi-gpu parallel training + return loss.detach() + + def zo_forward_nondiff(self, model, inputs): + """ + Get (no gradient) non-diffiable loss from the model. + """ + model.eval() + assert self.args.task_name == "SQuAD", "Non differentiable objective only supports SQuAD for now." + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + args = self.args + outputs = self.model.generate( + inputs["input_ids"], do_sample=args.sampling, temperature=args.temperature, + num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, + max_new_tokens=min(args.max_new_tokens, args.max_length - inputs["input_ids"].size(1)), + num_return_sequences=1, + eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], + self.tokenizer.eos_token_id], + ) + output_text = [] + for i in range(len(outputs)): + output_text.append( + self.tokenizer.decode(outputs[i][inputs["input_ids"].size(1):], skip_special_tokens=True).strip()) + f1s = [f1(output_text[i], inputs['gold'][i]) for i in range(len(output_text))] + + return -torch.tensor(np.mean(f1s), dtype=torch.float32) + + def get_grad_sparsity_by_name(self, name): + if self.gradient_sparsity is None: + return None + elif isinstance(self.gradient_sparsity, float): + return self.gradient_sparsity + elif isinstance(self.gradient_sparsity, dict): + return self.gradient_sparsity[name] + + def training_step(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: + """ + Perform a training step on a batch of inputs. + + Subclass and override to inject custom behavior. + + Args: + model (`nn.Module`): + The model to train. + inputs (`Dict[str, Union[torch.Tensor, Any]]`): + The inputs and targets of the model. + + The dictionary will be unpacked before being fed to the model. Most models expect the targets under the + argument `labels`. Check your model's documentation for all accepted arguments. + + Return: + `torch.Tensor`: The tensor with training loss on this batch. + """ + model.train() + inputs = self._prepare_inputs(inputs) + + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + + if self.args.gradient_accumulation_steps > 1 and not self.deepspeed: + # deepspeed handles loss scaling by gradient_accumulation_steps in its `backward` + loss = loss / self.args.gradient_accumulation_steps + + if self.do_grad_scaling: + self.scaler.scale(loss).backward() + elif self.use_apex: + with amp.scale_loss(loss, self.optimizer) as scaled_loss: + scaled_loss.backward() + elif self.deepspeed: + # loss gets scaled under gradient_accumulation_steps in deepspeed + loss = self.deepspeed.backward(loss) + else: + loss.backward() + + # Sparse gradient + self.sparse_grad_rng.manual_seed(self.sparse_grad_random_seed) + for name, param in model.named_parameters(): + if not param.requires_grad: + continue + grad_sparsity = self.get_grad_sparsity_by_name(name) + if grad_sparsity is not None: + param.grad[fast_random_mask_like(param.grad, grad_sparsity, generator=self.sparse_grad_rng)] = 0 + + return loss.detach() + + def _maybe_log_save_evaluate( + self, + tr_loss, + model, + trial, + epoch, + ignore_keys_for_eval=None, + *unused_args, + **kwargs, + ): + """ + 兼容 Transformer 不同版本对 `_maybe_log_save_evaluate` 的参数定义,自动丢弃上游未声明的 + 关键字,并为新增的必填参数(如 `start_time`、`grad_norm` 等)提供默认值。 + """ + base_method = super()._maybe_log_save_evaluate + if not hasattr(self, "_maybe_log_sig_params"): + self._maybe_log_sig_params = inspect.signature(base_method).parameters + + def _maybe_add(name, value, include_none=False): + if name in self._maybe_log_sig_params and (include_none or value is not None): + call_kwargs[name] = value + + call_kwargs = {} + _maybe_add("tr_loss", tr_loss, include_none=True) + _maybe_add("model", model, include_none=True) + _maybe_add("trial", trial, include_none=True) + _maybe_add("epoch", epoch, include_none=True) + _maybe_add("ignore_keys_for_eval", ignore_keys_for_eval, include_none=True) + + # 提前抓取常见关键字,其余保留在 kwargs 中,由后续过滤。 + optional_keys = ["start_time", "grad_norm", "learning_rate"] + for key in optional_keys: + value = kwargs.pop(key, None) + _maybe_add(key, value, include_none=True) + + for key, value in list(kwargs.items()): + if key in self._maybe_log_sig_params: + call_kwargs[key] = value + + return base_method(**call_kwargs) + + @staticmethod + def grouped_module_iter(model: nn.Module, group_level: str) -> Iterable[nn.Module]: + """ + Iterate over the top-level modules of a model and yield groups of modules that should be trained together. + + Parameters + ---------- + model: nn.Module + The model to iterate over. + group_level: str + The level at which to iterate over the model. One of "transformer", "mlp-attn", "linear" + """ + reg_pattern = OPT_PERTURBATION_LEVEL_TO_REGEX[group_level] + for name, module in model.named_modules(): + if re.match(reg_pattern, name): + yield name, module + + @torch.no_grad() + def zo_step_with_module_wise_perturbation_coordinate(self, model, inputs): + """Update the parameters right after perturbing the parameters.""" + args = self.args + perturbed_module_level = args.perturbed_module_level + + # Sample the random seed for sampling z + self.zo_random_seed = np.random.randint(1000000000) + + all_losses = [] + + # First function evaluation + # NOTE: when sparse_grad is set to True, it will also check the args.gradient_sparsity, + # so it does not necessarily use sparse grad. + + # Second function evaluation + assert args.q == 1, "only support q=1 for the memory efficiency. If you want to implement q>1, need to store random seeds to save memory. In addition, we need to set different random seed for different z in the q-loop." + for module_name, module in self.grouped_module_iter(model, perturbed_module_level): + self.named_parameters_to_optim = [] + for name, param in module.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((f"{module_name}.{name}", param)) + param.grad = None # Make sure the grad is empty and will not be updated. + + self.zo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + all_losses.append(loss1) + + for _ in range(args.q): + if self.args.perturbation_mode == "one_side": + self.zo_perturb_parameters(scaling_factor=-1) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / self.args.zo_eps).item() + else: # two side perturbation + self.zo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + + # Reset model back to its parameters at start of step + self.zo_perturb_parameters(scaling_factor=1) + + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(self.zo_random_seed) + self.sparse_grad_rng.manual_seed(self.sparse_grad_random_seed) + for name, param in self.named_parameters_to_optim: + # Resample z + z = self._safe_normal(mean=0, std=1, size=param.data.size(), device=param.data.device, + dtype=param.data.dtype) + grad_sparsity = self.get_grad_sparsity_by_name(name) + if grad_sparsity is not None: + z[fast_random_mask_like(z, grad_sparsity, generator=self.sparse_grad_rng)] = 0 + + if args.trainer == "zo_sign_opt": + graddiff_times_z = np.sign(self.projected_grad) * z + else: + graddiff_times_z = self.projected_grad * z + + param.grad = graddiff_times_z / args.q # NOTE this q division does not work for q>1. + self.optimizer.step() # will only update grad that is not None. + param.grad = None # avoid further update. + + assert self.args.gradient_accumulation_steps == 1 + + print(f"[debugging] num blocks: {len(all_losses)}") + + return torch.stack(all_losses).mean() + + @torch.no_grad() + def zo_step_with_module_wise_perturbation(self, model, inputs): + """Update all parameters once after perturbing all the parameters.""" + args = self.args + perturbed_module_level = args.perturbed_module_level + + # Sample the random seed for sampling z + self.zo_random_seed = np.random.randint(1000000000) + + all_losses = [] + module_name_to_projected_grads = {} + + # First function evaluation + # NOTE: when sparse_grad is set to True, it will also check the args.gradient_sparsity, + # so it does not necessarily use sparse grad. + + # Second function evaluation + assert args.q == 1, "only support q=1 for the memory efficiency. If you want to implement q>1, need to store random seeds to save memory. In addition, we need to set different random seed for different z in the q-loop." + for module_name, module in self.grouped_module_iter(model, perturbed_module_level): + self.named_parameters_to_optim = [] + for name, param in module.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((f"{module_name}.{name}", param)) + param.grad = None # Make sure the grad is empty and will not be updated. + + self.zo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + all_losses.append(loss1) + + if self.args.perturbation_mode == "one_side": + self.zo_perturb_parameters(scaling_factor=-1) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / self.args.zo_eps).item() + else: # two side perturbation + self.zo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + + # Reset model back to its parameters at start of step + self.zo_perturb_parameters(scaling_factor=1) + + module_name_to_projected_grads[module_name] = self.projected_grad + + for module_name, module in self.grouped_module_iter(model, perturbed_module_level): + self.named_parameters_to_optim = [] + for name, param in module.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((f"{module_name}.{name}", param)) + param.grad = None # Make sure the grad is empty and will not be updated. + + self.projected_grad = module_name_to_projected_grads[module_name] + + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(self.zo_random_seed) + self.sparse_grad_rng.manual_seed(self.sparse_grad_random_seed) + for name, param in self.named_parameters_to_optim: + # Resample z + z = self._safe_normal(mean=0, std=1, size=param.data.size(), device=param.data.device, + dtype=param.data.dtype) + grad_sparsity = self.get_grad_sparsity_by_name(name) + if grad_sparsity is not None: + z[fast_random_mask_like(z, grad_sparsity, generator=self.sparse_grad_rng)] = 0 + + if args.trainer == "zo_sign_opt": + graddiff_times_z = np.sign(self.projected_grad) * z + else: + graddiff_times_z = self.projected_grad * z + + param.grad = graddiff_times_z / args.q # NOTE this q division does not work for q>1. + self.optimizer.step() # will only update grad that is not None. + param.grad = None # avoid further update. + + assert self.args.gradient_accumulation_steps == 1 + + print(f"[debugging] num blocks: {len(all_losses)}") + + return torch.stack(all_losses).mean() + + @torch.no_grad() + def zo_step(self, model, inputs): + """ + Estimate gradient by MeZO. Return the loss from f(theta + z) + """ + args = self.args + + # What parameters to optimize + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + # # TODO avoid init the memory for grad. + # param.grad = torch.zeros_like(param.data) + param.grad = None # Make sure the grad is empty and will not be updated. + + # Sample the random seed for sampling z + self.zo_random_seed = np.random.randint(1000000000) + + # First function evaluation + # NOTE: when sparse_grad is set to True, it will also check the args.gradient_sparsity, + # so it does not necessarily use sparse grad. + self.zo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + # Second function evaluation + assert args.q == 1, "only support q=1 for the memory efficiency. If you want to implement q>1, need to store random seeds to save memory. In addition, we need to set different random seed for different z in the q-loop." + for _ in range(args.q): # TODO shall we change the seed? + if self.args.perturbation_mode == "one_side": + self.zo_perturb_parameters(scaling_factor=-1) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / self.args.zo_eps).item() + else: # two side perturbation + self.zo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + + # Reset model back to its parameters at start of step + self.zo_perturb_parameters(scaling_factor=1) + + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(self.zo_random_seed) + self.sparse_grad_rng.manual_seed(self.sparse_grad_random_seed) + for name, param in self.named_parameters_to_optim: + # Resample z + z = self._safe_normal(mean=0, std=1, size=param.data.size(), device=param.data.device, + dtype=param.data.dtype) + grad_sparsity = self.get_grad_sparsity_by_name(name) + if grad_sparsity is not None: + z[fast_random_mask_like(z, grad_sparsity, generator=self.sparse_grad_rng)] = 0 + + if args.trainer == "zo_sign_opt": + # ----signOpt_orig + # TODo why do we multiply lr here? We will multiply lr twice? + graddiff_times_z = np.sign(self.projected_grad) * z + # ----signOpt_mul_sign + # graddiff_times_z = self._get_learning_rate() * torch.sign(self.projected_grad * z) + else: + # ----mezo original + graddiff_times_z = self.projected_grad * z + + # # previous implementation + # # no param.grad involved + # param.data -= self._get_learning_rate() * self.projected_grad * z + + # param.grad += graddiff_times_z.detach() + # more mem-efficient: + # run optimizer.step here to avoid caching all grad. + param.grad = graddiff_times_z / args.q # NOTE this q division does not work for q>1. + self.optimizer.step() # will only update grad that is not None. + # param.data = param.data - graddiff_times_z / args.q # NOTE this q division does not work for q>1. + param.grad = None # avoid further update. + + # for name, param in self.named_parameters_to_optim: + # param.grad = param.grad / args.q + + # No gradient accumulation support + assert self.args.gradient_accumulation_steps == 1 + + return loss1 + + @torch.no_grad() + def zo_step_v1(self, model, inputs): + """ + Estimate gradient by MeZO. Return the loss from f(theta + z) + Works with q > 1. But for q > 1, it is not memory efficient. + """ + args = self.args + + # What parameters to optimize + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + # # TODO avoid init the memory for grad. + # param.grad = torch.zeros_like(param.data) + + for i_q in range(args.q): # TODO shall we change the seed? + # Sample the random seed for sampling z + self.zo_random_seed = np.random.randint(1000000000) + + # First function evaluation + self.zo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + # Second function evaluation + if self.args.perturbation_mode == "one_side": + self.zo_perturb_parameters(scaling_factor=-1) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / self.args.zo_eps).item() + else: # two side perturbation + self.zo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + + # Reset model back to its parameters at start of step + self.zo_perturb_parameters(scaling_factor=1) + + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(self.zo_random_seed) + for name, param in self.named_parameters_to_optim: + # Resample z + z = self._safe_normal(mean=0, std=1, size=param.data.size(), device=param.data.device, + dtype=param.data.dtype) + + if args.trainer == "zo_sign_opt": + # ----signOpt_orig + graddiff_times_z = np.sign(self.projected_grad) * z + # ----signOpt_mul_sign + # graddiff_times_z = self._get_learning_rate() * torch.sign(self.projected_grad * z) + else: + # ----mezo original + graddiff_times_z = self.projected_grad * z + + # # previous implementation + # # no param.grad involved + # param.data -= self._get_learning_rate() * self.projected_grad * z + + # param.grad += graddiff_times_z.detach() + # more mem-efficient: + # run optimizer.step here to avoid caching all grad. + if i_q == 0: + param.grad = graddiff_times_z / args.q + else: + param.grad += graddiff_times_z / args.q + # if i_q == args.q - 1: + # self.optimizer.step() # TODO If q > 1, We cannot use this trick anymore. This will cause repeated update. + # # param.data = param.data - graddiff_times_z / args.q # NOTE this q division does not work for q>1. + # param.grad = None + + # for name, param in self.named_parameters_to_optim: + # param.grad = param.grad / args.q + self.optimizer.step() + self.optimizer.zero_grad() + + # No gradient accumulation support + assert self.args.gradient_accumulation_steps == 1 + + return loss1 + + @torch.no_grad() + def zo_step_v2(self, model, inputs): + """ + Estimate gradient by MeZO. Return the loss from f(theta + z) + Works with q > 1. But for q > 1, it is not memory efficient. + """ + args = self.args + + # What parameters to optimize + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + # # TODO avoid init the memory for grad. + # param.grad = torch.zeros_like(param.data) + + seed_list = [] + projected_grad_list = [] + for i_q in range(args.q): # TODO shall we change the seed? + # Sample the random seed for sampling z + self.zo_random_seed = np.random.randint(1000000000) + seed_list.append(self.zo_random_seed) + + # First function evaluation + self.zo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + # Second function evaluation + if self.args.perturbation_mode == "one_side": + self.zo_perturb_parameters(scaling_factor=-1) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / self.args.zo_eps).item() + else: # two side perturbation + self.zo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + + # Reset model back to its parameters at start of step + self.zo_perturb_parameters(scaling_factor=1) + + projected_grad_list.append(self.projected_grad) + + # difference from v1: switch the order of for loop + # to save memory + for name, param in self.named_parameters_to_optim: + for i_q in range(args.q): + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(seed_list[i_q]) + + graddiff_times_z = torch.zeros_like(param.data, device=param.data.device, + dtype=param.data.dtype) + + # Resample z + z = self._safe_normal(mean=0, std=1, size=param.data.size(), device=param.data.device, + dtype=param.data.dtype) + + if args.trainer == "zo_sign_opt": + # ----signOpt_orig + graddiff_times_z += np.sign(projected_grad_list[i_q]) * z + # ----signOpt_mul_sign + # graddiff_times_z = torch.sign(projected_grad_list[i_q] * z) + else: + # ----mezo original + graddiff_times_z += projected_grad_list[i_q] * z + + # # previous implementation + # # no param.grad involved + # param.data -= self._get_learning_rate() * self.projected_grad * z + + # param.grad += graddiff_times_z.detach() + # more mem-efficient: + # run optimizer.step here to avoid caching all grad. + if i_q == args.q - 1: + param.grad = graddiff_times_z.detach() + self.optimizer[name].step() + # param.data = param.data - graddiff_times_z / args.q # NOTE this q division does not work for q>1. + param.grad = None + + # for name, param in self.named_parameters_to_optim: + # param.grad = param.grad / args.q + + # No gradient accumulation support + assert self.args.gradient_accumulation_steps == 1 + + return loss1 + + @torch.no_grad() + def zo_conserv_step(self, model, inputs): + """ + Estimate gradient by MeZO. Return the loss from f(theta + z) + update in the conservative way, i.e. + reject the update if it's not decreasing + """ + args = self.args + + # What parameters to optimize + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + param.grad = None + + loss0 = self.zo_forward(model, inputs) + + # Sample the random seed for sampling z + self.zo_random_seed = np.random.randint(1000000000) + + # First function evaluation + self.zo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + # Second function evaluation + if self.args.perturbation_mode == "one_side": + self.zo_perturb_parameters(scaling_factor=-1) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / self.args.zo_eps).item() + else: # two side perturbation + self.zo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + + # Reset model back to its parameters at start of step + self.zo_perturb_parameters(scaling_factor=1) + + def update_params(sign=1.0): + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(self.zo_random_seed) + for name, param in self.named_parameters_to_optim: + # Resample z + z = self._safe_normal(mean=0, std=1, size=param.data.size(), device=param.data.device, + dtype=param.data.dtype) + + if args.trainer == "zo_sign_opt": + # ----signOpt_orig + # TODo why do we multiply lr here? We will multiply lr twice? + graddiff_times_z = np.sign(self.projected_grad) * z + # ----signOpt_mul_sign + # graddiff_times_z = self._get_learning_rate() * torch.sign(self.projected_grad * z) + else: + # ----mezo original + graddiff_times_z = self.projected_grad * z + + # # previous implementation + # # no param.grad involved + # param.data -= self._get_learning_rate() * self.projected_grad * z + + # param.grad += graddiff_times_z.detach() + # more mem-efficient: + # run optimizer.step here to avoid caching all grad. + param.grad = sign * graddiff_times_z + # self.optimizer[name].step() + self.optimizer.step() + # param.data = param.data - graddiff_times_z / args.q + param.grad = None + + update_params() + loss1 = self.zo_forward(model, inputs) + + update_params(sign=-2.0) + loss2 = self.zo_forward(model, inputs) + + # conduct the update in the conservative way + # choose from the three and take the minimum loss one + if loss1 > loss0: + if loss0 < loss2: + update_params() + else: + if loss1 < loss2: + update_params(2.0) + + # No gradient accumulation support + assert self.args.gradient_accumulation_steps == 1 + + return loss1 + + def zo_update(self, model): + """ + Update the parameters with the estimated gradients. + """ + # # Optimizer step + # self.optimizer.step() + # print(type(self.optimizer), self.optimizer) + self.lr_scheduler.step() # NOTE When we use own optimizer, this will no longer update the lr anymore. + # self.optimizer.zero_grad() + # model.zero_grad() + + @staticmethod + @torch.no_grad() + def functional_call_loss(params, names, buffers, model, batch): + params = {k: v for k, v in zip(names, params)} + outputs = functional_call(model, (params, buffers), tuple(), kwargs=batch) + return outputs + + def forward_grad_step(self, model, inputs): + """ + Forward Gradient Method + + Paper: Gradients without Backpropagation + https://arxiv.org/pdf/2202.08587.pdf + """ + args = self.args + # print(model.__dict__) + # What parameters to optimize + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + param.grad = None + # this is not memory efficient. + # param.grad = torch.zeros_like(param.data) + + # Sample the random seed for sampling vs + self.zo_random_seed = np.random.randint(1000000000) + torch.manual_seed(self.zo_random_seed) + + loss = 0 + vs = [torch.randn_like(p) for _, p in self.named_parameters_to_optim] + + assert args.q == 1, "q > 1" + + # fixme: this is a workaround for device map error when using jvp + inputs = { + k: v.to(device=model.device) if isinstance(v, torch.Tensor) else v for k, v in inputs.items() + } + f = partial( + self.functional_call_loss, + names=[n for n, _ in self.named_parameters_to_optim], buffers=dict(model.named_buffers()), + model=model, batch=inputs + ) + + # jvp profiling + # torch.cuda.reset_peak_memory_stats() + loss_, jvp_ = jvp(f, (list([p for _, p in self.named_parameters_to_optim]),), (vs,)) + # print(f"JVP peak memory usage: {torch.cuda.max_memory_allocated() / 1024 ** 3:.2f} GB") + + # print(len(jvp_), jvp_[0], jvp_[1].shape, len(jvp_[2][0][0])) + # for v, p in zip(vs, [p for _, p in self.named_parameters_to_optim]): + # p.grad += v * jvp_[0].to(p.device) + jvp_ = jvp_[0] + with torch.no_grad(): + for v, (n, p) in zip(vs, [(n, p) for n, p in self.named_parameters_to_optim]): + # p.grad += v * jvp_[0].to(p.device) + # p.grad.add_(v * jvp_[0].to(p.device)) + # grad = v * jvp_[0].to(p.device) / args.q + + if "bias" not in n and "layer_norm" not in n and "layernorm" not in n: + p.data.sub_(self._get_learning_rate() * (v * jvp_.to(p.device) + args.weight_decay * p.data)) + else: + p.data.sub_(self._get_learning_rate() * (v * jvp_.to(p.device))) + loss += loss_[0].item() + + # for name, param in self.named_parameters_to_optim: + # param.grad = param.grad / args.q + + # for name, param in self.named_parameters_to_optim: + # if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + # param.data = param.data - self._get_learning_rate() * (param.grad + args.weight_decay * param.data) + # else: + # param.data = param.data - self._get_learning_rate() * (param.grad) + + return torch.tensor(loss) + + def forward_grad_update(self, model): + """ + Update the parameters with the estimated gradients from forward_grad_step. + """ + args = self.args + # for name, param in self.named_parameters_to_optim: + # if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + # param.data = param.data - self._get_learning_rate() * (param.grad + args.weight_decay * param.data) + # else: + # param.data = param.data - self._get_learning_rate() * (param.grad) + + self.lr_scheduler.step() + + ############## Misc overload functions ############## + + def _set_signature_columns_if_needed(self): + """ + We overload this function for non-differentiable objective training to pass "gold" -- the gold text for the task + """ + if self._signature_columns is None: + # Inspect model forward signature to keep only the arguments it accepts. + signature = inspect.signature(self.model.forward) + self._signature_columns = list(signature.parameters.keys()) + # Labels may be named label or label_ids, the default data collator handles that. + self._signature_columns += list(set(["label", "label_ids"] + self.label_names)) + self._signature_columns += ["gold"] + + def save_model(self, output_dir: Optional[str] = None, _internal_call: bool = False): + """ + We overload this function to fix an FSDP saving bug (before fix, it will likely cause OOM) + """ + + if output_dir is None: + output_dir = self.args.output_dir + + if is_torch_tpu_available(): + self._save_tpu(output_dir) + elif is_sagemaker_mp_enabled(): + # Calling the state_dict needs to be done on the wrapped model and on all processes. + os.makedirs(output_dir, exist_ok=True) + state_dict = self.model_wrapped.state_dict() + if self.args.should_save: + self._save(output_dir, state_dict=state_dict) + if IS_SAGEMAKER_MP_POST_1_10: + # 'user_content.pt' indicates model state_dict saved with smp >= 1.10 + Path(os.path.join(output_dir, "user_content.pt")).touch() + elif ( + ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp + or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp + or self.fsdp is not None + ): + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, StateDictType, FullStateDictConfig + full_state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) + + # Fix the FSDP loading bug + with FSDP.state_dict_type(self.model, StateDictType.FULL_STATE_DICT, full_state_dict_config): + state_dict = self.model.state_dict() + # state_dict = self.model.state_dict() + + if self.args.should_save: + self._save(output_dir, state_dict=state_dict) + elif self.deepspeed: + # this takes care of everything as long as we aren't under zero3 + if self.args.should_save: + self._save(output_dir) + + if is_deepspeed_zero3_enabled(): + # It's too complicated to try to override different places where the weights dump gets + # saved, so since under zero3 the file is bogus, simply delete it. The user should + # either user deepspeed checkpoint to resume or to recover full weights use + # zero_to_fp32.py stored in the checkpoint. + if self.args.should_save: + file = os.path.join(output_dir, WEIGHTS_NAME) + if os.path.isfile(file): + # logger.info(f"deepspeed zero3: removing {file}, see zero_to_fp32.py to recover weights") + os.remove(file) + + # now save the real model if stage3_gather_16bit_weights_on_model_save=True + # if false it will not be saved. + # This must be called on all ranks + if not self.deepspeed.save_16bit_model(output_dir, WEIGHTS_NAME): + logger.warning( + "deepspeed.save_16bit_model didn't save the model, since" + " stage3_gather_16bit_weights_on_model_save=false. Saving the full checkpoint instead, use" + " zero_to_fp32.py to recover weights" + ) + self.deepspeed.save_checkpoint(output_dir) + + elif self.args.should_save: + self._save(output_dir) + + # Push to the Hub when `save_model` is called by the user. + if self.args.push_to_hub and not _internal_call: + self.push_to_hub(commit_message="Model save") diff --git a/baselines/agzo/zo-bench/utils.py b/baselines/agzo/zo-bench/utils.py new file mode 100644 index 0000000..fa5b9bd --- /dev/null +++ b/baselines/agzo/zo-bench/utils.py @@ -0,0 +1,449 @@ +import contextlib +import json +import logging +import signal +import time +from collections.abc import Mapping +from dataclasses import is_dataclass, asdict +from typing import Any, Dict, List, NewType, Optional, Union + +import numpy as np +import torch +import torch.nn.functional as F +import transformers +from torch.nn import CrossEntropyLoss +from transformers.data.data_collator import DataCollatorMixin +from transformers.modeling_outputs import CausalLMOutputWithPast +from transformers.utils import PaddingStrategy +import importlib + +# Prefer shared NPU/CUDA helpers if available +try: + import npu_compat as npu +except Exception: # pragma: no cover + npu = None + +InputDataClass = NewType("InputDataClass", Any) +from dataclasses import dataclass +from transformers.tokenization_utils_base import PreTrainedTokenizerBase + +logger = logging.getLogger(__name__) + +# fixme: only support OPT now +OPT_PERTURBATION_LEVEL_TO_REGEX = { + "transformer-block": r".*model\.decoder\.layers\.[0-9]+$" + r"|.*model\.decoder\.embed_.*" + r"|.*model\.decoder\.final_layer_norm$", + "mlp-attn": r".*model\.decoder\.layers\.[0-9]+\.self_attn$" + r"|.*model\.decoder\.layers\.[0-9]+\.fc[12]$" + r"|.*model\.decoder\.layers\.[0-9]+\.final_layer_norm$" + r"|.*model\.decoder\.layers\.[0-9]+\.self_attn_layer_norm$" + r"|.*model\.decoder\.embed_.*" + r"|.*model\.decoder\.final_layer_norm$", + "linear": r".*model\.decoder\.layers\.[0-9]+\.self_attn.[qkv]_proj$" + r"|.*model\.decoder\.layers\.[0-9]+\.self_attn.out_proj$" + r"|.*model\.decoder\.layers\.[0-9]+\.fc[12]$" + r"|.*model\.decoder\.layers\.[0-9]+\.final_layer_norm$" + r"|.*model\.decoder\.layers\.[0-9]+\.self_attn_layer_norm$" + r"|.*model\.decoder\.embed_.*" + r"|.*model\.decoder\.final_layer_norm$", +} + + +def forward_wrap_with_option_len( + self, + input_ids=None, + labels=None, + option_len=None, + num_options=None, + return_dict=None, + **kwargs +): + """ + This is to replace the original forward function of Transformer models to enable: + (1) Partial target sequence: loss will only be calculated on part of the sequence + (2) Classification-style training: a classification loss (CE) will be calculated over several options + Input: + - input_ids, labels: same as the original forward function + - option_len: a list of int indicating the option lengths, and loss will be calculated only on the + last option_len tokens + - num_options: a list of int indicating the number of options for each example (this will be #label + words for classification tasks and #choices for multiple choice tasks), and a classification loss + will be calculated. + """ + outputs = self.original_forward(input_ids=input_ids, **kwargs) + if labels is None: + return outputs + + # in prompt tuning, we need to remove the virtual tokens from the logits to match the input ids + # Prefer logits from the model output; if absent, try to derive from hidden states + logits = getattr(outputs, "logits", None) + if logits is None: + # Try to get hidden states in a model-agnostic way + hidden_states = None + if isinstance(outputs, (tuple, list)) and len(outputs) > 0: + hidden_states = outputs[0] + else: + hidden_states = getattr(outputs, "last_hidden_state", None) + + if hidden_states is not None: + # If model exposes lm_head, use it + if hasattr(self, "lm_head") and self.lm_head is not None: + logits = self.lm_head(hidden_states) + # Otherwise try get_output_embeddings (tied embeddings as LM head) + elif hasattr(self, "get_output_embeddings") and (self.get_output_embeddings() is not None): + output_emb = self.get_output_embeddings() + # Linear projection with tied embeddings; add bias if present + weight = getattr(output_emb, "weight", None) + bias = getattr(output_emb, "bias", None) + if weight is None: + raise AttributeError("Model's output embeddings lack weight; cannot derive logits.") + logits = torch.matmul(hidden_states, weight.T) + if bias is not None: + logits = logits + bias + else: + raise AttributeError( + "Model output has no logits and model lacks LM head; " + "please use a causal LM (AutoModelForCausalLM) rather than a base/embedding model." + ) + else: + raise AttributeError( + "Forward output missing both logits and hidden states; cannot compute loss." + ) + + loss = None + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + # Here we use input_ids (which should always = labels) bc sometimes labels are correct candidate IDs + shift_labels = torch.clone(input_ids)[..., 1:].contiguous() + shift_labels[shift_labels == self.config.pad_token_id] = -100 + + # Apply option len (do not calculate loss on the non-option part) + # for _i, _len in enumerate(option_len): + # shift_labels[_i, :-_len] = -100 + # re-write the above code to avoid the for loop + non_option_len = shift_labels.shape[1] - option_len + mask = torch.arange( + shift_labels.shape[1], device=shift_labels.device + ).expand(shift_labels.shape[0], -1) < non_option_len.unsqueeze(-1) + shift_labels[mask] = -100 + + # Calculate the loss + loss_fct = CrossEntropyLoss(ignore_index=-100) + if num_options is not None: + # Train as a classification tasks + log_probs = F.log_softmax(shift_logits, dim=-1) + mask = shift_labels != -100 # Option part + shift_labels[~mask] = 0 # So that it doesn't mess up with indexing + + selected_log_probs = torch.gather(log_probs, dim=-1, index=shift_labels.unsqueeze(-1)).squeeze( + -1) # (bsz x num_options, len) + selected_log_probs = (selected_log_probs * mask).sum(-1) / mask.sum(-1) # (bsz x num_options) + + if any([x != num_options[0] for x in num_options]): + # Multi choice tasks with different number of options + loss = 0 + start_id = 0 + count = 0 + while start_id < len(num_options): + end_id = start_id + num_options[start_id] + _logits = selected_log_probs[start_id:end_id].unsqueeze(0) # (1, num_options) + _labels = labels[start_id:end_id][0].unsqueeze(0) # (1) + loss = loss_fct(_logits, _labels) + loss + count += 1 + start_id = end_id + loss = loss / count + else: + num_options = num_options[0] + selected_log_probs = selected_log_probs.view(-1, num_options) # (bsz, num_options) + labels = labels.view(-1, num_options)[:, 0] # Labels repeat so we only take the first one + loss = loss_fct(selected_log_probs, labels) + else: + loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +def encode_prompt(task, template, train_samples, eval_sample, tokenizer, max_length, sfc=False, icl_sfc=False, + generation=False, generation_with_gold=False, max_new_tokens=None): + """ + Encode prompts for eval_sample + Input: + - task, template: task and template class + - train_samples, eval_sample: demonstrations and the actual sample + - tokenizer, max_length: tokenizer and max length + - sfc: generate prompts for calibration (surface form competition; https://arxiv.org/abs/2104.08315) + - icl_sfc: generate prompts for ICL version calibration + - generation: whether it is an generation task + - generation_with_gold: whether to include the generation-task gold answers (for training) + - max_new_tokens: max number of new tokens to generate so that we can save enough space + (only for generation tasks) + Output: + - encodings: a list of N lists of tokens. N is the number of options for classification/multiple-choice. + - option_lens: a list of N integers indicating the number of option tokens. + """ + + # Demonstrations for ICL + train_prompts = [template.verbalize(sample, sample.correct_candidate).strip() for sample in train_samples] + train_prompts = task.train_sep.join(train_prompts).strip() + + # sfc or icl_sfc indicates that this example is used for calibration + if sfc or icl_sfc: + encode_fn = template.encode_sfc + verbalize_fn = template.verbalize_sfc + else: + encode_fn = template.encode + verbalize_fn = template.verbalize + + unverbalized_eval_prompt = encode_fn(eval_sample).strip(' ') + if not generation: + # We generate one prompt for each candidate (different classes in classification) + # or different choices in multiple-choice tasks + verbalized_eval_prompts = [verbalize_fn(eval_sample, cand).strip(' ') for cand in eval_sample.candidates] + unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt)) + option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for + verbalized_eval_prompt in verbalized_eval_prompts] + + if sfc: + # Without demonstrations + final_prompts = verbalized_eval_prompts + else: + # With demonstrations + final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in + verbalized_eval_prompts] + else: + assert not sfc and not icl_sfc, "Generation tasks do not support SFC" + if generation_with_gold: + verbalized_eval_prompts = [verbalize_fn(eval_sample, eval_sample.correct_candidate)] + unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt)) + option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for + verbalized_eval_prompt in verbalized_eval_prompts] + final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in + verbalized_eval_prompts] + else: + option_lens = [0] + final_prompts = [(train_prompts + task.train_sep + unverbalized_eval_prompt).lstrip().strip(' ')] + + # Tokenize + encodings = [tokenizer.encode(final_prompt) for final_prompt in final_prompts] + + # Truncate (left truncate as demonstrations are less important) + if generation and max_new_tokens is not None: + max_length = max_length - max_new_tokens + + if any([len(encoding) > max_length for encoding in encodings]): + logger.warn("Exceed max length") + if hasattr(tokenizer, 'add_bos_token') and tokenizer.add_bos_token: + encodings = [encoding[0:1] + encoding[1:][-(max_length - 1):] for encoding in encodings] + else: + encodings = [encoding[-max_length:] for encoding in encodings] + + return encodings, option_lens + + +@dataclass +class ICLCollator: + """ + Collator for ICL + """ + tokenizer: PreTrainedTokenizerBase + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + if not isinstance(features[0], Mapping): + features = [vars(f) for f in features] + first = features[0] + batch = {} + + pad_id = self.tokenizer.pad_token_id + + pad_ids = {"input_ids": pad_id, "attention_mask": 0, "sfc_input_ids": pad_id, "sfc_attention_mask": 0, + "labels": pad_id} + for key in first: + pp = pad_ids[key] + lens = [len(f[key]) for f in features] + max_len = max(lens) + feature = np.stack([np.pad(f[key], (0, max_len - lens[i]), "constant", constant_values=(0, pp)) for i, f in + enumerate(features)]) + padded_feature = torch.from_numpy(feature).long() + batch[key] = padded_feature + + return batch + + +@dataclass +class DataCollatorWithPaddingAndNesting: + """ + Collator for training + """ + + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str, PaddingStrategy] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + return_tensors: str = "pt" + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + features = [ff for f in features for ff in f] + batch = self.tokenizer.pad( + features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors=self.return_tensors, + ) + if "label" in batch: + batch["labels"] = batch["label"] + del batch["label"] + if "label_ids" in batch: + batch["labels"] = batch["label_ids"] + del batch["label_ids"] + return batch + + +@dataclass +class NondiffCollator(DataCollatorMixin): + """ + Collator for non-differentiable objectives + """ + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str, PaddingStrategy] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + label_pad_token_id: int = -100 + return_tensors: str = "pt" + + def torch_call(self, features): + import torch + + label_name = "label" if "label" in features[0].keys() else "labels" + labels = [feature[label_name] for feature in features] if label_name in features[0].keys() else None + + no_labels_features = [{k: v for k, v in feature.items() if k != label_name and k != "gold"} for feature in + features] + + batch = self.tokenizer.pad( + no_labels_features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors="pt", + ) + + if labels is None: + return batch + + sequence_length = batch["input_ids"].shape[1] + padding_side = self.tokenizer.padding_side + + def to_list(tensor_or_iterable): + if isinstance(tensor_or_iterable, torch.Tensor): + return tensor_or_iterable.tolist() + return list(tensor_or_iterable) + + if padding_side == "right": + batch[label_name] = [ + to_list(label) + [self.label_pad_token_id] * (sequence_length - len(label)) for label in labels + ] + else: + batch[label_name] = [ + [self.label_pad_token_id] * (sequence_length - len(label)) + to_list(label) for label in labels + ] + + batch[label_name] = torch.tensor(batch[label_name], dtype=torch.int64) + if "gold" in features[0]: + batch["gold"] = [feature["gold"] for feature in features] + + return batch + + +class SIGUSR1Callback(transformers.TrainerCallback): + """ + This callback is used to save the model when a SIGUSR1 signal is received + (SLURM stop signal or a keyboard interruption signal). + """ + + def __init__(self) -> None: + super().__init__() + self.signal_received = False + signal.signal(signal.SIGUSR1, self.handle_signal) + signal.signal(signal.SIGINT, self.handle_signal) + logger.warn("Handler registered") + + def handle_signal(self, signum, frame): + self.signal_received = True + logger.warn("Signal received") + + def on_step_end(self, args, state, control, **kwargs): + if self.signal_received: + control.should_save = True + control.should_training_stop = True + + def on_train_end(self, args, state, control, **kwargs): + if self.signal_received: + exit(0) + + +@dataclass +class Prediction: + correct_candidate: Union[int, str] + predicted_candidate: Union[int, str] + + +@contextlib.contextmanager +def count_time(name): + logger.info("Starting %s ..." % name) + start_time = time.time() + try: + yield + finally: + logger.info("Done with %.2fs" % (time.time() - start_time)) + + +# Global context for count_time enrichment +_COUNT_TIME_CTX: Dict[str, Any] = {} + + +def set_count_time_context(model_name: Optional[str] = None): + """Set optional context for count_time logs (e.g., current model name).""" + try: + if model_name is not None: + _COUNT_TIME_CTX["model_name"] = model_name + except Exception: + pass + + +@contextlib.contextmanager +def temp_seed(seed): + state = np.random.get_state() + np.random.seed(seed) + try: + yield + finally: + np.random.set_state(state) + + +class EnhancedJSONEncoder(json.JSONEncoder): + def default(self, o): + if is_dataclass(o): + return asdict(o) + return super().default(o) + + +def write_predictions_to_file(final_preds, output): + with open(output, "w") as f: + for pred in final_preds: + f.write(json.dumps(pred, cls=EnhancedJSONEncoder) + "\n") + + +def write_metrics_to_file(metrics, output): + json.dump(metrics, open(output, "w"), cls=EnhancedJSONEncoder, indent=4) diff --git a/baselines/loren/.python-version b/baselines/loren/.python-version new file mode 100644 index 0000000..ed7d51a --- /dev/null +++ b/baselines/loren/.python-version @@ -0,0 +1 @@ +3.11.15 diff --git a/baselines/loren/LICENSE b/baselines/loren/LICENSE new file mode 100644 index 0000000..70256a2 --- /dev/null +++ b/baselines/loren/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Hyunseok Seung + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/baselines/loren/README.md b/baselines/loren/README.md new file mode 100644 index 0000000..559346c --- /dev/null +++ b/baselines/loren/README.md @@ -0,0 +1,103 @@ +# Low-Rank Curvature for Zeroth-Order Optimization in LLM Fine-Tuning + +This repository provides the official implementation of **LOREN**, a curvature-aware zeroth-order (ZO) optimization +method for efficient fine-tuning of LLMs. LOREN adaptively learns a **low-rank curvature preconditioner** and integrates +it with REINFORCE leave-one-out (RLOO) estimator to **reduce variance**, achieving superior convergence, accuracy, and memory efficiency compared to existing ZO methods. + +> Accepted at **AAAI Conference on Artificial Intelligence (AAAI-26)**, Singapore, January 2026. +--- + +## Overview + +LOREN reformulates preconditioned ZO optimization as *learning an anisotropic perturbation distribution* that captures +local curvature. It combines: +- **Rank-1 block-diagonal preconditioning** to encode curvature efficiently. +- **RLOO variance reduction** to stabilize and denoise gradient estimates. + +### Benchmark Results +

+ GPT-2-XL QNLI + OPT-13B BoolQ +

+ +

+ Figure 1: Test accuracy curves for GPT-2-XL fine-tuned on QNLI and OPT-13B fine-tuned on CB, using early stopping. +

+ +

+ OPT13B +

+ +

+ Figure 2: Training loss curves for different ZO optimizers when fine-tuning OPT-13B on SuperGLUE tasks. +

+ +--- + +## Models + +| Family | Model | +|:-----------|:--| +| DistilBERT | `distilbert-base-cased` | +| RoBERTa | `roberta-large` | +| GPT | `gpt2-xl` | +| OPT | `facebook/opt-2.7b`, `facebook/opt-13b` | +| LLaMA | `meta-llama/Meta-Llama-3-8B` | + +## Tasks + +**GLUE:** `mnli`, `qnli`, `sst2`, `cola` +**SuperGLUE:** `rte`, `boolq`, `wic`, `cb` + +## Algorithms +| Algorithm | Description | Reference | +|:--------------|:----------------------------------------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| `ZO` | Baseline memory-efficient ZO | [Malladi et al., 2023, *Fine-Tuning Language Models with Just Forward Passes*](https://proceedings.neurips.cc/paper_files/paper/2023/file/a627810151be4d13f907ac898ff7e948-Paper-Conference.pdf) | +| `ZOAdam` | MeZO with Adam's adaptive update | | +| `ZOSVRG` | MeZO with stochastic variance-reduced gradients | [Gautam et al., 2024, *Variance-reduced Zeroth-Order Methods for Fine-Tuning Language Models*](https://openreview.net/pdf?id=yc758jO4i5) | +| `LOZO` | Low-rank ZO gradient | [Chen et al., 2025, *Enhancing Zeroth-Order Fine-Tuning for Language Models with Low-Rank Structures*](https://openreview.net/pdf?id=9BiVepgmWW) | +| `HiZOO` | Hessian informed ZO | [Zhao et al., 2025, *Second-Order Fine-Tuning without Pain for LLMs: A Hessian Informed Zeroth-Order Optimizer*](https://openreview.net/forum?id=bEqI61iBue) | +| `LOREN`(ours) | Low-rank curvature-aware ZO with variance reduction | Seung et al., 2026, *Low-Rank Curvature for Zeroth-Order Optimization in LLM Fine-Tuning* | + +--- + +## How to Run + +Fine-tune a model with a chosen algorithm: + +``` shell +python main.py\ + --epochs $epochs \ + --model_name $model \ + --task $task \ + --algorithm $algorithm \ + --lr $lr \ + --weight_decay 0.0 \ + --num_queries $num_queries \ # Default: 2 (MeZO, LOZO, MeZO-Adam), 3 (MeZO-SVRG, HiZOO) + --perturbation_scale 1e-3 \ + --lr_mezosvrg_mb 1e-6 --q 2 --anneal 5 \ # MeZO-SVRG + --eps 1e-8 \ # MeZO-Adam + --rank 2 --step_interval 50 \ # LOZO + --hessian_smooth_type constant1e-8 \ # HiZOO + --lr_cov 1e-3 --damping 0.1 \ # LOREN + --samplesize 512 --samplesize_validation 256 \ + --batchsize $bsz \ + --batchsize_limit $bsz_lim \ + --full_parameter \ + --max_seq_length 128 \ + --device 0 --save_every 10000000 --logging csv \ + --init_seed 42 --trial $trial \ + --early_stopping --patience 1000 +``` + +--- + +## Citation +``` +@inproceedings{seung2026lowrank, +title={Low-Rank Curvature for Zeroth-Order Optimization in LLM Fine-tuning}, +author={Seung, Hyunseok and Lee, Jaewoo and Ko, Hyunsuk}, +booktitle={The Fortieth AAAI Conference on Artificial Intelligence}, +year={2026}, +} +``` \ No newline at end of file diff --git a/baselines/loren/TROUBLESHOOTING.md b/baselines/loren/TROUBLESHOOTING.md new file mode 100644 index 0000000..9cc4686 --- /dev/null +++ b/baselines/loren/TROUBLESHOOTING.md @@ -0,0 +1,81 @@ +# LOREN:独立环境、入口与排障 + +官方来源:https://github.com/hseung88/loren.git;锁定提交:`b80a32bc394332d1a1f115f41dfb5dcf7b326d37`。 +官方文件保留原样;此目录新增 pyproject.toml、uv.lock、native.py、run_compatible.py 和本文。 +原仓库 Git 历史存放在被忽略的 `.upstream-git/`,防止主项目意外把整个目录当成 gitlink。 +查看上游版本:`git --git-dir=.upstream-git --work-tree=. rev-parse HEAD`。 +不要在这个目录执行普通 git commit/push;主项目尚未提交。 + +## 安装与版本 + +在 WSL 中执行(不需要激活根目录环境): + +```bash +cd ~/experiments_codebase +source scripts/env.sh +cd baselines/loren +uv sync --locked +uv run --locked python native.py --help +``` + +此目录 `.venv` 独立,Python 3.11,torch 2.13.0,原生 Transformers 4.44.2。 +直接依赖精确版本写在 pyproject.toml,全部间接依赖和 wheel 哈希写在 uv.lock。 +`uv sync --locked` 默认 native;`uv sync --locked --no-default-groups --group modern` 切换到 Transformers 4.57.1。 +两组互斥,使用同一个本库 `.venv`,不会激活其他方法的环境。不要使用 `uv pip install -U` 绕开锁。 + +## 官方入口及命令 + +原入口 `main.py`。本地资源包装入口 `native.py` 仅设置共享路径、提供本地 Dataset 和启动参数,然后运行原始程序。 +`--asset-model`、`--asset-task`、`--asset-out` 是包装参数,其余参数透传官方入口;以 `--help` 为准。 +MeZO/LOZO/AGZO包装器默认固定 train_set_seed=42,并将result_file显式指向共享输出;否则原版会因num_dev配合空采样seed触发断言,或因相对result目录缺失在训练完成后报错。用户后置同名参数可覆盖这些默认值。 + +```bash +uv run --locked python native.py --asset-model facebook/opt-1.3b --asset-task sst2 --epochs 1 --samplesize 4 --samplesize_validation 4 --batchsize 2 --batchsize_limit 2 --lr 1e-6 --num_queries 2 --perturbation_scale 1e-3 --damping 0.1 --lr_cov 1e-3 --weight_decay 0 --max_seq_length 64 --logging csv --init_seed 42 +``` + +调参请使用官方参数:学习率 `--lr`,差分半径 `--perturbation_scale`,batch `--batchsize`。 +参数覆盖:MeZO/LOZO/AGZO 默认 full(不传 LoRA/prefix/head-only 开关);LOREN 包装器显式传 `--full_parameter`。 +全参数覆盖不等于无结构全维搜索;LOZO/AGZO 仍使用结构化扰动。 + +## Qwen3 / DROP 与统一比较入口 + +```bash +uv run --locked --no-default-groups --group modern python run_compatible.py --model Qwen/Qwen3-0.6B --task sst2 --budget 12 --train-samples 16 --dev-samples 4 --eval-samples 4 --batch-size 2 --eval-batch-size 2 --calibration-samples 2 --no-save-checkpoint +# DROP:将 --task 改为 drop,并合理增加 --max-length(短冒烟可以先用128)。 +``` + +兼容层 `../../src/experiments_codebase/official.py` 从本库源码编译官方数值函数;不导入旧 Trainer,也不另写一套公式。 +通用数据协议和计账在 `../../src/experiments_codebase/task.py`、`runner.py`。 +此入口统一 SST2 为两 verbalizer 的交叉熵、DROP 为答案 token 的 teacher-forced CE;它与部分官方任务目标不同,日志会标记 task adapter。 +预算为总 main forward,而非更新步数;检测和基提取前向不免费。评估前向另列。 +不支持从兼容检查点续训;可用 `--action evaluate --checkpoint ...` 或 `--action generate --checkpoint ... --prompt ...` 推理。 + +## 核心位置 + +- 核心算法:`model/glue_transformer_loren.py: configure_params / perturb_parameters / lnes_zo_update`。 +- 模型/数据:`model/glue_transformer.py; dataset/glue.py; trainer/`。 +- 官方超参数原型:入口中的参数 dataclass/parser 与原始 shell 脚本;与本站兼容入口参数不是同一命名空间。 + +## 系统组件与常见问题 + +原生任务是 GLUE/SuperGLUE;模型分支没有 Qwen,任务分支没有 DROP。原生入口不支持这两个扩展。modern 兼容入口可把同一官方数值核用于 Qwen/DROP,但不是作者端到端任务复现。原生使用分类模型/新分类头,兼容入口使用因果模型 verbalizer,两者成绩不能直接混为同一协议。 + +WSL 必须能看到 NVIDIA 驱动:先运行 `nvidia-smi`。RTX 5070 Ti 是 Blackwell;原论文旧版 torch/CUDA wheel 不支持其架构。 +本机选用支持当前显卡的 torch 2.13.0,不声称完全复刻论文年代的二进制环境。 +CUDA runtime 随 wheel 安装,普通运行无需 nvcc;自编译第三方扩展才需要 CUDA toolkit、gcc/g++、make、Python headers。 +Fedora 常见系统依赖:`git curl ca-certificates libgomp libstdc++`;缺库先用 `ldd` 核查,不要盲目替换驱动。 +uv 会下载 Python 3.11,不依赖系统 Python 3.14;保持 `.python-version`。 +如果 WSL 解析到 198.18.* 且直连超时,可在未跟踪的根 `.env` 配置你现有代理,再 `source ../../scripts/env.sh`;不要把代理/token 写入源码。 +本次用临时 HTTP(S)_PROXY 沿用主机代理;未修改系统网络配置。 +`huggingface-hub` 不能随意升到2.x:Transformers 4.x 需要 <1.0。已锁0.36.0。 +新版setuptools移除了pkg_resources,旧Trainer/accelerate仍导入它;锁80.9.0同时满足torch要求的>=77.0.3。LOREN官方requirements漏列loguru,本环境已补0.7.3。 +旧 datasets/pyarrow/numpy 有 ABI 约束,三者必须遵守 uv.lock;不能拿现代 `.venv` 的 site-packages 混入原生环境。 +共享DROP不能用datasets5.x的List元数据序列化后直接给2.x/3.x读;请在根锁定环境datasets3.6执行prepare_assets,工具可从原始parquet重建不兼容资产。 +E盘必须真实挂载。Assets默认位于 `/mnt/e/Experiments/Assets`,包装器在写入前检查 mountpoint。 +模型和数据只从本地共享目录读取;资产缺失先在根环境运行 `scripts/prepare_assets.py --download-missing`。 +Qwen的词表较大,长序列或大 batch 会增显存;先减batch/长度,不要把OOM归因于优化算法。 + +## 验证状态 + +以根目录 `reports/validation_report.json` 和 `reports/validation.log` 为准,区分安装、导入、短步训练、模型任务矩阵。 +`--help` 通过不代表训练通过,短步通过也不代表论文精度复现。未完成项目会明确记录。 diff --git a/baselines/loren/common/__init__.py b/baselines/loren/common/__init__.py new file mode 100644 index 0000000..5ebea80 --- /dev/null +++ b/baselines/loren/common/__init__.py @@ -0,0 +1,4 @@ +from .logging import get_logger + + +__all__ = ['get_logger'] diff --git a/baselines/loren/common/alg_utils.py b/baselines/loren/common/alg_utils.py new file mode 100644 index 0000000..69c6bd5 --- /dev/null +++ b/baselines/loren/common/alg_utils.py @@ -0,0 +1,73 @@ +import math +import torch + + +@torch.no_grad() +def generate_basis(m, rank, ref_mat, orthogonal=False): + Z = torch.randn(m, rank, dtype=ref_mat.dtype, device=ref_mat.device) + + if orthogonal is True: + U, S, Vt = torch.linalg.svd(Z.T @ Z) + S = 1. / torch.sqrt(S) + return (Z @ U @ torch.diag(S) @ Vt) * math.sqrt(rank) + else: + return Z + + +@torch.no_grad() +def sgd_with_wdecay(param, grad, lr, weight_decay): + param.mul_(1 - lr * weight_decay) + param.add_(grad, alpha=-lr) + + +@torch.no_grad() +def ema_update(param, grad, lr, weight_decay, beta): + updated_param = param.mul(1 - lr * weight_decay) + updated_param.add_(grad, alpha=-lr) + + param.mul_(beta).add_(updated_param, alpha=1.0 - beta) + + +def exponential_cooling_schedule(initial_temp, alpha, iteration): + """ + Exponential cooling schedule function for simulated annealing. + + Parameters: + initial_temp (float): The initial temperature. + alpha (float): The cooling rate (0 < alpha < 1). + iteration (int): The current iteration number. + + Returns: + float: The temperature at the given iteration. + """ + return initial_temp * (alpha ** iteration) + + +def logarithmic_cooling_schedule(initial_temp, iteration): + """ + Logarithmic cooling schedule function for simulated annealing. + + Parameters: + initial_temp (float): The initial temperature. + iteration (int): The current iteration number. + + Returns: + float: The temperature at the given iteration. + """ + return initial_temp / (1 + math.log(1 + iteration)) + + +def linear_cooling_schedule(initial_temp, final_temp, max_iterations, iteration): + """ + Linear cooling schedule function for simulated annealing. + + Parameters: + initial_temp (float): The initial temperature. + final_temp (float): The final temperature. + max_iterations (int): The maximum number of iterations. + iteration (int): The current iteration number. + + Returns: + float: The temperature at the given iteration. + """ + return initial_temp - (initial_temp - final_temp) * (iteration / max_iterations) diff --git a/baselines/loren/common/hessian_smooth_scheduler.py b/baselines/loren/common/hessian_smooth_scheduler.py new file mode 100644 index 0000000..e21ae5d --- /dev/null +++ b/baselines/loren/common/hessian_smooth_scheduler.py @@ -0,0 +1,208 @@ +import math +import warnings +from functools import partial +from typing import Callable, Iterable, Optional, Tuple, Union + +import torch +from torch import nn +# from torch.optim import Optimizer +# from torch.optim.lr_scheduler import LambdaLR, ReduceLROnPlateau + +from transformers.utils import logging +from transformers.utils.versions import require_version + +logger = logging.get_logger(__name__) + + +def get_reduce_on_plateau_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step, + num_training_steps): + # to be updated + return learning_rate + + +def _get_inverse_sqrt_schedule_lr_lambda(current_step: int, *, num_warmup_steps: int, timescale: int = None): + if current_step < num_warmup_steps: + return float(current_step) / float(max(1, num_warmup_steps)) + shift = timescale - num_warmup_steps + decay = 1.0 / math.sqrt((current_step + shift) / timescale) + return decay + + +def get_inverse_sqrt_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step, num_training_steps): + # to be updated + return learning_rate + + +def get_constant_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step, + num_training_steps): + if current_step < num_warmup_steps: + return float(current_step) / float(max(1.0, num_warmup_steps)) * learning_rate + + return learning_rate + + +def get_linear_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step, + num_training_steps): + if current_step < num_warmup_steps: + return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate + return max(0.0, float(num_training_steps - current_step) / float( + max(1, num_training_steps - num_warmup_steps))) * learning_rate + + +def get_cosine_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step, + num_training_steps): + num_cycles = 2 + if current_step < num_warmup_steps: + return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate + progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps)) + return max(0.0, 0.5 * (1.0 + math.cos(math.pi * float(num_cycles) * 2.0 * progress))) * learning_rate + + +def get_cosine_with_hard_restarts_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, + current_step, num_training_steps): + num_cycles = 2 + if current_step < num_warmup_steps: + return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate + progress = float(current_step - num_warmup_steps) / float(max(1, num_training_steps - num_warmup_steps)) + if progress >= 1.0: + return 0.0 * learning_rate + return max(0.0, 0.5 * (1.0 + math.cos(math.pi * ((float(num_cycles) * progress) % 1.0)))) * learning_rate + + +def get_polynomial_decay_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, current_step, + num_training_steps): + lr_init = learning_rate + lr_end = 1e-10 + power = 3 + if current_step < num_warmup_steps: + return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate + elif current_step > num_training_steps: + return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init + else: + lr_range = lr_init - lr_end + decay_steps = num_training_steps - num_warmup_steps + pct_remaining = 1 - (current_step - num_warmup_steps) / decay_steps + decay = lr_range * pct_remaining ** power + lr_end + return decay / lr_init * learning_rate # as LambdaLR multiplies by lr_init + + +def get_polynomial_decay_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step, + num_training_steps): + lr_init = learning_rate + lr_end = 1e-10 + power = 3 + if current_step > num_training_steps: + return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init + else: + lr_range = lr_init - lr_end + decay_steps = num_training_steps - 0 + pct_remaining = 1 - (current_step - 0) / decay_steps + decay = lr_range * pct_remaining ** power + lr_end + return decay / lr_init * learning_rate # as LambdaLR multiplies by lr_init + + +def get_constant_polynomial_decay_schedule(learning_rate, name, num_warmup_steps, num_decay_steps, current_step, + num_training_steps): + lr_init = learning_rate + lr_end = 1e-10 + power = 3 + if current_step < num_decay_steps: + return learning_rate + elif current_step > num_training_steps: + return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init + else: + lr_range = lr_init - lr_end + decay_steps = num_training_steps - num_decay_steps + pct_remaining = 1 - (current_step - num_decay_steps) / decay_steps + decay = lr_range * pct_remaining ** power + lr_end + return decay / lr_init * learning_rate / 100 # as LambdaLR multiplies by lr_init + + +def get_constant_decay1_schedule(current_step, num_training_steps): + if current_step < 9800: + return 1e-6 + else: + return 1e-8 + + +def get_constant6_schedule(current_step, num_training_steps): + return 1e-6 + + +def get_constant8_schedule(current_step, num_training_steps): + return 1e-8 + + +def get_constant10_schedule(current_step, num_training_steps): + return 1e-10 + + +def get_constant12_schedule(current_step, num_training_steps): + return 1e-12 + + +def get_constant4_schedule(current_step, num_training_steps): + return 1e-4 + + +def get_constant2_schedule(current_step, num_training_steps): + return 1e-2 + + +def get_constant0_schedule(current_step, num_training_steps): + return 0 + + +def get_constant_schedule_with_warmup(current_step, num_training_steps): + if current_step < num_warmup_steps: + return float(current_step) / float(max(1.0, num_warmup_steps)) * 1e-6 + + return 0 + + +def get_constant_polynomial_decay_schedule_with_warmup(learning_rate, name, num_warmup_steps, num_decay_steps, + current_step, num_training_steps): + lr_init = learning_rate + lr_end = 1e-7 + power = 3 + if current_step < num_warmup_steps: + return float(current_step) / float(max(1, num_warmup_steps)) * learning_rate + elif current_step >= num_warmup_steps and current_step < num_decay_steps: + return learning_rate + elif current_step > num_training_steps: + return lr_end / lr_init * learning_rate # as LambdaLR multiplies by lr_init + else: + lr_range = lr_init - lr_end + decay_steps = num_training_steps - num_decay_steps + pct_remaining = 1 - (current_step - num_decay_steps) / decay_steps + decay = lr_range * pct_remaining ** power + lr_end + return decay / lr_init * learning_rate # as LambdaLR multiplies by lr_init + + +TYPE_TO_SCHEDULER_FUNCTION = { + 'linear_with_warmup': get_linear_schedule_with_warmup, + 'cosine_with_warmup': get_cosine_schedule_with_warmup, + 'cosine_with_hard_restarts_with_warmup': get_cosine_with_hard_restarts_schedule_with_warmup, + 'polynomial_decay_with_warmup': get_polynomial_decay_schedule_with_warmup, + 'inverse_sqrt': get_inverse_sqrt_schedule, + 'reduce_on_plateau': get_reduce_on_plateau_schedule, + 'constant_polynomial_decay': get_constant_polynomial_decay_schedule, + 'constant_polynomial_decay_with_warmup': get_constant_polynomial_decay_schedule_with_warmup, + 'polynomial_decay': get_polynomial_decay_schedule, + 'constant0': get_constant0_schedule, + 'constant1e-6': get_constant6_schedule, + 'constant1e-8': get_constant8_schedule, + 'constant1e-10': get_constant10_schedule, + 'constant1e-12': get_constant12_schedule, + 'constant1e-2': get_constant2_schedule, + 'constant1e-4': get_constant4_schedule, + 'constant_with_warmup': get_constant_schedule_with_warmup, + 'constant_decay1': get_constant_decay1_schedule, + +} + + +def Hessian_smooth_scheduler(Hessian_smooth_type, current_step, num_training_steps): + schedule_func = TYPE_TO_SCHEDULER_FUNCTION[Hessian_smooth_type] + + return schedule_func(current_step, num_training_steps) \ No newline at end of file diff --git a/baselines/loren/common/logging.py b/baselines/loren/common/logging.py new file mode 100644 index 0000000..3f68084 --- /dev/null +++ b/baselines/loren/common/logging.py @@ -0,0 +1,39 @@ +import sys +from loguru import logger + +__all__ = ["get_logger"] + + +logger_sink = {} +LOG_FORMAT = ( + "[{time:MM-DD HH:mm:ss}] " + # "[{process.name}]|" + # "{level: <6} " + # "{name}:{function}:{line}\n\t - {message}\n" + "{function}:{line:<4}| {message}" +) +logger.remove() + + +def get_logger(file_name=None, clear=False, **kwargs): + global logger_sink + + if clear: + logger.remove() + logger_sink.clear() + + if file_name is None: + file_name = sys.stderr + if "level" not in kwargs: + kwargs["level"] = "INFO" + + if "format" not in kwargs: + kwargs["format"] = LOG_FORMAT + + if file_name in logger_sink.values(): + logger.debug(f"{str(file_name)} already registered") + else: + sink_id = logger.add(file_name, **kwargs) + logger_sink[sink_id] = file_name + logger.debug(f"sink_id: {sink_id:02d} ---> {str(file_name)}") + return logger diff --git a/baselines/loren/common/utils.py b/baselines/loren/common/utils.py new file mode 100644 index 0000000..a5f5aaa --- /dev/null +++ b/baselines/loren/common/utils.py @@ -0,0 +1,171 @@ +import os +import pickle +import torch +import contextlib + +import numpy as np + +import matplotlib +import matplotlib.pyplot as plt + + +matplotlib.rcParams['pdf.fonttype'] = 42 +plt.rcParams.update({'font.size': 12}) + + +def save_pickle(data, folder, filename): + os.makedirs(folder, exist_ok=True) + filepath = os.path.join(folder, filename) + with open(filepath, 'wb') as file: + pickle.dump(data, file) + + +def load_pickle(file_path, key): + try: + with open(file_path, 'rb') as file: + # Load the data from the pickle file + data = pickle.load(file) + + # Print the contents of the pickle file + print("Contents of the pickle file:") + if key == 'Tr_Loss': + arr = windowed_mean(data[key], window_size=4) + print(np.nanmin(arr)) + elif key == 'Val_Acc': + arr = windowed_mean(data[key], window_size=4) + print(np.max(arr)) + elif key == 'Query': + print(np.sum(data[key])) + else: + print(data[key]) + + except FileNotFoundError: + print(f"Error: File '{file_path}' not found.") + + except Exception as e: + print(f"Error: Unable to load the pickle file. {e}") + + +def convert_to_cpu_float(dictionary): + """ + Convert PyTorch tensors in a dictionary from cuda:0 to floats on CPU. + + Parameters: + - dictionary: Dictionary with keys and PyTorch tensors/lists of tensors on cuda:0. + + Returns: + - Converted dictionary with tensors/lists as floats on CPU. + """ + converted_dict = {} + for key, value in dictionary.items(): + if isinstance(value, torch.Tensor): + converted_dict[key] = value.cpu().float() + elif isinstance(value, list): + converted_dict[key] = [item.cpu().numpy() for item in value] + else: + converted_dict[key] = value # Non-tensor values remain unchanged + + return converted_dict + + +def average_across_batch(arr, epochs): + arr_np = np.array(arr) + arr_avg = np.mean(np.array(np.split(arr_np, epochs)), axis=1) + + return np.reshape(arr_avg, (1, arr_avg.shape[0])) + + +def moving_average(a, n=20): + ret = np.cumsum(a, dtype=float) + ret[n:] = ret[n:] - ret[:-n] + return ret[n - 1:] / n + + +def plot_results(title, d, loss="Train Loss: ", lim_x=1000, lim_y=3): + plt.figure() + for k, val in d.items(): + + v = np.array([val]) + means = np.mean(v, axis=0) + # mins = np.amin(v, axis=0) + # maxes = np.amax(v, axis=0) + means = moving_average(means) + plt.plot(range(1, len(means)+1), means, linewidth=2, linestyle='solid', markersize=12, label=k) + + plt.title(title) + plt.yscale('log') + plt.xlim(1, lim_x) + plt.ylim(0.9, lim_y) + plt.ylabel(loss) + plt.xlabel('Step') + plt.legend(bbox_to_anchor=(0.65, 1.0), loc="upper left") + plt.grid() + plt.tight_layout() + plt.savefig(title + '.pdf') + + +def plot_results_time(title, d_y, d_x, loss="Train Loss: ", lim_x=1000, lim_y=3): + plt.figure() + for k, val in d_y.items(): + v = np.array([val]) + v_x = np.cumsum(np.array([d_x[k]]))*(1e-17) + + means = np.mean(v, axis=0) + # mins = np.amin(v, axis=0) + # maxes = np.amax(v, axis=0) + means = moving_average(means) + ll = len(means) + plt.plot(v_x[:ll], means, linewidth=2, linestyle='solid', markersize=12, label=k) + + plt.title(title) + plt.yscale('log') + plt.xscale('log') + plt.xlim(0, lim_x) + # plt.ylim(0.7, lim_y) + plt.ylabel(loss) + plt.xlabel('Time (s)') + plt.legend(bbox_to_anchor=(0.0, 1), loc="upper left") + plt.grid() + plt.tight_layout() + plt.savefig(title + '.pdf') + + +def plot_results_query(title, d_y, d_x, loss="Train Loss: ", lim_x=1000, lim_y=3): + plt.figure() + for k, val in d_y.items(): + v = np.array([val]) + v_x = np.cumsum(np.array([d_x[k]])) + + means = np.mean(v, axis=0) + # mins = np.amin(v, axis=0) + # maxes = np.amax(v, axis=0) + means = moving_average(means) + ll = len(means) + plt.plot(v_x[:ll], means, linewidth=2, linestyle='solid', markersize=12, label=k) + + plt.title(title) + plt.yscale('log') + plt.xscale('log') + plt.xlim(1e3, lim_x) + plt.ylim(0.7, lim_y) + plt.ylabel(loss) + plt.xlabel('Queries') + plt.legend(bbox_to_anchor=(0.0, 1), loc="upper left") + plt.grid() + plt.tight_layout() + plt.savefig(title + '.pdf') + + +def windowed_mean(arr, window_size): + arr = np.array(arr) + return np.mean(arr.reshape(-1, window_size), axis=1) + + +@contextlib.contextmanager +def temp_seed(seed): + state = np.random.get_state() + np.random.seed(seed) + try: + yield + finally: + np.random.set_state(state) diff --git a/baselines/loren/dataset/__init__.py b/baselines/loren/dataset/__init__.py new file mode 100644 index 0000000..f29768f --- /dev/null +++ b/baselines/loren/dataset/__init__.py @@ -0,0 +1,29 @@ +from .glue import GLUEDataModule, GLUE_TASKS +from .superglue import SuperGLUEDataModule, SUPERGLUE_TASKS + + +__all__ = ['GLUEDataModule', 'GLUE_TASKS', 'SuperGLUEDataModule', 'SUPERGLUE_TASKS'] + + +def get_data_module(args): + if args.task in GLUE_TASKS: + dm_class = GLUEDataModule + elif args.task in SUPERGLUE_TASKS: + dm_class = SuperGLUEDataModule + else: + raise ValueError(f"Task {args.task} is not supported") + + dm = dm_class( + model_name_or_path=args.model_name, + task_name=args.task, + max_seq_length=args.max_seq_length, + sample_size=args.samplesize, + train_batch_size=args.batchsize, + validation_sample_size=args.samplesize_validation, + eval_batch_size=args.batchsize, + soft_prompt=args.soft_prompt, + hf_token=args.hf_token + ) + dm.setup(stage='fit') + + return dm diff --git a/baselines/loren/dataset/glue.py b/baselines/loren/dataset/glue.py new file mode 100644 index 0000000..3af65a7 --- /dev/null +++ b/baselines/loren/dataset/glue.py @@ -0,0 +1,184 @@ +from typing import Optional + +import datasets +import lightning as L +from torch.utils.data import DataLoader, Subset +from transformers import AutoTokenizer + +from dataset.mezo_dataset import tokenize_multipart_input + + +GLUE_TASKS = ["cola", "sst2", "mnli", "qnli"] + + +class GLUEDataModule(L.LightningDataModule): + task_text_field_map = { + "cola": ["sentence"], + "sst2": ["sentence"], + "mnli": ["premise", "hypothesis"], + "qnli": ["question", "sentence"], + } + + glue_task_num_labels = { + "cola": 2, + "sst2": 2, + "mnli": 3, + "qnli": 2, + } + + loader_columns = [ + "datasets_idx", + "input_ids", + "token_type_ids", + "attention_mask", + "start_positions", + "end_positions", + "labels" + ] + + glue_task_label_mapping = { + 'sst2': { + 0: 'terrible', + 1: 'great' + } + } + + def __init__( + self, + model_name_or_path: str, + task_name: str = "mrpc", + max_seq_length: int = 512, + train_batch_size: int = 32, + eval_batch_size: int = 32, + sample_size: int = 128, + validation_sample_size: int = 128, + soft_prompt: bool = False, + hf_token: Optional[str] = None, + **kwargs, + ): + super().__init__() + self.model_name_or_path = model_name_or_path + self.task_name = task_name + self.max_seq_length = max_seq_length + self.train_batch_size = train_batch_size + self.eval_batch_size = eval_batch_size + self.sample_size = sample_size + self.validation_sample_size = validation_sample_size + + self.text_fields = self.task_text_field_map[task_name] + self.num_labels = self.glue_task_num_labels[task_name] + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name_or_path, use_fast=True, token=hf_token) + self.soft_prompt = soft_prompt + if soft_prompt is True: + self.loader_columns.append("mask_pos") + + def setup(self, stage: str = 'fit', randomize=False, seed=None): + self.dataset = datasets.load_dataset("glue", self.task_name) + + for split in self.dataset.keys(): + if split == "test": + continue + + if self.soft_prompt is True: + self.dataset[split] = self.dataset[split].map( + self.convert_to_features_soft_prompt, + batched=False, + remove_columns=["label"], + load_from_cache_file=True + ) + else: + self.dataset[split] = self.dataset[split].map( + self.convert_to_features, + batched=True, + remove_columns=["label"], + load_from_cache_file=True + ) + self.columns = [c for c in self.dataset[split].column_names if c in self.loader_columns] + self.dataset[split].set_format(type="torch", columns=self.columns) + + self.eval_splits = [x for x in self.dataset.keys() if "validation" in x] + + self.subset_indices = list(range(self.sample_size)) + self.subset_indices_val = list(range(self.validation_sample_size)) + + self.subset_train_dataset = Subset(self.dataset["train"], self.subset_indices) + if len(self.eval_splits) == 1: + self.subset_val_dataset = Subset(self.dataset["validation"], self.subset_indices_val) + else: + self.subset_val_dataset = Subset(self.dataset["validation_matched"], self.subset_indices_val) + + def prepare_data(self): + datasets.load_dataset("glue", self.task_name) + AutoTokenizer.from_pretrained(self.model_name_or_path, use_fast=True) + + def train_dataloader(self): + return DataLoader(self.subset_train_dataset, batch_size=self.train_batch_size, shuffle=True) + + def train_full_dataloader(self): + return DataLoader(self.subset_train_dataset, batch_size=self.sample_size, shuffle=True) + + def val_dataloader(self): + return DataLoader(self.subset_val_dataset, batch_size=self.eval_batch_size) + + def test_dataloader(self): + if len(self.eval_splits) == 1: + return DataLoader(self.dataset["test"], batch_size=self.eval_batch_size) + elif len(self.eval_splits) > 1: + return [DataLoader(self.dataset[x], batch_size=self.eval_batch_size) for x in self.eval_splits] + + def convert_to_features_soft_prompt(self, example_batch, indices=None): + if self.task_name == 'sst2': + inputs = tokenize_multipart_input( + input_text_list=[example_batch[self.text_fields[0]]], + max_length=self.max_seq_length, + tokenizer=self.tokenizer, + task_name=self.task_name, + prompt=True, + template='*cls**sent_0*_It_was*mask*.*sep+*', + label_word_list={0: ' terrible', 1: ' great'} + ) + inputs['labels'] = example_batch["label"] + return inputs + elif self.task_name == 'mnli': + inputs = tokenize_multipart_input( + input_text_list=[example_batch[self.text_fields[0]], example_batch[self.text_fields[1]]], + max_length=256, + tokenizer=self.tokenizer, + task_name=self.task_name, + prompt=True, + template='*cls**sent-_0*?*mask*,*+sentl_1**sep+*', + label_word_list={'contradiction': 'No', 'entailment': 'Yes', 'neutral': 'Maybe'}, + first_sent_limit=240 + ) + inputs['labels'] = example_batch["label"] + return inputs + + def convert_to_features(self, example_batch, indices=None): + + # Either encode single sentence or sentence pairs + if len(self.text_fields) > 1: + texts_or_text_pairs = list(zip(example_batch[self.text_fields[0]], + example_batch[self.text_fields[1]])) + else: + texts_or_text_pairs = example_batch[self.text_fields[0]] + + # Tokenize the text/text pairs + if (self.model_name_or_path == 'distilbert-base-cased' or + self.model_name_or_path == 'roberta-large'): + features = self.tokenizer.batch_encode_plus(texts_or_text_pairs, + max_length=self.max_seq_length, + pad_to_max_length=True, + truncation=True) + # Rename label to labels to make it easier to pass to model forward + features["labels"] = example_batch["label"] + elif 'gpt2' in self.model_name_or_path or 'opt' in self.model_name_or_path: + if self.tokenizer.pad_token_id is None: + self.tokenizer.pad_token_id = self.tokenizer.eos_token_id + + features = self.tokenizer.batch_encode_plus(texts_or_text_pairs, + max_length=self.max_seq_length, + pad_to_max_length=True, + truncation=True) + features["labels"] = example_batch["label"] + + return features diff --git a/baselines/loren/dataset/mezo_dataset.py b/baselines/loren/dataset/mezo_dataset.py new file mode 100644 index 0000000..2c62896 --- /dev/null +++ b/baselines/loren/dataset/mezo_dataset.py @@ -0,0 +1,696 @@ +"""Dataset utils for different data settings for GLUE.""" + +import os +import torch +import numpy as np +import time +from filelock import FileLock +import json +# from src.processors import processors_mapping, num_labels_mapping, output_modes_mapping, compute_metrics_mapping, median_mapping +from transformers.data.processors.utils import InputFeatures +import dataclasses +from dataclasses import dataclass +from typing import List, Optional, Union +import pandas as pd +from common.logging import logger + +# logger = logging.getLogger(__name__) +# logger.setLevel(logging.INFO) + + +@dataclass(frozen=True) +class OurInputFeatures(InputFeatures): + """ + Inherit from Transformers' InputFeatuers. + """ + + input_ids: List[int] + attention_mask: Optional[List[int]] = None + token_type_ids: Optional[List[int]] = None + label: Optional[Union[int, float]] = None + mask_pos: Optional[List[int]] = None # Position of the mask token + label_word_list: Optional[List[int]] = None # Label word mapping (dynamic) + + # For icl sfc + sfc_input_ids: List[int] = None + sfc_attention_mask: Optional[List[int]] = None + sfc_mask_pos: Optional[List[int]] = None + + def to_json_string(self): + """Serializes this instance to a JSON string.""" + return json.dumps(dataclasses.asdict(self)) + "\n" + + +def input_example_to_string(example, sep_token): + if example.text_b is None: + return example.text_a + else: + # Warning: very simple hack here + return example.text_a + ' ' + sep_token + ' ' + example.text_b + + +def input_example_to_tuple(example): + if example.text_b is None: + if pd.isna(example.text_a) or example.text_a is None: + return [''] + logger.warn("Empty input") + else: + return [example.text_a] + else: + return [example.text_a, example.text_b] + + +def tokenize_multipart_input( + input_text_list, + max_length, + tokenizer, + task_name=None, + prompt=False, + template=None, + label_word_list=None, + first_sent_limit=None, + other_sent_limit=None, + gpt3=False, + truncate_head=False, + support_labels=None, +): + def enc(text): + return tokenizer.encode(text, add_special_tokens=False) + + input_ids = [] + attention_mask = [] + token_type_ids = [] # Only for BERT + mask_pos = None # Position of the mask token + + if prompt: + """ + Concatenate all sentences and prompts based on the provided template. + Template example: '*cls*It was*mask*.*sent_0***label_0:*sent_1****label_1*:*sent_2***' + *xx* represent variables: + *cls*: cls_token + *mask*: mask_token + *sep*: sep_token + *sep+*: sep_token, also means +1 for segment id + *sent_i*: sentence i (input_text_list[i]) + *sent-_i*: same as above, but delete the last token + *sentl_i*: same as above, but use lower case for the first word + *sentl-_i*: same as above, but use lower case for the first word and delete the last token + *+sent_i*: same as above, but add a space before the sentence + *+sentl_i*: same as above, but add a space before the sentence and use lower case for the first word + *label_i*: label_word_list[i] + *label_x*: label depends on the example id (support_labels needed). this is only used in GPT-3's in-context learning + + Use "_" to replace space. + PAY ATTENTION TO SPACE!! DO NOT leave space before variables, for this will lead to extra space token. + """ + assert template is not None + + special_token_mapping = { + 'bos': tokenizer.bos_token_id, 'cls': tokenizer.cls_token_id, 'eos': tokenizer.eos_token_id, 'mask': tokenizer.mask_token_id, 'sep': tokenizer.sep_token_id, 'sep+': tokenizer.sep_token_id, + } + template_list = template.split('*') # Get variable list in the template + segment_id = 0 # Current segment id. Segment id +1 if encountering sep+. + + for part_id, part in enumerate(template_list): + new_tokens = [] + segment_plus_1_flag = False + if part in special_token_mapping: + if (part == 'cls' or part == 'bos'): # and ('T5' in type(tokenizer).__name__ or tokenizer.model_type == "gpt2"): + # T5 or GPT-2 do not have cls token + continue + new_tokens.append(special_token_mapping[part]) + if part == 'sep+': + segment_plus_1_flag = True + elif part[:6] == 'label_': + # Note that label_word_list already has extra space, so do not add more space ahead of it. + label_id = int(part.split('_')[1]) + label_word = label_word_list[label_id] + new_tokens.append(label_word) + elif part[:7] == 'labelx_': + instance_id = int(part.split('_')[1]) + label_id = support_labels[instance_id] + label_word = label_word_list[label_id] + new_tokens.append(label_word) + elif part[:5] == 'sent_': + sent_id = int(part.split('_')[1]) + new_tokens += enc(input_text_list[sent_id]) + elif part[:6] == '+sent_': + # Add space + sent_id = int(part.split('_')[1]) + new_tokens += enc(' ' + input_text_list[sent_id]) + elif part[:6] == 'sent-_': + # Delete the last token + sent_id = int(part.split('_')[1]) + new_tokens += enc(input_text_list[sent_id][:-1]) + elif part[:6] == 'sentl_': + # Lower case the first token + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].lower() + text[1:] + new_tokens += enc(text) + elif part[:7] == '+sentl_': + # Lower case the first token and add space + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].lower() + text[1:] + new_tokens += enc(' ' + text) + elif part[:7] == 'sentl-_': + # Lower case the first token and discard the last token + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].lower() + text[1:] + new_tokens += enc(text[:-1]) + elif part[:6] == 'sentu_': + # Upper case the first token + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].upper() + text[1:] + new_tokens += enc(text) + elif part[:7] == '+sentu_': + # Upper case the first token and add space + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].upper() + text[1:] + new_tokens += enc(' ' + text) + elif part[:8] == '+sentu-_': + # Upper case the first token and add space + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].upper() + text[1:] + new_tokens += enc(' ' + text[:-1]) + else: + # Just natural language prompt + part = part.replace('_', ' ') + # handle special case when T5 tokenizer might add an extra space + if len(part) == 1: + new_tokens.append(tokenizer.convert_tokens_to_ids(part)) + else: + new_tokens += enc(part) + + if part[:4] == 'sent' or part[1:5] == 'sent': + # If this part is the sentence, limit the sentence length + sent_id = int(part.split('_')[1]) + if sent_id == 0: + if first_sent_limit is not None: + new_tokens = new_tokens[:first_sent_limit] + else: + if other_sent_limit is not None: + new_tokens = new_tokens[:other_sent_limit] + + input_ids += new_tokens + attention_mask += [1 for i in range(len(new_tokens))] + token_type_ids += [segment_id for i in range(len(new_tokens))] + + if segment_plus_1_flag: + segment_id += 1 + else: + if tokenizer.cls_token_id is not None: + input_ids = [tokenizer.cls_token_id] + attention_mask = [1] + token_type_ids = [0] + else: + input_ids = [] + attention_mask = [] + token_type_ids = [] + + for sent_id, input_text in enumerate(input_text_list): + if input_text is None: + # Do not have text_b + continue + if pd.isna(input_text) or input_text is None: + # Empty input + input_text = '' + input_tokens = enc(input_text) + [tokenizer.sep_token_id] + input_ids += input_tokens + attention_mask += [1 for i in range(len(input_tokens))] + token_type_ids += [sent_id for i in range(len(input_tokens))] + + if 'T5' in type(tokenizer).__name__: # T5 does not have CLS token + input_ids = input_ids[1:] + attention_mask = attention_mask[1:] + token_type_ids = token_type_ids[1:] + + # Padding + if first_sent_limit is not None and len(input_ids) > max_length: + # If using sentence limit, the total length still exceeds the maximum limit, report a warning + logger.warn("Input exceeds max_length limit: {}".format(tokenizer.decode(input_ids))) + + # Code below is commented out, because we use dynamic padding rather than static padding to max_length + while len(input_ids) < max_length: + input_ids.append(tokenizer.pad_token_id) + attention_mask.append(0) + token_type_ids.append(0) + + # Truncate + if len(input_ids) > max_length: + if truncate_head: + input_ids = input_ids[-max_length:] + attention_mask = attention_mask[-max_length:] + token_type_ids = token_type_ids[-max_length:] + else: + # Default is to truncate the tail + input_ids = input_ids[:max_length] + attention_mask = attention_mask[:max_length] + token_type_ids = token_type_ids[:max_length] + + # Find mask token + if prompt and tokenizer.mask_token_id is not None: + # Make sure that the masked position is inside the max_length + assert tokenizer.mask_token_id in input_ids, \ + "Mask token not found for input: {} {}".format(input_text_list, input_ids) + mask_pos = [input_ids.index(tokenizer.mask_token_id)] + assert mask_pos[0] < max_length + elif prompt and tokenizer.mask_token_id is None: + # autoregressive model + mask_pos = [len(input_ids) - 1] + + result = {'input_ids': input_ids, 'attention_mask': attention_mask} + if 'BERT' in type(tokenizer).__name__: + # Only provide token type ids for BERT + result['token_type_ids'] = token_type_ids + + if prompt: + result['mask_pos'] = mask_pos + + return result + + +class FewShotDataset(torch.utils.data.Dataset): + """Few-shot dataset.""" + + def __init__(self, args, tokenizer, cache_dir=None, mode="train", use_demo=False): + self.args = args + self.task_name = args.task_name + self.processor = processors_mapping[args.task_name] + self.tokenizer = tokenizer + self.mode = mode + + # If not using demonstrations, use use_demo=True + self.use_demo = use_demo + if self.use_demo: + print("Use demonstrations") + assert mode in ["train", "dev", "test"] + + # Get label list and (for prompt) label word list + self.label_list = self.processor.get_labels() + self.num_labels = len(self.label_list) + if args.prompt and args.mapping is not None: + self.label_to_word = eval(args.mapping) + + for key in self.label_to_word: + # For RoBERTa/BART/T5, tokenization also considers space, so we use space+word as label words. + if self.label_to_word[key][0] not in ['<', '[', '.', ',']: + # Make sure space+word is in the vocabulary + assert len(tokenizer.tokenize(' ' + self.label_to_word[key])) == 1 + self.label_to_word[key] = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(' ' + self.label_to_word[key])[0]) + else: + self.label_to_word[key] = tokenizer.convert_tokens_to_ids(self.label_to_word[key]) + print("Label {} to word {} ({})".format(key, tokenizer.convert_ids_to_tokens(self.label_to_word[key]), self.label_to_word[key])) + + if len(self.label_list) > 1: + self.label_word_list = [self.label_to_word[label] for label in self.label_list] + else: + # Regression task + # '0' represents low polarity and '1' represents high polarity. + self.label_word_list = [self.label_to_word[label] for label in ['0', '1']] + else: + self.label_to_word = None + self.label_word_list = None + + # Multiple sampling: when using demonstrations, we sample different combinations of demonstrations during + # inference and aggregate the results by averaging the logits. The number of different samples is num_sample. + if (mode == "train") or not self.use_demo: + # We do not do multiple sampling when not using demonstrations or when it's the training mode + self.num_sample = 1 + else: + self.num_sample = args.num_sample + + # If we use multiple templates, we also need to do multiple sampling during inference. + if args.prompt and args.template_list is not None: + print("There are %d templates. Multiply num_sample by %d" % (len(args.template_list), len(args.template_list))) + self.num_sample *= len(args.template_list) + + print("Total num_sample for mode %s: %d" % (mode, self.num_sample)) + + # Load cache + # Cache name distinguishes mode, task name, tokenizer, and length. So if you change anything beyond these elements, make sure to clear your cache. + cached_features_file = os.path.join( + cache_dir if cache_dir is not None else args.data_dir, + "cached_{}_{}_{}_{}".format( + mode, + tokenizer.__class__.__name__ + "-" + tokenizer.model_type, + str(args.max_seq_length), + args.task_name, + ), + ) + + print(f"Creating/loading examples from dataset file at {args.data_dir}") + + lock_path = cached_features_file + ".lock" + with FileLock(lock_path): + + if os.path.exists(cached_features_file) and not args.overwrite_cache: + start = time.time() + self.support_examples, self.query_examples = torch.load(cached_features_file) + print( + f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start + ) + else: + print(f"Creating features from dataset file at {args.data_dir}") + + # The support examples are sourced from the training set. + self.support_examples = self.processor.get_train_examples(args.data_dir) + + if mode == "dev": + self.query_examples = self.processor.get_dev_examples(args.data_dir) + elif mode == "test": + self.query_examples = self.processor.get_test_examples(args.data_dir) + else: + self.query_examples = self.support_examples + + start = time.time() + torch.save([self.support_examples, self.query_examples], cached_features_file) + # ^ This seems to take a lot of time so I want to investigate why and how we can improve. + print( + "Saving features into cached file %s [took %.3f s]", cached_features_file, time.time() - start + ) + + # For filtering in using demonstrations, load pre-calculated embeddings + if self.use_demo and args.demo_filter: + split_name = '' + if mode == 'train': + split_name = 'train' + elif mode == 'dev': + if args.task_name == 'mnli': + split_name = 'dev_matched' + elif args.task_name == 'mnli-mm': + split_name = 'dev_mismatched' + else: + split_name = 'dev' + elif mode == 'test': + if args.task_name == 'mnli': + split_name = 'test_matched' + elif args.task_name == 'mnli-mm': + split_name = 'test_mismatched' + else: + split_name = 'test' + else: + raise NotImplementedError + + self.support_emb = np.load(os.path.join(args.data_dir, "train_{}.npy".format(args.demo_filter_model))) + self.query_emb = np.load(os.path.join(args.data_dir, "{}_{}.npy".format(split_name, args.demo_filter_model))) + print("Load embeddings (for demonstration filtering) from {}".format(os.path.join(args.data_dir, "{}_{}.npy".format(split_name, args.demo_filter_model)))) + + assert len(self.support_emb) == len(self.support_examples) + assert len(self.query_emb) == len(self.query_examples) + + # Size is expanded by num_sample + self.size = len(self.query_examples) * self.num_sample + + # Prepare examples (especially for using demonstrations) + support_indices = list(range(len(self.support_examples))) + self.example_idx = [] + for sample_idx in range(self.num_sample): + for query_idx in range(len(self.query_examples)): + # If training, exclude the current example. Else keep all. + if self.use_demo and args.demo_filter: + # Need sentence_transformers for demonstrations, + # which is not included in the requirements for us, but see original LM-BFF repo. + from sentence_transformers import SentenceTransformer, util + + # Demonstration filtering + candidate = [support_idx for support_idx in support_indices + if support_idx != query_idx or mode != "train"] + sim_score = [] + for support_idx in candidate: + sim_score.append((support_idx, util.pytorch_cos_sim(self.support_emb[support_idx], self.query_emb[query_idx]))) + sim_score.sort(key=lambda x: x[1], reverse=True) + if self.num_labels == 1: + # Regression task + limit_each_label = int(len(sim_score) // 2 * args.demo_filter_rate) + count_each_label = {'0': 0, '1': 0} + context_indices = [] + + if args.debug_mode: + print("Query %s: %s" % (self.query_examples[query_idx].label, self.query_examples[query_idx].text_a)) # debug + for support_idx, score in sim_score: + if count_each_label['0' if float(self.support_examples[support_idx].label) <= median_mapping[args.task_name] else '1'] < limit_each_label: + count_each_label['0' if float(self.support_examples[support_idx].label) <= median_mapping[args.task_name] else '1'] += 1 + context_indices.append(support_idx) + if args.debug_mode: + print(" %.4f %s | %s" % (score, self.support_examples[support_idx].label, self.support_examples[support_idx].text_a)) # debug + else: + limit_each_label = int(len(sim_score) // self.num_labels * args.demo_filter_rate) + count_each_label = {label: 0 for label in self.label_list} + context_indices = [] + + if args.debug_mode: + print("Query %s: %s" % (self.query_examples[query_idx].label, self.query_examples[query_idx].text_a)) # debug + for support_idx, score in sim_score: + if count_each_label[self.support_examples[support_idx].label] < limit_each_label: + count_each_label[self.support_examples[support_idx].label] += 1 + context_indices.append(support_idx) + if args.debug_mode: + print(" %.4f %s | %s" % (score, self.support_examples[support_idx].label, self.support_examples[support_idx].text_a)) # debug + else: + # Using demonstrations without filtering + context_indices = [support_idx for support_idx in support_indices + if support_idx != query_idx or mode != "train"] + + # We'll subsample context_indices further later. + self.example_idx.append((query_idx, context_indices, sample_idx)) + + # If it is not training, we pre-process the data; otherwise, we process the data online. + if mode != "train": + self.features = [] + _ = 0 + for query_idx, context_indices, bootstrap_idx in self.example_idx: + # The input (query) example + example = self.query_examples[query_idx] + # The demonstrations + supports = self.select_context([self.support_examples[i] for i in context_indices]) + + if args.template_list is not None: + template = args.template_list[sample_idx % len(args.template_list)] # Use template in order + else: + template = args.template + self.features.append(self.convert_fn( + example=example, + supports=supports, + use_demo=self.use_demo, + label_list=self.label_list, + prompt=args.prompt, + template=template, + sfc_template=getattr(args, "icl_sfc_prompt", None), + label_word_list=self.label_word_list, + verbose=True if _ == 0 else False, + )) + + _ += 1 + else: + self.features = None + + def select_context(self, context_examples): + """ + Select demonstrations from provided examples. + """ + max_demo_per_label = 1 + counts = {k: 0 for k in self.label_list} + if len(self.label_list) == 1: + # Regression + counts = {'0': 0, '1': 0} + selection = [] + + if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail: + # For GPT-3's in-context learning, we sample gpt3_in_context_num demonstrations randomly. + order = np.random.permutation(len(context_examples)) + for i in range(min(self.args.gpt3_in_context_num, len(order))): + selection.append(context_examples[order[i]]) + else: + # Our sampling strategy + order = np.random.permutation(len(context_examples)) + + for i in order: + label = context_examples[i].label + if len(self.label_list) == 1: + # Regression + label = '0' if float(label) <= median_mapping[self.args.task_name] else '1' + if counts[label] < max_demo_per_label: + selection.append(context_examples[i]) + counts[label] += 1 + if sum(counts.values()) == len(counts) * max_demo_per_label: + break + + assert len(selection) > 0 + + return selection + + def __len__(self): + return self.size + + def __getitem__(self, i): + if self.features is None: + query_idx, context_indices, bootstrap_idx = self.example_idx[i] + # The input (query) example + example = self.query_examples[query_idx] + # The demonstrations + supports = self.select_context([self.support_examples[i] for i in context_indices]) + + if self.args.template_list is not None: + template = self.args.template_list[sample_idx % len(self.args.template_list)] + else: + template = self.args.template + + features = self.convert_fn( + example=example, + supports=supports, + use_demo=self.use_demo, + label_list=self.label_list, + prompt=self.args.prompt, + template=template, + label_word_list=self.label_word_list, + verbose=False, + ) + + else: + features = self.features[i] + + return features + + def get_labels(self): + return self.label_list + + + def convert_fn( + self, + example, + supports, + use_demo=False, + label_list=None, + prompt=False, + template=None, + sfc_template=None, + label_word_list=None, + verbose=False + ): + """ + Returns a list of processed "InputFeatures". + """ + max_length = self.args.max_seq_length + + # Prepare labels + label_map = {label: i for i, label in enumerate(label_list)} # Mapping the label names to label ids + if len(label_list) == 1: + # Regression + label_map = {'0': 0, '1': 1} + + # Get example's label id (for training/inference) + if example.label is None: + example_label = None + elif len(label_list) == 1: + # Regerssion + example_label = float(example.label) + else: + example_label = label_map[example.label] + + # Prepare other features + if not use_demo: + # No using demonstrations + inputs = tokenize_multipart_input( + input_text_list=input_example_to_tuple(example), + max_length=max_length, + tokenizer=self.tokenizer, + task_name=self.args.task_name, + prompt=prompt, + template=template, + label_word_list=label_word_list, + first_sent_limit=self.args.first_sent_limit, + other_sent_limit=self.args.other_sent_limit, + ) + features = OurInputFeatures(**inputs, label=example_label) + + else: + # Using demonstrations + + # Max length + if self.args.double_demo: + # When using demonstrations, double the maximum length + # Note that in this case, args.max_seq_length is the maximum length for a single sentence + max_length = max_length * 2 + if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail: + # When using GPT-3's in-context learning, take the maximum tokenization length of the model (512) + if self.tokenizer.model_type == "gpt2": + max_length = 1024 + elif self.tokenizer.model_type == "opt": + max_length = 2048 + else: + max_length = 512 + + # All input sentences, including the query and the demonstrations, are put into augmented_examples, + # and are numbered based on the order (starting from 0). For single sentence tasks, the input (query) + # is the sentence 0; for sentence-pair tasks, the input (query) is the sentence 0 and 1. Note that for GPT-3's + # in-context learning, the input (query) might be at the end instead of the beginning (gpt3_in_context_head) + augmented_example = [] + query_text = input_example_to_tuple(example) # Input sentence list for query + support_by_label = [[] for i in range(len(label_map))] + + if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail: + support_labels = [] + augmented_example = query_text + for support_example in supports: + augmented_example += input_example_to_tuple(support_example) + current_label = support_example.label + if len(label_list) == 1: + current_label = '0' if float(current_label) <= median_mapping[self.args.task_name] else '1' # Regression + support_labels.append(label_map[current_label]) + else: + # Group support examples by label + for label_name, label_id in label_map.items(): + if len(label_list) == 1: + # Regression + for support_example in filter(lambda s: ('0' if float(s.label) <= median_mapping[self.args.task_name] else '1') == label_name, supports): + support_by_label[label_id] += input_example_to_tuple(support_example) + else: + for support_example in filter(lambda s: s.label == label_name, supports): + support_by_label[label_id] += input_example_to_tuple(support_example) + + augmented_example = query_text + for label_id in range(len(label_map)): + augmented_example += support_by_label[label_id] + + # Tokenization (based on the template) + inputs = tokenize_multipart_input( + input_text_list=augmented_example, + max_length=max_length, + tokenizer=self.tokenizer, + task_name=self.args.task_name, + prompt=prompt, + template=template, + label_word_list=label_word_list, + first_sent_limit=self.args.first_sent_limit, + other_sent_limit=self.args.other_sent_limit, + truncate_head=self.args.truncate_head, + gpt3=self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail, + support_labels=None if not (self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail) else support_labels + ) + if sfc_template is not None: + # Process sfc example + if verbose: + print("*** SFC Example ***") + sfc_feature = self.convert_fn( + example, supports, use_demo=use_demo, label_list=label_list, prompt=prompt, template=sfc_template, label_word_list=label_word_list, verbose=verbose + ) + features = OurInputFeatures(**inputs, label=example_label, sfc_input_ids=sfc_feature.input_ids, sfc_attention_mask=sfc_feature.attention_mask, sfc_mask_pos=sfc_feature.mask_pos) + else: + features = OurInputFeatures(**inputs, label=example_label) + + if verbose: + print("*** Example ***") + print("guid: %s" % (example.guid)) + print("features: %s" % features) + print("text: %s" % self.tokenizer.decode(features.input_ids)) + + return features + + + diff --git a/baselines/loren/dataset/superglue.py b/baselines/loren/dataset/superglue.py new file mode 100644 index 0000000..cbade57 --- /dev/null +++ b/baselines/loren/dataset/superglue.py @@ -0,0 +1,183 @@ +import datasets +import numpy as np +import pytorch_lightning as pl +from datasets import Dataset, DatasetDict +from torch.utils.data import DataLoader, Subset +from transformers import AutoTokenizer +from common.utils import temp_seed + + +SUPERGLUE_TASKS = ["rte", "wic", "copa", "boolq", "cb", "wsc"] + + +class SuperGLUEDataModule(pl.LightningDataModule): + task_num_labels = { + "rte": 2, + "wic": 2, + "copa": 2, + "boolq": 2, + "cb": 3, + "wsc": 2, + } + + loader_columns = [ + "datasets_idx", + "input_ids", + "token_type_ids", + "attention_mask", + "start_positions", + "end_positions", + "labels" + ] + + def __init__( + self, + model_name_or_path: str, + task_name: str = "rte", + max_seq_length: int = 512, + train_batch_size: int = 32, + eval_batch_size: int = 32, + sample_size: int = 128, + validation_sample_size: int = 128, + **kwargs, + ): + super().__init__() + self.model_name_or_path = model_name_or_path + self.task_name = task_name + self.max_seq_length = max_seq_length + self.train_batch_size = train_batch_size + self.eval_batch_size = eval_batch_size + self.sample_size = sample_size + self.validation_sample_size = validation_sample_size + + self.num_labels = self.task_num_labels[task_name] + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name_or_path, use_fast=True) + + def sample_subset(self, split="train", seed=0, num=100): + with temp_seed(seed): + lens = len(self.dataset[split]) + index = np.random.permutation(lens).tolist()[:num + 1] + index = index[:num] + return index + + def load_dataset(self, task_name): + hf_dataset = datasets.load_dataset("super_glue", task_name) + dataset = DatasetDict() + if task_name == "rte": + dataset = hf_dataset.map(lambda x: {"input": (x["premise"], x["hypothesis"])}) + elif task_name == "boolq": + dataset = hf_dataset.map(lambda x: {"input": (x["passage"], x["question"]+"?" if x["question"][-1] != "?" else x["question"])}) + elif task_name == "copa": + dataset = DatasetDict() + for split in hf_dataset.keys(): + examples = [] + for example in hf_dataset[split]: + premise = example["premise"] + choice1 = example["choice1"] + choice2 = example["choice2"] + question = example["question"] + + if question == "cause": + examples.append({ + "input": [choice1, premise], + "label": int(example["label"] == 0) if example["label"] is not None else None + }) + examples.append({ + "input": [choice2, premise], + "label": int(example["label"] == 1) if example["label"] is not None else None + }) + else: + examples.append({ + "input": [premise, choice1], + "label": int(example["label"] == 0) if example["label"] is not None else None + }) + examples.append({ + "input": [premise, choice2], + "label": int(example["label"] == 1) if example["label"] is not None else None + }) + dataset[split] = Dataset.from_list(examples) + + elif task_name == "cb": + dataset = hf_dataset.map(lambda x: {"input": (x["premise"], x["hypothesis"])}) + elif task_name == "wic": + dataset = hf_dataset.map(lambda x: {"input": (f"{x['word']} : {x['sentence1']}", x['sentence2'])}) + elif task_name == "wsc": + def wsc_formatter(example): + text = example['text'] + span1_index = example['span1_index'] + span2_index = example['span2_index'] + span1_text = example['span1_text'] + span2_text = example['span2_text'] + + words = text.split() + span1_word_len = len(span1_text.split()) + span2_word_len = len(span2_text.split()) + + words[span1_index:span1_index + span1_word_len] = [f"# {span1_text} #"] + + if span1_word_len > 1: + # If the span is more than one word, we need to adjust the index of the second span since the first more than one word has been replaced by a single word + span2_index -= span1_word_len - 1 + words[span2_index:span2_index + span2_word_len] = [f"* {span2_text} *"] + + return " ".join(words) + dataset = hf_dataset.map(lambda x: {"input": wsc_formatter(x)}) + + return dataset + + def setup(self, stage='fit', randomize=False, seed=None): + self.dataset = self.load_dataset(self.task_name) + + for split in self.dataset.keys(): + if split == "test": + continue + + self.dataset[split] = self.dataset[split].map( + self.convert_to_features, + batched=True, + remove_columns=["label"], + load_from_cache_file=True + ) + self.columns = [c for c in self.dataset[split].column_names if c in self.loader_columns] + self.dataset[split].set_format(type="torch", columns=self.columns) + + if len(self.dataset["train"]) < self.sample_size: + self.sample_size = len(self.dataset["train"]) + + self.eval_splits = ["validation"] + if len(self.dataset[self.eval_splits[0]]) < self.validation_sample_size: + self.validation_sample_size = len(self.dataset[self.eval_splits[0]]) + + self.subset_indices = list(range(self.sample_size)) + self.subset_indices_val = list(range(self.validation_sample_size)) + + self.subset_train_dataset = Subset(self.dataset["train"], self.subset_indices) + self.subset_val_dataset = Subset(self.dataset["validation"], self.subset_indices_val) + + def prepare_data(self): + datasets.load_dataset("super_glue", self.task_name) + AutoTokenizer.from_pretrained(self.model_name_or_path, use_fast=True) + + def train_dataloader(self): + return DataLoader(self.subset_train_dataset, batch_size=self.train_batch_size, shuffle=True) + + def train_full_dataloader(self): + return DataLoader(self.subset_train_dataset, batch_size=self.sample_size, shuffle=True) + + def val_dataloader(self): + return DataLoader(self.subset_val_dataset, batch_size=self.eval_batch_size) + + def test_dataloader(self): + return DataLoader(self.dataset["test"], batch_size=self.eval_batch_size) + + def convert_to_features(self, example_batch, indices=None): + if self.tokenizer.pad_token_id is None: + # GPT2 and OPT + self.tokenizer.pad_token_id = self.tokenizer.eos_token_id + + features = self.tokenizer.batch_encode_plus( + example_batch["input"], max_length=self.max_seq_length, pad_to_max_length=True, truncation=True + ) + features["labels"] = example_batch["label"] + + return features diff --git a/baselines/loren/figures/gpt_qnli_acc.png b/baselines/loren/figures/gpt_qnli_acc.png new file mode 100644 index 0000000..aeb1848 Binary files /dev/null and b/baselines/loren/figures/gpt_qnli_acc.png differ diff --git a/baselines/loren/figures/opt13_cb_acc.png b/baselines/loren/figures/opt13_cb_acc.png new file mode 100644 index 0000000..c809471 Binary files /dev/null and b/baselines/loren/figures/opt13_cb_acc.png differ diff --git a/baselines/loren/figures/opt13b_train_loss.png b/baselines/loren/figures/opt13b_train_loss.png new file mode 100644 index 0000000..e5b73ca Binary files /dev/null and b/baselines/loren/figures/opt13b_train_loss.png differ diff --git a/baselines/loren/main.py b/baselines/loren/main.py new file mode 100644 index 0000000..282c569 --- /dev/null +++ b/baselines/loren/main.py @@ -0,0 +1,157 @@ +import argparse +import logging +import math +import os +from datetime import datetime + +import torch +import transformers + +from common.logging import get_logger +from dataset import get_data_module +from model import get_model +from trainer import finetune_ZO, finetune_FO + + +def parse_arguments(): + parser = argparse.ArgumentParser(description='Argument Parser for Model Fine-tuning') + + # common + parser.add_argument('--model_name', type=str, default='distilbert-base-cased', + help='Name of the pre-trained model') + parser.add_argument('--task', type=str, default='mnli', help='Task for model training') + parser.add_argument('--algorithm', type=str, default='ZO', help='Algorithm to use', + choices=["FOSGD", "FOAdam", "ZO", "ZOAdam", "ZOSVRG", "LOZO", "HiZOO", "LOREN"]) + parser.add_argument('--device', type=int, default=0, help='GPU Number') + parser.add_argument('--results', type=str, default='results_demo', + help='Name of folder to store results') + # training + parser.add_argument('--epochs', type=int, default=1, help='Number of training epochs') + parser.add_argument('--batchsize', type=int, default=64, help='Batch size for training') + parser.add_argument('--batchsize_limit', type=int, default=64, + help='Max batch size to be used to avoid memory error') + parser.add_argument('--full_parameter', action='store_true', + help='True for full parameter fine-tuning') + # dataset + parser.add_argument('--samplesize', type=int, default=512, help='Training data sample size') + parser.add_argument('--samplesize_validation', type=int, default=256, + help='Validation data sample size') + parser.add_argument('--max_seq_length', type=int, default=256, + help='Max sequence length for inputs') + # optimization + parser.add_argument('--lr', type=float, default=2e-3, help='Learning rate') + parser.add_argument('--weight_decay', type=float, default=0.01, help='weight_decay') + parser.add_argument('--perturbation_scale', type=float, default=1e-3, + help='Perturbation scale for SPSA estimators') + parser.add_argument('--early_stopping', action='store_true', help='Enable early stopping') + parser.add_argument('--patience', type=int, default=10, help='Early stopping patience; ' + 'if the validation accuracy does not improve for this number of evaluations, ' + 'stop training') + parser.add_argument('--num_queries', type=int, default=10, + help='Number of queries to evaluate in large batch update') + # experiment + parser.add_argument('--soft_prompt', action='store_true', help='True for using soft prompt') + parser.add_argument('--save_ckpt', action='store_true', help='Save checkpoint') + parser.add_argument('--save_every', type=int, default=10, help='Save checkpoint every n epochs') + parser.add_argument('--eval_every', type=int, default=1, + help='Evaluate on validation set every n epochs') + parser.add_argument('--fp16', action='store_true', help='Use FP16 precision') + parser.add_argument('--bf16', action='store_true', help='Use BF16 precision') + parser.add_argument('--logging', type=str, default="csv", choices=['tensorboard', 'csv'], + help="Choose logging method; either wandb or tensorboard or none") + parser.add_argument('--trial', type=int, default=0, help='Trial number') + parser.add_argument('--init_seed', type=int, default=None, help='Random seed for model initialization') + parser.add_argument('--clipping', action='store_true', help='set to True to apply gradient clipping') + # SVRG + parser.add_argument('--q', type=int, default=2, help='q parameter used only for ZO-SVRG') + parser.add_argument('--lr_mezosvrg_mb', type=float, default=1e-6, + help='Mini-batch learning rate for MeZO-SVRG') + parser.add_argument('--anneal', type=float, default=1.5, help='Annealing parameter') + # Adam + parser.add_argument('--eps', type=float, default=1e-8, help='the level of adaptivity (eps for adam)') + parser.add_argument('--low_bit_adam', type=int, default=0, + help='Use Adam with quantized states; options: 4 or 8') + # LOZO + parser.add_argument('--rank', type=int, default=2, help='rank of U and V') + parser.add_argument('--step_interval', type=int, default=50, help='frequency of updating matrix V') + # HiZOO + parser.add_argument('--hessian_smooth_type', type=str, default="constant1e-8", + help="hessian smooth type") + # LOREN + parser.add_argument('--damping', type=float, default=1.0, help='damping') + parser.add_argument('--lr_cov', type=float, default=1e-3, help='Learning rate for covariance') + + args = parser.parse_args() + return args + + +def setup_logger(): + timestamp = datetime.now().strftime("%Y%m%d%H%M%S") + logfile = os.path.join(args.output_dir, f'log_{timestamp}.txt') + logger = get_logger(logfile, level="DEBUG") + get_logger(level='INFO') + + """ + The default of training_args.log_level is passive, so we set log level at info here + to have that default. + """ + transformers.utils.logging.set_verbosity_info() + transformers.utils.logging.set_verbosity(logging.INFO) + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + + return logger + + +if __name__ == "__main__": + os.environ["TOKENIZERS_PARALLELISM"] = "true" + args = parse_arguments() + args.hf_token = os.getenv('HF_TOKEN') + + trimmed_model_name = args.model_name.split('/')[-1] + num_steps = math.ceil(args.samplesize / args.batchsize) * args.epochs + args.run_name = f'{args.algorithm}_lr{args.lr:.0e}_nq-{args.num_queries}' + + if args.algorithm == 'ZOSVRG': + args.run_name += f'_lr_mb_{args.lr_mezosvrg_mb:.0e}_q_{args.q:.0e}_anneal_{args.anneal:.0e}' + elif args.algorithm == 'ZOAdam': + args.run_name += f'_eps_{args.eps:.0e}' + if args.low_bit_adam == 4 or args.low_bit_adam == 8: + args.run_name += f'_{args.low_bit_adam}bit' + elif args.algorithm == 'LOZO': + args.run_name += f'_rank_{args.rank}_step-interval_{args.step_interval}' + elif args.algorithm == 'HiZOO': + args.run_name += f'_hessian_smooth-{args.hessian_smooth_type}' + elif args.algorithm == 'LOREN': + args.run_name += f'_damp-{args.damping:.0e}_covlr{args.lr_cov:.0e}' + + args.run_name += f'_bsz{args.batchsize}_steps{num_steps}' + args.output_dir = os.path.join(args.results, trimmed_model_name, args.task, args.run_name) + + if args.logging == "tensorboard": + from lightning.pytorch.loggers import TensorBoardLogger + + writer = TensorBoardLogger(args.output_dir) + elif args.logging == 'csv': + from lightning.pytorch.loggers import CSVLogger + + writer = CSVLogger(args.output_dir, + flush_logs_every_n_steps=10) + os.makedirs(args.output_dir, exist_ok=True) + + # logging setup + logger = setup_logger() + logger.debug(f"Training Arguments {args}") + + if torch.cuda.is_available(): + device = torch.device("cuda:" + str(args.device)) + else: + device = torch.device("cpu") + + dm = get_data_module(args) + transformer = get_model(args, dm) + + if 'FO' in args.algorithm: + finetune_FO(args, device, dm, transformer, writer) + else: + finetune_ZO(args, device, dm, transformer, writer) diff --git a/baselines/loren/model/__init__.py b/baselines/loren/model/__init__.py new file mode 100644 index 0000000..5d3b50f --- /dev/null +++ b/baselines/loren/model/__init__.py @@ -0,0 +1,65 @@ +from .glue_transformer import GLUETransformer +from .glue_transformer_fo import GLUETransformerFO +from .glue_transformer_mezo import GLUETransformerMeZo +from .glue_transformer_svrg import GLUETransformerMeZoSVRG +from .glue_transformer_adam import GLUETransformerMeZoAdam +from .glue_transformer_lozo import GLUETransformerLoZo +from .glue_transformer_hizoo import GLUETransformerHiZOO +from .glue_transformer_loren import GLUETransformerLOREN +from .opt import OPTDecoder, OPTForCausalLM, OPTModel +from .roberta import RobertaConfig, RobertaLMHead, RobertaModel, RobertaPreTrainedModel +from .prompt_finetune import (RobertaModelForPromptFinetuning, OPTModelForPromptFinetuning, + LlamaModelForPromptFinetuning) + + +__all__ = ['GLUETransformer', 'GLUETransformerMeZo', + 'GLUETransformerMeZoSVRG', 'GLUETransformerMeZoAdam', + 'GLUETransformerHiZOO', 'GLUETransformerLOREN', + 'RobertaPreTrainedModel', 'RobertaModel', 'RobertaLMHead', + 'RobertaModelForPromptFinetuning', 'RobertaConfig', 'OPTModelForPromptFinetuning', + 'OPTModel', 'OPTForCausalLM', 'OPTDecoder', 'LlamaModelForPromptFinetuning'] + + +model_class = { + 'FOSGD': GLUETransformerFO, + 'FOAdam': GLUETransformerFO, + 'ZO': GLUETransformerMeZo, + 'ZOSVRG': GLUETransformerMeZoSVRG, + 'ZOAdam': GLUETransformerMeZoAdam, + 'LOZO': GLUETransformerLoZo, + 'HiZOO': GLUETransformerHiZOO, + 'LOREN': GLUETransformerLOREN, +} + + +def get_model(args, dm): + glue_transformer = model_class[args.algorithm] + transformer = glue_transformer( + model_name_or_path=args.model_name, + num_labels=dm.num_labels, + eval_splits=dm.eval_splits, + task_name=dm.task_name, + learning_rate=args.lr_mezosvrg_mb if 'SVRG' in args.algorithm else args.lr, + learning_rate_aux=args.lr if 'SVRG' in args.algorithm else None, + lr_anneal=args.anneal, + full_parameter=args.full_parameter, + batchsize_limit=args.batchsize_limit, + zero_order_eps=args.perturbation_scale, + soft_prompt=args.soft_prompt, + use_SGD=True if 'SGD' in args.algorithm else False, + logger_type=args.logging, + hf_token=args.hf_token, + model_init_seed=args.init_seed, + q=args.q, + step_interval=args.step_interval, + rank=args.rank, + weight_decay=args.weight_decay, + eps=args.eps, + damping=args.damping, + lr_cov=args.lr_cov, + num_queries=args.num_queries, + clipping=args.clipping, + hessian_smooth_type=args.hessian_smooth_type, + num_epochs=args.epochs, + ) + return transformer diff --git a/baselines/loren/model/glue_transformer.py b/baselines/loren/model/glue_transformer.py new file mode 100644 index 0000000..0c23a50 --- /dev/null +++ b/baselines/loren/model/glue_transformer.py @@ -0,0 +1,421 @@ +import math +import os +import pickle +from typing import Optional + +import lightning as L +import numpy as np +import torch +from common.logging import logger as logging +from transformers import (AutoConfig, AutoModelForSequenceClassification, + OPTForSequenceClassification, LlamaForSequenceClassification) + +from .prompt_finetune import RobertaModelForPromptFinetuning +from .roberta import RobertaConfig + +MODEL_NAME = "model.pt" +OPTIMIZER_NAME = "optimizer.pt" +DATA_MODULE_NAME = "data_module.pkl" +TRAIN_STATE_NAME = "train_state.pkl" +WANDB_INFO_NAME = "wandb_info.pkl" +STEP_INFO_NAME = "step_info.pkl" + + +class TrainState: + def __init__(self): + self.validation_step_outputs = [] + self.tr_loss = [] + self.tr_loss_minibatch = [] + self.time = [] + self.query = [] + self.grad_norm = [] + self.proj_val = [] + self.z_grad = [] + self.val_loss_ls = [] + self.val_acc = [] + self.lr_list = [] + self.memory_usage = [] + self.global_training_steps = 0 + self.learning_rate = 0 + self.learning_rate_aux = 0 + self.full_grad = None + + +class GLUETransformer(L.LightningModule): + def __init__( + self, + model_name_or_path: str, + num_labels: int, + zero_order_eps: float = 1e-3, + learning_rate_aux: float = 1e-3, + minibatch: int = 64, + max_norm: float = 18000.0, + z_std: float = 1.0, + lr_anneal: float = 1.0, + full_parameter: bool = True, + batchsize_limit: int = 16, + eval_splits: Optional[list] = None, + soft_prompt: bool = False, + use_SGD: bool = True, + logger_type: str = 'wandb', + hf_token: Optional[str] = None, + lora: bool = False, + model_init_seed: Optional[int] = None, + num_queries: int = 2, + **kwargs, + ): + super().__init__() + + self.save_hyperparameters() + + self.model_name = model_name_or_path + self.config = AutoConfig.from_pretrained(model_name_or_path, num_labels=num_labels) + self.soft_prompt = soft_prompt + self.lora = lora + + if model_init_seed is not None: + original_seed = torch.initial_seed() + torch.manual_seed(model_init_seed) + + if model_name_or_path == 'distilbert-base-cased' or model_name_or_path == 'roberta-large': + if self.soft_prompt is True and model_name_or_path == 'roberta-large': + config = RobertaConfig.from_pretrained( + 'roberta-large', + num_labels=num_labels, + finetuning_task=self.hparams.task_name) + self.model = RobertaModelForPromptFinetuning.from_pretrained( + "roberta-large", + config=config + ) + else: + self.model = AutoModelForSequenceClassification.from_pretrained(model_name_or_path, config=self.config) + elif 'gpt2' in model_name_or_path: + self.model = AutoModelForSequenceClassification.from_pretrained(model_name_or_path, config=self.config) + self.model.config.pad_token_id = self.model.config.eos_token_id + elif 'opt' in model_name_or_path: + self.model = OPTForSequenceClassification.from_pretrained(model_name_or_path, num_labels=num_labels) + elif 'llama' in model_name_or_path or self.config.model_type == 'llama': + self.model = LlamaForSequenceClassification.from_pretrained(model_name_or_path, config = self.config, + use_auth_token=True) + self.model.config.pad_token_id = self.model.config.eos_token_id + else: + raise NotImplementedError(f"Model {model_name_or_path} not supported yet.") + + if model_init_seed is not None: + torch.manual_seed(original_seed) + + logging.debug(self.model) + + self.use_SGD = use_SGD + self.zero_order_eps = zero_order_eps + self.minibatch = minibatch + self.max_norm = max_norm + self.z_std = z_std + self.lr_anneal = lr_anneal + self.full_parameter = full_parameter + self.batchsize_limit = batchsize_limit + self.logger_type = logger_type + self.num_queries = num_queries + + # train state + self.state = TrainState() + self.state.validation_step_outputs = [] + self.state.tr_loss = [] + self.state.tr_loss_minibatch = [] + self.state.time = [] + self.state.query = [] + self.state.grad_norm = [] + self.state.proj_val = [] + self.state.z_grad = [] + self.state.val_loss_ls = [] + self.state.val_acc = [] + self.state.lr_list = [] + self.state.memory_usage = [] + + self.state.global_training_steps = 0 + self.state.learning_rate = self.hparams.learning_rate + self.state.learning_rate_aux = learning_rate_aux + + def forward(self, **inputs): + return self.model(**inputs) + + def forward_ZO_val(self, inputs): + model = self.model + model.eval() + batch_size = inputs['input_ids'].shape[0] + iterations = math.ceil(batch_size/self.batchsize_limit) + + loss_sum = 0 + correct_sum = 0 + total_samples = 0 + + for i in range(iterations): + input_batch = {} + for k, v in inputs.items(): + input_batch[k] = v[i*self.batchsize_limit:min((i+1)*self.batchsize_limit, batch_size)] + + with torch.no_grad(): + outputs = model(**input_batch) + + logits = outputs[1] + if self.hparams.num_labels > 1: + preds = torch.argmax(logits, axis=1) + elif self.hparams.num_labels == 1: + preds = logits.squeeze() + + labels = input_batch["labels"] + correct_sum += (preds == labels).sum().item() + total_samples += len(labels) + + loss_sum += outputs[0].float() * len(labels) # loss is averaged over samples + + torch.cuda.empty_cache() + + # freeing up memory + del input_batch, outputs, logits, preds + return loss_sum, correct_sum, total_samples + + def configure_params(self): + model = self.model + if self.full_parameter: + self.params = [(n, p) for n, p in model.named_parameters()] + else: + raise NotImplementedError("partial optimization not supported yet.") + + def configure_optimizers(self): + """Prepare optimizer""" + model = self.model + + if self.full_parameter: + self.params_to_opt = model.parameters() + else: + raise NotImplementedError("partial optimization not supported yet.") + + if self.use_SGD: + optimizer = torch.optim.SGD(self.params_to_opt, lr=self.hparams.learning_rate) + else: + optimizer = torch.optim.Adam(self.params_to_opt, lr=self.hparams.learning_rate) + return optimizer + + def training_step(self, batch, batch_idx): + outputs = self(**batch) + loss = outputs[0] + + return {'loss': loss} + + def on_train_batch_end(self, outputs, batch, batch_idx): + loss = outputs['loss'] + self.state.tr_loss.append(loss.detach().cpu().float().numpy()) + logging.info(f'train_loss : {loss.item():.4f}') + self.log('train_loss', loss.item()) + self.measure_memory_usage() + + def validation_step(self, batch, batch_idx, dataloader_idx=0): + outputs = self(**batch) + val_loss, logits = outputs[:2] + self.state.val_loss_ls.append(val_loss.detach().cpu().float().numpy()) + + if self.hparams.num_labels > 1: + preds = torch.argmax(logits, axis=1) + elif self.hparams.num_labels == 1: + preds = logits.squeeze() + + labels = batch["labels"] + + # Compute Validation Accuracy + correct_predictions = (preds == labels).sum().item() + total_samples = len(labels) + accuracy = correct_predictions / total_samples + self.state.val_acc.append(accuracy) + + val_info = {"loss": val_loss, "preds": preds, "labels": labels} + self.state.validation_step_outputs.append(val_info) + + return val_info + + def on_validation_epoch_end(self): + if len(self.state.validation_step_outputs) == 0: + return + + loss_sum = torch.stack( + [x['loss'] * len(x['labels']) for x in self.state.validation_step_outputs] + ).sum() + val_preds = torch.cat([x['preds'] for x in self.state.validation_step_outputs]) + val_labels = torch.cat([x['labels'] for x in self.state.validation_step_outputs]) + + avg_loss = loss_sum.item() / len(val_labels) + val_acc = (val_preds == val_labels).sum().item() / len(val_labels) + logging.info(f'val_loss: {avg_loss:.4f}, val_acc: {val_acc:.3f}') + + self.log('val_loss', avg_loss) + self.log('val_acc', val_acc) + + self.state.validation_step_outputs.clear() + return {"val_loss": avg_loss, "val_acc": val_acc} + + @torch.no_grad() + def zo_forward_memory_eff(self, model, inputs): + model.eval() + batch_size = inputs['input_ids'].shape[0] + iterations = math.ceil(batch_size/self.batchsize_limit) + loss = 0.0 + + for i in range(iterations): + input_batch = {} + for k, v in inputs.items(): + input_batch[k] = v[i*self.batchsize_limit:min((i+1)*self.batchsize_limit, batch_size)] + + with torch.inference_mode(): + outputs = model(**input_batch) + + loss += outputs[0].float() + return loss / iterations + + def zo_forward(self, model, inputs): + model.eval() + with torch.no_grad(): + outputs = model(**inputs) + loss = outputs[0] + return loss.detach() + + def efficient_perturb_parameters(self, + parameters, + random_seed: int, + uniform: bool = False, + use_beta: bool = False, + scaling_factor=1): + torch.manual_seed(random_seed) + e = self.beta if use_beta else self.zero_order_eps + for _, param in parameters: + if uniform: + # uniform distribution over unit sphere + z = torch.randn(size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + z = z / torch.linalg.norm(z) + else: + z = torch.normal(mean=0, std=self.z_std, size=param.data.size(), + device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * e + return + + def efficient_perturb_parameters_layerwise(self, + parameters, + seed_list: list, + uniform: bool = False, + use_beta: bool = False, + scaling_factor=1): + # assert the same size of seed list and trainable parameters + assert len(seed_list) == len(parameters) + e = self.beta if use_beta else self.zero_order_eps + for (_, param), seed in zip(parameters, seed_list): + torch.manual_seed(seed) + if uniform: + # uniform distribution over unit sphere + z = torch.randn(size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + z = z / torch.linalg.norm(z) + else: + z = torch.normal(mean=0, std=self.z_std, size=param.data.size(), + device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * e + return + + def log_training_loss(self, model, batch, fullbatch=False, tb_writer=None): + with torch.no_grad(): + # loss computation + loss = self.zo_forward_memory_eff(model, batch) + if fullbatch: + logging.info(f"Fullbatch Train Loss : {loss:.3f}") + self.state.tr_loss.append(loss.detach().cpu().float().numpy()) + if tb_writer is not None: + tb_writer.add_scalar("fb_train_loss", loss.item(), self.state.global_training_steps) + else: + logging.info(f"Minibatch Train Loss : {loss:.3f}") + self.state.tr_loss_minibatch.append(loss.detach().cpu().float().numpy()) + if tb_writer is not None: + tb_writer.add_scalar("mb_train_loss", loss.item(), self.state.global_training_steps) + + def forward_difference_grad_est(self, model, parameters, batch, uniform=False): + random_seed = np.random.randint(1000000000, size=1) + with torch.no_grad(): + # first function evaluation + self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform) + loss1 = self.zo_forward_memory_eff(model, batch) + # second function evaluation + self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform, scaling_factor=-1) + loss2 = self.zo_forward_memory_eff(model, batch) + proj_grad = (loss1 - loss2)/self.zero_order_eps + self.state.proj_val.append(torch.abs(proj_grad).detach().cpu().float().numpy()) + + estimator = {} + torch.manual_seed(random_seed) + for name, param in parameters: + if uniform: + # uniform distribution over unit sphere + z = torch.randn(size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + z = z / torch.linalg.norm(z) + else: + z = torch.normal(mean=0, std=self.z_std, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + estimator[name] = proj_grad*z + return estimator + + def clip_gradients_dict(self, grad_dict): + """Clip the gradients in a dictionary to a maximum norm.""" + total_norm = 0 + for param_name, grad in grad_dict.items(): + total_norm += grad.norm(2) ** 2 + total_norm = total_norm ** 0.5 + logging.debug(f'Norm: {total_norm}') + self.state.grad_norm.append(total_norm) + clip_coef = self.state.max_norm / (total_norm + 1e-6) + + if clip_coef < 1: + for param_name, grad in grad_dict.items(): + grad_dict[param_name].mul_(clip_coef) + + return grad_dict + + def compute_grad_norm_zo(self, grad_dict): + """Compute gradient norm.""" + total_norm = 0 + for param_name, grad in grad_dict.items(): + total_norm += grad.norm(2) ** 2 + total_norm = total_norm ** 0.5 + logging.debug(f'Gradient Norm: {total_norm}') + self.state.grad_norm.append(total_norm) + + def compute_grad_norm_fo(self, param): + total_norm = 0 + for p in param: + if not p.detach().grad is None: + param_norm = p.detach().grad.data.norm(2) + total_norm += param_norm.item() ** 2 + total_norm = total_norm ** (1. / 2) + logging.debug(f'Grad Norm: {total_norm}') + self.state.grad_norm.append(total_norm) + + def get_average_tensors(self, tensor_list, n=50): + v1 = torch.stack(tensor_list[-n:]).mean(dim=0) + v2 = torch.stack(tensor_list[-2*n:-n]).mean(dim=0) + return v1, v2 + + def get_average_np(self, np_list, n=50): + ll = np.array(np_list) + v1 = np.mean(ll[-n:]) + v2 = np.mean(ll[-3*n:-2*n]) + return v1, v2 + + def measure_memory_usage(self): + device = next(self.model.parameters()).device + allocated_memory_bytes = torch.cuda.memory_reserved(device) + allocated_memory_gb = allocated_memory_bytes / (1024 ** 3) + self.state.memory_usage.append(allocated_memory_gb) + # logging.info(f'Memory usage (GB): {allocated_memory_gb:.2f}') + return allocated_memory_gb + + def load_from_checkpoint(self, checkpoint_path: str): + self.model.load_state_dict(torch.load(os.path.join(checkpoint_path, MODEL_NAME))) + self.state = pickle.load(open(os.path.join(checkpoint_path, TRAIN_STATE_NAME), 'rb')) + + def save_checkpoint(self, checkpoint_path: str): + os.makedirs(checkpoint_path, exist_ok=True) + torch.save(self.model.state_dict(), os.path.join(checkpoint_path, MODEL_NAME)) + pickle.dump(self.state, open(os.path.join(checkpoint_path, TRAIN_STATE_NAME), 'wb')) diff --git a/baselines/loren/model/glue_transformer_adam.py b/baselines/loren/model/glue_transformer_adam.py new file mode 100644 index 0000000..8515773 --- /dev/null +++ b/baselines/loren/model/glue_transformer_adam.py @@ -0,0 +1,64 @@ +import time +import numpy as np +import torch +from .glue_transformer_mezo import GLUETransformerMeZo + + +class GLUETransformerMeZoAdam(GLUETransformerMeZo): + def zo_step(self, model, batch, random_seed): + """ + Zeroth-order gradient estimation + """ + # first function evaluation + self.perturb_parameters(random_seed, scaling_factor=1) + loss1 = self.zo_forward_memory_eff(model, batch) + + # second function evaluation + self.perturb_parameters(random_seed, scaling_factor=-2) + loss2 = self.zo_forward_memory_eff(model, batch) + + projected_grad = ((loss1 - loss2) / (2 * self.zero_order_eps)).item() + + # model_dtype = next(self.model.parameters()).dtype + # projected_grad = projected_grad.to(model_dtype) + + # reset model back to its parameters at start of step + self.perturb_parameters(random_seed, scaling_factor=1) + + return loss1, projected_grad + + def training_step(self, model, batch, tb_writer=None, **kwargs): + # run ZO update + num_grad_est = self.num_queries // 2 + n = batch['input_ids'].size(0) + start_time = time.perf_counter() + random_seeds = [np.random.randint(1000000000) for _ in range(num_grad_est)] + optimizer = kwargs['optimizer'] + log_dict = kwargs['log'] + + + losses = [] + for k in range(num_grad_est): + loss, projected_grad = self.zo_step(model, batch, random_seeds[k]) + losses.append(loss.item()) + mean_proj_grad = projected_grad / num_grad_est + + # compute SPSA gradient estimator + torch.manual_seed(random_seeds[k]) + for _, param in self.params: + param.grad = mean_proj_grad * torch.normal(mean=0, std=1, size=param.data.size(), + device=param.data.device, + dtype=param.data.dtype) + optimizer.step() + param.grad = None + + lmean = np.mean(losses) + self.state.global_training_steps += 1 + + # logging + total_time = time.perf_counter() - start_time + self.state.time.append(total_time) + self.state.query.append(2*n*num_grad_est) + + log_dict['train_loss'] = lmean.item() + log_dict['time'] = total_time diff --git a/baselines/loren/model/glue_transformer_fo.py b/baselines/loren/model/glue_transformer_fo.py new file mode 100644 index 0000000..d2c28a5 --- /dev/null +++ b/baselines/loren/model/glue_transformer_fo.py @@ -0,0 +1,32 @@ +import time +import torch +from .glue_transformer import GLUETransformer + + +class GLUETransformerFO(GLUETransformer): + def __init__(self, *args, use_sgd=False, **kwargs): + super().__init__(*args, **kwargs) + self.use_sgd = use_sgd + + def training_step(self, model, batch, tb_writer=None, **kwargs): + start_time = time.perf_counter() + optimizer = kwargs['optimizer'] + log_dict = kwargs['log'] + + outputs = model(**batch) + loss = outputs[0] + + optimizer.zero_grad() + loss.backward() + optimizer.step() + + self.state.global_training_steps += 1 + + # Logging + total_time = time.perf_counter() - start_time + n = batch['input_ids'].size(0) + self.state.time.append(total_time) + self.state.query.append(n) + + log_dict['train_loss'] = loss.item() + log_dict['time'] = total_time \ No newline at end of file diff --git a/baselines/loren/model/glue_transformer_hizoo.py b/baselines/loren/model/glue_transformer_hizoo.py new file mode 100644 index 0000000..52adc3c --- /dev/null +++ b/baselines/loren/model/glue_transformer_hizoo.py @@ -0,0 +1,127 @@ +import time +from typing import Optional + +import numpy as np +import torch + +from .glue_transformer_mezo import GLUETransformerMeZo +from common.hessian_smooth_scheduler import Hessian_smooth_scheduler + +class GLUETransformerHiZOO(GLUETransformerMeZo): + def __init__( + self, + model_name_or_path: str, + num_labels: int, + zero_order_eps: float = 1e-3, + learning_rate_aux: float = 1e-3, + minibatch: int = 64, + max_norm: float = 18000.0, + z_std: float = 1.0, + lr_anneal: float = 1.0, + full_parameter: bool = True, + batchsize_limit: int = 16, + eval_splits: Optional[list] = None, + soft_prompt: bool = False, + use_SGD: bool = True, + logger_type: str = 'wandb', + hf_token: Optional[str] = None, + lora: bool = False, + model_init_seed: Optional[int] = None, + num_queries: int = 10, + weight_decay: float = 0.01, + hessian_smooth_type: str = "constant1e-8", + num_epochs: int = 3000, + **kwargs, + ): + super().__init__(model_name_or_path, + num_labels, + zero_order_eps, + learning_rate_aux, + minibatch, + max_norm, + z_std, + lr_anneal, + full_parameter, + batchsize_limit, + eval_splits, + soft_prompt, + use_SGD, + logger_type, + hf_token, + lora, + model_init_seed) + self.Hessian_matrix = {} + self.hessian_smooth_type = hessian_smooth_type + self.num_epochs = num_epochs + self.num_queries = num_queries + self.weight_decay = weight_decay + + def configure_params(self): + super().configure_params() + + for name, param in self.params: + if param.requires_grad: + self.Hessian_matrix[name] = torch.ones(size=param.data.size(), device=param.data.device, + dtype=param.data.dtype) + + @torch.no_grad() + def efficient_Hessian_perturb_parameters(self, random_seed: int, Hessian_matrix=None, + scaling_factor=1): + torch.manual_seed(random_seed) + for name, param in self.params: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor / torch.sqrt(Hessian_matrix[name]) * z * self.zero_order_eps + + def zo_Hessian_step(self, model, batch, random_seed): + loss_original = self.zo_forward_memory_eff(model, batch) + + self.efficient_Hessian_perturb_parameters(random_seed, self.Hessian_matrix, scaling_factor=1) + loss1 = self.zo_forward_memory_eff(model, batch) + self.efficient_Hessian_perturb_parameters(random_seed, self.Hessian_matrix, scaling_factor=-2) + loss2 = self.zo_forward_memory_eff(model, batch) + self.efficient_Hessian_perturb_parameters(random_seed, self.Hessian_matrix, scaling_factor=1) + return loss_original, loss1, loss2 + + def zo_Hessian_update(self, random_seed, loss_original, loss1, loss2, Hessian_smooth, num_grad_est): + torch.manual_seed(random_seed) + for name, param in self.params: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, + dtype=param.data.dtype) + + Hessian_temp = self.Hessian_matrix[name] * z * z + Hessian_estimator = (torch.abs(loss1 + loss2 - 2 * loss_original) * Hessian_temp * Hessian_smooth / ( + 2 * self.zero_order_eps * self.zero_order_eps)) + + self.Hessian_matrix[name] = ((1 - Hessian_smooth) * self.Hessian_matrix[name] + Hessian_estimator) + + grad = (loss1 - loss2) / (2 * self.zero_order_eps) * z / torch.sqrt(self.Hessian_matrix[name]) + grad = grad / num_grad_est + param.data = param.data - self.state.learning_rate * (grad + self.weight_decay * param.data) + + def training_step(self, model, batch, tb_writer=None, **kwargs): + num_grad_est = self.num_queries // 3 + n = batch['input_ids'].size(0) + start_time = time.perf_counter() + random_seeds = [np.random.randint(1000000000) for _ in range(num_grad_est)] + log_dict = kwargs['log'] + + Hessian_smooth = Hessian_smooth_scheduler(self.hessian_smooth_type, self.state.global_training_steps, + self.num_epochs) + + losses = [] + for k in range(num_grad_est): + loss_original, loss1, loss2 = self.zo_Hessian_step(model, batch, random_seeds[k]) + losses.append(loss_original.item()) + self.zo_Hessian_update(random_seeds[k], loss_original, loss1, loss2, Hessian_smooth, num_grad_est) + + lmean = np.mean(losses) + self.state.global_training_steps += 1 + + # logging + total_time = time.perf_counter() - start_time + + self.state.time.append(total_time) + self.state.query.append(3 * n * num_grad_est) + + log_dict['train_loss'] = lmean.item() + log_dict['time'] = total_time \ No newline at end of file diff --git a/baselines/loren/model/glue_transformer_loren.py b/baselines/loren/model/glue_transformer_loren.py new file mode 100644 index 0000000..2bc726c --- /dev/null +++ b/baselines/loren/model/glue_transformer_loren.py @@ -0,0 +1,159 @@ +import math +import time +from typing import Optional + +import numpy as np +import torch + +from .glue_transformer_lozo import GLUETransformerLoZo +from common.alg_utils import sgd_with_wdecay + + +class GLUETransformerLOREN(GLUETransformerLoZo): + def __init__( + self, + model_name_or_path: str, + num_labels: int, + zero_order_eps: float = 1e-3, + learning_rate_aux: float = 1e-3, + minibatch: int = 64, + max_norm: float = 18000.0, + z_std: float = 1.0, + lr_anneal: float = 1.0, + full_parameter: bool = True, + batchsize_limit: int = 16, + eval_splits: Optional[list] = None, + soft_prompt: bool = False, + use_SGD: bool = True, + logger_type: str = 'wandb', + hf_token: Optional[str] = None, + lora: bool = False, + model_init_seed: Optional[int] = None, + weight_decay: float = 0.01, + damping: float = 0.1, + lr_cov: float = 2e-3, + beta1: float = 0.9, + num_queries: int = 10, + **kwargs, + ): + super().__init__(model_name_or_path, + num_labels, + zero_order_eps, + learning_rate_aux, + minibatch, + max_norm, + z_std, + lr_anneal, + full_parameter, + batchsize_limit, + eval_splits, + soft_prompt, + use_SGD, + logger_type, + hf_token, + lora, + model_init_seed, + weight_decay) + + self.damping = damping + self.lr_cov = lr_cov + self.d_sqrt = math.sqrt(damping) + self.evec_a = {} + self.momentum = {} + self.num_queries = num_queries + self.beta1 = beta1 + self.param_info = {} + + assert num_queries >= 2, 'At least 2 samples are required for RLOO estimation' + + def configure_params(self): + super().configure_params() + for name, param in self.params: + param_shape = param.shape + param_flat_size = param.numel() + evec_size = param.size(1) if param.ndim >= 2 else param_flat_size + a = torch.randn(evec_size, device=param.device, dtype=param.dtype) + self.evec_a[name] = a + if param.ndim >= 2: + self.momentum[name] = torch.zeros_like(param) + self.param_info[name] = { + 'shape': param_shape, + 'flat_size': param_flat_size, + 'evec_size': evec_size, + 'mfactor': param_flat_size // evec_size + } + + @torch.no_grad() + def perturb_parameters(self, random_seed: int, scaling_factor=1): + torch.manual_seed(random_seed) + for name, param in self.params: + info = self.param_info[name] + shape = info['shape'] + a = self.evec_a[name] + a_flat = a.view(1, -1).expand(info['mfactor'], -1).reshape(-1) + u_vec = torch.randn_like(param).view(-1) + sq_norm_a = torch.dot(a_flat, a_flat) + dot_au = torch.dot(a_flat, u_vec) + damping_sq_norm_a = math.sqrt(self.damping + sq_norm_a.item()) + alpha = (self.d_sqrt + damping_sq_norm_a) * dot_au / (sq_norm_a * damping_sq_norm_a) + sqrt_cov_u = u_vec.sub(alpha * a_flat).view(shape) + param.add_(sqrt_cov_u, alpha=scaling_factor * self.zero_order_eps) + + @torch.no_grad() + def lnes_zo_update(self, random_seeds, fvals, fmean): + fweight = torch.tensor(fvals, device='cuda') - fmean + num_queries_inv = 1.0 / (self.num_queries - 1) + eps_inv = 1.0 / (self.zero_order_eps * (self.num_queries - 1)) + + for k in range(self.num_queries): + torch.manual_seed(random_seeds[k]) + for name, param in self.params: + info = self.param_info[name] + shape = info['shape'] + a = self.evec_a[name] + a_flat = a.view(1, -1).expand(info['mfactor'], -1).reshape(-1) + u_vec = torch.randn_like(param).view(-1) + sq_norm_a = torch.dot(a_flat, a_flat) + dot_au = torch.dot(a_flat, u_vec) + damping_sq_norm_a = math.sqrt(self.damping + sq_norm_a.item()) + + alpha = (self.d_sqrt + damping_sq_norm_a) * dot_au / (sq_norm_a * damping_sq_norm_a) + sqrt_cov_u = u_vec.sub(alpha * a_flat).view(shape) + + gx = sqrt_cov_u.mul(fweight[k] * eps_inv) + if param.ndim >= 2: + self.momentum[name].mul_(self.beta1).add_(gx) + gx = self.momentum[name] + sgd_with_wdecay(param, gx, self.state.learning_rate, self.weight_decay) + + c1 = (dot_au * u_vec - a_flat) + c2 = (self.d_sqrt + damping_sq_norm_a) * (dot_au ** 2 - sq_norm_a) * a_flat / (sq_norm_a * damping_sq_norm_a) + ak_grad = fweight[k] * (self.zero_order_eps ** 2) * (c1 - c2) / damping_sq_norm_a + ak_grad = ak_grad.view(shape).sum(0) * num_queries_inv + sgd_with_wdecay(self.evec_a[name], ak_grad, self.lr_cov, self.weight_decay) + + def training_step(self, model, batch, tb_writer=None, **kwargs): + n = batch['input_ids'].size(0) + start_time = time.perf_counter() + random_seeds = [np.random.randint(1000000000) for _ in range(self.num_queries)] + log_dict = kwargs['log'] + + fvals = [] + with torch.inference_mode(): + for k in range(self.num_queries): + self.perturb_parameters(random_seeds[k], scaling_factor=1) + loss = self.zo_forward_memory_eff(model, batch) + fvals.append(loss.item()) + self.perturb_parameters(random_seeds[k], scaling_factor=-1) + + fmean = np.mean(fvals) + self.lnes_zo_update(random_seeds, fvals, fmean) + self.state.global_training_steps += 1 + + total_time = time.perf_counter() - start_time + + self.state.time.append(total_time) + self.state.query.append(self.num_queries * n) + + log_dict['train_loss'] = fmean.item() + log_dict['time'] = total_time diff --git a/baselines/loren/model/glue_transformer_lozo.py b/baselines/loren/model/glue_transformer_lozo.py new file mode 100644 index 0000000..6557e0c --- /dev/null +++ b/baselines/loren/model/glue_transformer_lozo.py @@ -0,0 +1,145 @@ +import time +from typing import Optional + +import numpy as np +import torch + +from .glue_transformer_mezo import GLUETransformerMeZo + + +class GLUETransformerLoZo(GLUETransformerMeZo): + def __init__( + self, + model_name_or_path: str, + num_labels: int, + zero_order_eps: float = 1e-3, + learning_rate_aux: float = 1e-3, + minibatch: int = 64, + max_norm: float = 18000.0, + z_std: float = 1.0, + lr_anneal: float = 1.0, + full_parameter: bool = True, + batchsize_limit: int = 16, + eval_splits: Optional[list] = None, + soft_prompt: bool = False, + use_SGD: bool = True, + logger_type: str = 'wandb', + hf_token: Optional[str] = None, + lora: bool = False, + model_init_seed: Optional[int] = None, + step_interval: int = 50, # subspace bases update interval in LoZo + rank: int = 2, + weight_decay: float = 0.01, + **kwargs, + ): + super().__init__(model_name_or_path, + num_labels, + zero_order_eps, + learning_rate_aux, + minibatch, + max_norm, + z_std, + lr_anneal, + full_parameter, + batchsize_limit, + eval_splits, + soft_prompt, + use_SGD, + logger_type, + hf_token, + lora, + model_init_seed) + self.rank = rank + self.basis_upd_interval = step_interval + self.subspace_basis = {} + self.weight_decay = weight_decay + + @torch.no_grad() + def lowrank_perturb_parameters(self, random_seed, scaling_factor=1, pos=None): + torch.manual_seed(random_seed) + + for name, param in self.params: + if param.data.ndim >= 2: + V = self.subspace_basis[name] + + U = torch.randn(param.data.size(0), self.rank, + device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * (U @ V.t()) * self.zero_order_eps + else: + z = torch.normal(mean=0, std=self.z_std, size=param.data.size(), + device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * self.zero_order_eps + + def lowrank_zo_step(self, model, batch, random_seed, pos=None): + self.lowrank_perturb_parameters(random_seed, scaling_factor=1, pos=pos) + loss1 = self.zo_forward_memory_eff(model, batch) + + # second function evaluation + self.lowrank_perturb_parameters(random_seed, scaling_factor=-2, pos=pos) + loss2 = self.zo_forward_memory_eff(model, batch) + + projected_grad = ((loss1 - loss2) / (2 * self.zero_order_eps)).item() + + # reset model back to its parameters at start of step + self.lowrank_perturb_parameters(random_seed, scaling_factor=1, pos=pos) + return loss1, projected_grad + + @torch.no_grad() + def _gd_with_decay(self, name, param, grad): + if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + param.mul_(1.0 - self.state.learning_rate * self.weight_decay) + + param.sub_(grad, alpha=self.state.learning_rate) + + def lowrank_zo_update(self, random_seed, proj_grad): + torch.manual_seed(random_seed) + + for name, param in self.params: + if param.data.ndim >= 2: + V = self.subspace_basis[name] + U = torch.randn(param.data.size(0), self.rank, + device=param.data.device, dtype=param.data.dtype) + grad = proj_grad * (U @ V.t()) + else: + z = torch.normal(mean=0, std=1, size=param.data.size(), + device=param.data.device, dtype=param.data.dtype) + grad = proj_grad * z + + self._gd_with_decay(name, param, grad) + + def update_basis(self, sub_dim: int = 1): + for name, param in self.params: + if param.data.ndim >= 2: + self.subspace_basis[name] = torch.randn(param.data.size(sub_dim), + self.rank, + device=param.data.device, + dtype=param.data.dtype) + + def training_step(self, model, batch, tb_writer=None, **kwargs): + num_grad_est = self.num_queries // 2 + n = batch['input_ids'].size(0) + start_time = time.perf_counter() + random_seeds = [np.random.randint(1000000000) for _ in range(num_grad_est)] + log_dict = kwargs['log'] + + step = self.state.global_training_steps + if step % self.basis_upd_interval == 0: + self.update_basis(sub_dim=1) + + losses = [] + for k in range(num_grad_est): + loss, proj_grad = self.lowrank_zo_step(model, batch, random_seeds[k]) + losses.append(loss.item()) + mean_proj_grad = proj_grad / num_grad_est + self.lowrank_zo_update(random_seeds[k], mean_proj_grad) + + lmean = np.mean(losses) + self.state.global_training_steps += 1 + + total_time = time.perf_counter() - start_time + + self.state.time.append(total_time) + self.state.query.append(2*n*num_grad_est) + + log_dict['train_loss'] = lmean.item() + log_dict['time'] = total_time diff --git a/baselines/loren/model/glue_transformer_mezo.py b/baselines/loren/model/glue_transformer_mezo.py new file mode 100644 index 0000000..a3ddd90 --- /dev/null +++ b/baselines/loren/model/glue_transformer_mezo.py @@ -0,0 +1,75 @@ +import time + +import numpy as np +import torch + +from .glue_transformer import GLUETransformer + + +class GLUETransformerMeZo(GLUETransformer): + def perturb_parameters(self, random_seed: int, scaling_factor=1): + torch.manual_seed(random_seed) + + for name, param in self.params: + z = torch.normal(mean=0, std=self.z_std, size=param.data.size(), + device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * self.zero_order_eps + + def zo_step(self, model, batch, random_seed): + """ + Zeroth-order gradient estimation + """ + # first function evaluation + self.perturb_parameters(random_seed, scaling_factor=1) + loss1 = self.zo_forward_memory_eff(model, batch) + + # second function evaluation + self.perturb_parameters(random_seed, scaling_factor=-2) + loss2 = self.zo_forward_memory_eff(model, batch) + + projected_grad = ((loss1 - loss2) / (2 * self.zero_order_eps)).item() + + # model_dtype = next(self.model.parameters()).dtype + # projected_grad = projected_grad.to(model_dtype) + + # reset model back to its parameters at start of step + self.perturb_parameters(random_seed, scaling_factor=1) + + return loss1, projected_grad + + @torch.no_grad() + def zo_update(self, random_seed, projected_grad, scale=-1): + torch.manual_seed(random_seed) + + # compute SPSA gradient estimator + for _, param in self.params: + u = torch.normal(mean=0, std=1, size=param.data.size(), + device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scale * self.state.learning_rate * projected_grad * u + + def training_step(self, model, batch, tb_writer=None, **kwargs): + # run ZO update + num_grad_est = self.num_queries // 2 + n = batch['input_ids'].size(0) + start_time = time.perf_counter() + random_seeds = [np.random.randint(1000000000) for _ in range(num_grad_est)] + log_dict = kwargs['log'] + + losses = [] + for k in range(num_grad_est): + loss, projected_grad = self.zo_step(model, batch, random_seeds[k]) + losses.append(loss.item()) + mean_proj_grad = projected_grad / num_grad_est + self.zo_update(random_seeds[k], mean_proj_grad) + + lmean = np.mean(losses) + self.state.global_training_steps += 1 + + # logging + total_time = time.perf_counter() - start_time + + self.state.time.append(total_time) + self.state.query.append(2*n*num_grad_est) + + log_dict['train_loss'] = lmean.item() + log_dict['time'] = total_time diff --git a/baselines/loren/model/glue_transformer_svrg.py b/baselines/loren/model/glue_transformer_svrg.py new file mode 100644 index 0000000..992e8fc --- /dev/null +++ b/baselines/loren/model/glue_transformer_svrg.py @@ -0,0 +1,182 @@ +import logging +import time +from typing import Optional + +import numpy as np +import torch + +from .glue_transformer_mezo import GLUETransformerMeZo + + +class GLUETransformerMeZoSVRG(GLUETransformerMeZo): + def __init__( + self, + model_name_or_path: str, + num_labels: int, + zero_order_eps: float = 1e-3, + learning_rate_aux: float = 1e-3, + minibatch: int = 64, + max_norm: float = 18000.0, + z_std: float = 1.0, + lr_anneal: float = 1.0, + full_parameter: bool = True, + batchsize_limit: int = 16, + eval_splits: Optional[list] = None, + soft_prompt: bool = False, + use_SGD: bool = True, + logger_type: str = 'wandb', + hf_token: Optional[str] = None, + lora: bool = False, + model_init_seed: Optional[int] = None, + q: int = 1, + **kwargs, + ): + super().__init__( + model_name_or_path, + num_labels, + zero_order_eps, + learning_rate_aux, + minibatch, + max_norm, + z_std, + lr_anneal, + full_parameter, + batchsize_limit, + eval_splits, + soft_prompt, + use_SGD, + logger_type, + hf_token, + lora, + model_init_seed) + + self.q = q + + def training_step(self, model, batch, tb_writer=None, **kwargs): + # run MeZO-SVRG update + n = batch['input_ids'].size(0) + logging.debug(f'Batch size: {n}') + start_time = time.perf_counter() + log_dict = kwargs['log'] + + # current iteration + curr_iter = kwargs['curr_iter'] + total_batches = kwargs['full_batch_size'] + w = 2 * total_batches + full_batch = kwargs['is_full_batch'] + + # learning rate scheduling strategy + if len(self.state.tr_loss_minibatch) > 2*w and curr_iter % total_batches == 0: + v1, v2 = self.get_average_np(self.state.tr_loss_minibatch, int(w/2)) + logging.debug(f'leading average: {v1}') + logging.debug(f'trailing average: {v2}') + if v1/v2 > 1.05: + self.state.learning_rate_aux = max(self.state.learning_rate_aux/self.lr_anneal, 1e-5) + self.state.learning_rate = max(self.state.learning_rate/self.lr_anneal, 1e-6) + logging.debug(f'Learning rate (full-batch): {self.state.learning_rate_aux}') + logging.debug(f'Learning rate (mini-batch): {self.state.learning_rate}') + self.state.lr_list.append(self.state.learning_rate_aux) + + # parameters contains tuples of params to optimize in list + parameters = self.params + + # do full batch update every q steps + if full_batch is True: + self.state.full_grad = self.SPSA_estimator(model, parameters, batch) + self.parameters = parameters.copy() + with torch.no_grad(): + for name, param in parameters: + param.data = param.data - self.state.learning_rate_aux * self.state.full_grad[name] + else: + # minibatch update + parameters = self.SPSA_estimator_me(model, parameters, batch, scale=-1) # in-place operation + parameters = self.SPSA_estimator_me(model, self.parameters, batch) # in-place operation + + with torch.no_grad(): + for name, param in parameters: + param.data = param.data - self.state.learning_rate * self.state.full_grad[name] + + self.state.global_training_steps += 1 + + total_time = time.perf_counter() - start_time + self.state.time.append(total_time) + self.state.query.append(2*n) + + with torch.no_grad(): + # loss computation + loss = self.zo_forward_memory_eff(model, batch) + + # self.log_training_loss(model, batch, + # fullbatch=True if curr_iter % self.q == 0 else False, + # tb_writer=tb_writer) + if full_batch: + self.state.tr_loss.append(loss.detach().cpu().float().numpy()) + log_dict['fb_train_loss'] = loss.item() + else: + self.state.tr_loss_minibatch.append(loss.detach().cpu().float().numpy()) + log_dict['train_loss'] = loss.item() + + log_dict['time'] = total_time + # log_dict['memory'] = self.measure_memory_usage() + + def SPSA_estimator(self, model, parameters, batch): + return self.central_difference_grad_est(model, parameters, batch) + + def SPSA_estimator_me(self, model, parameters, batch, scale=1): + # memory efficient SPSA estimator + return self.central_difference_grad_est_me(model, parameters, batch, scale) + + def central_difference_grad_est(self, model, parameters, batch, uniform=False): + random_seed = np.random.randint(1000000000, size=1) + with torch.no_grad(): + # first function evaluation + self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform) + loss1 = self.zo_forward_memory_eff(model, batch) + # second function evaluation + self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform, scaling_factor=-2) + loss2 = self.zo_forward_memory_eff(model, batch) + proj_grad = (loss1 - loss2)/(2 * self.zero_order_eps) + model_dtype = next(self.model.parameters()).dtype + proj_grad = proj_grad.to(model_dtype) + logging.debug(f'Projected Grad: {proj_grad}') + self.state.proj_val.append(torch.abs(proj_grad).detach().cpu().float().numpy()) + + estimator = {} + self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform) + torch.manual_seed(random_seed) + for name, param in parameters: + if uniform: + # uniform distribution over unit sphere + z = torch.randn(size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + z = z / torch.linalg.norm(z) + else: + z = torch.normal(mean=0, std=self.z_std, size=param.data.size(), + device=param.data.device, dtype=param.data.dtype) + estimator[name] = proj_grad*z + return estimator + + def central_difference_grad_est_me(self, model, parameters, batch, scale, uniform=False): + # memory efficient central difference spsa estimator + random_seed = np.random.randint(1000000000, size=1) + with torch.no_grad(): + # first function evaluation + self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform) + loss1 = self.zo_forward_memory_eff(model, batch) + # second function evaluation + self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform, scaling_factor=-2) + loss2 = self.zo_forward_memory_eff(model, batch) + proj_grad = (loss1 - loss2)/(2 * self.zero_order_eps) + self.state.proj_val.append(torch.abs(proj_grad).detach().cpu().float().numpy()) + + self.efficient_perturb_parameters(parameters, random_seed, uniform=uniform) + torch.manual_seed(random_seed) + for name, param in parameters: + if uniform: + # uniform distribution over unit sphere + z = torch.randn(size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + z = z / torch.linalg.norm(z) + else: + z = torch.normal(mean=0, std=self.z_std, size=param.data.size(), + device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scale * self.state.learning_rate * proj_grad * z + return parameters diff --git a/baselines/loren/model/opt.py b/baselines/loren/model/opt.py new file mode 100644 index 0000000..6b8a467 --- /dev/null +++ b/baselines/loren/model/opt.py @@ -0,0 +1,1360 @@ +import random +from typing import List, Optional, Tuple, Union + +import loralib as lora +import torch +import torch.utils.checkpoint +from torch import nn +from transformers import PretrainedConfig +from transformers.activations import ACT2FN +from transformers.modeling_outputs import (BaseModelOutputWithPast, + CausalLMOutputWithPast, + QuestionAnsweringModelOutput, + SequenceClassifierOutputWithPast) +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import (add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, logging, + replace_return_docstrings) + +logger = logging.get_logger(__name__) + +_CHECKPOINT_FOR_DOC = "facebook/opt-350m" +_CONFIG_FOR_DOC = "OPTConfig" +_TOKENIZER_FOR_DOC = "GPT2Tokenizer" + +# Base model docstring +_EXPECTED_OUTPUT_SHAPE = [1, 8, 1024] + +# SequenceClassification docstring +_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ArthurZ/opt-350m-dummy-sc" +_SEQ_CLASS_EXPECTED_LOSS = 1.71 +_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_0'" + +OPT_PRETRAINED_MODEL_ARCHIVE_LIST = [ + "facebook/opt-125m", + "facebook/opt-350m", + "facebook/opt-1.3b", + "facebook/opt-2.7b", + "facebook/opt-6.7b", + "facebook/opt-13b", + "facebook/opt-30b", + # See all OPT models at https://huggingface.co/models?filter=opt +] + + +class OPTConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`OPTModel`]. It is used to instantiate a OPT model + according to the specified arguments, defining the model architecture. Instantiating a configuration with the + defaults will yield a similar configuration to that of the OPT + [facebook/opt-350m](https://huggingface.co/facebook/opt-350m) architecture. + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + + Args: + vocab_size (`int`, *optional*, defaults to 50272): + Vocabulary size of the OPT model. Defines the number of different tokens that can be represented by the + `inputs_ids` passed when calling [`OPTModel`] + hidden_size (`int`, *optional*, defaults to 768): + Dimensionality of the layers and the pooler layer. + num_hidden_layers (`int`, *optional*, defaults to 12): + Number of decoder layers. + ffn_dim (`int`, *optional*, defaults to 3072): + Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. + num_attention_heads (`int`, *optional*, defaults to 12): + Number of attention heads for each attention layer in the Transformer decoder. + activation_function (`str` or `function`, *optional*, defaults to `"relu"`): + The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, + `"relu"`, `"silu"` and `"gelu_new"` are supported. + max_position_embeddings (`int`, *optional*, defaults to 2048): + The maximum sequence length that this model might ever be used with. Typically set this to something large + just in case (e.g., 512 or 1024 or 2048). + do_layer_norm_before (`bool`, *optional*, defaults to `True`): + Whether to perform layer normalization before the attention block. + word_embed_proj_dim (`int`, *optional*): + `word_embed_proj_dim` can be set to down-project word embeddings, *e.g.* `opt-350m`. Defaults to + `hidden_size`. + dropout (`float`, *optional*, defaults to 0.1): + The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. + attention_dropout (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + layerdrop: (`float`, *optional*, defaults to 0.0): + The LayerDrop probability. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more + details. + init_std (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + use_cache (`bool`, *optional*, defaults to `True`): + Whether or not the model should return the last key/values attentions (not used by all models). + + Example: + + ```python + >>> from transformers import OPTConfig, OPTModel + + >>> # Initializing a OPT facebook/opt-large style configuration + >>> configuration = OPTConfig() + + >>> # Initializing a model (with random weights) from the facebook/opt-large style configuration + >>> model = OPTModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + model_type = "opt" + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + vocab_size=50272, + hidden_size=768, + num_hidden_layers=12, + ffn_dim=3072, + max_position_embeddings=2048, + do_layer_norm_before=True, + _remove_final_layer_norm=False, + word_embed_proj_dim=None, + dropout=0.1, + attention_dropout=0.0, + num_attention_heads=12, + activation_function="relu", + layerdrop=0.0, + init_std=0.02, + use_cache=True, + pad_token_id=1, + bos_token_id=2, + eos_token_id=2, + apply_lora=False, + lora_r=None, + lora_alpha=None, + **kwargs + ): + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + **kwargs, + ) + self.vocab_size = vocab_size + self.max_position_embeddings = max_position_embeddings + self.num_attention_heads = num_attention_heads + self.word_embed_proj_dim = word_embed_proj_dim if word_embed_proj_dim is not None else hidden_size + self.ffn_dim = ffn_dim + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.dropout = dropout + self.attention_dropout = attention_dropout + self.activation_function = activation_function + self.init_std = init_std + self.layerdrop = layerdrop + self.use_cache = use_cache + self.do_layer_norm_before = do_layer_norm_before + + self.apply_lora = apply_lora + self.lora_r = lora_r + self.lora_alpha = lora_alpha + + # Note that the only purpose of `_remove_final_layer_norm` is to keep backward compatibility + # with checkpoints that have been fine-tuned before transformers v4.20.1 + # see https://github.com/facebookresearch/metaseq/pull/164 + self._remove_final_layer_norm = _remove_final_layer_norm + + +def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0): + """ + Make causal mask used for bi-directional self-attention. + """ + bsz, tgt_len = input_ids_shape + mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min)) + mask_cond = torch.arange(mask.size(-1)) + mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) + mask = mask.to(dtype) + + if past_key_values_length > 0: + mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1) + return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) + + +def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + bsz, src_len = mask.size() + tgt_len = tgt_len if tgt_len is not None else src_len + + expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) + + inverted_mask = 1.0 - expanded_mask + + return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) + + +class OPTLearnedPositionalEmbedding(nn.Embedding): + """ + This module learns positional embeddings up to a fixed maximum size. + """ + + def __init__(self, num_embeddings: int, embedding_dim: int): + # OPT is set up so that if padding_idx is specified then offset the embedding ids by 2 + # and adjust num_embeddings appropriately. Other models don't have this hack + self.offset = 2 + super().__init__(num_embeddings + self.offset, embedding_dim) + + def forward(self, attention_mask: torch.LongTensor, past_key_values_length: int = 0): + """`input_ids_shape` is expected to be [bsz x seqlen].""" + attention_mask = attention_mask.long() + + # create positions depending on attention_mask + positions = (torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask).long() - 1 + + # cut positions if `past_key_values_length` is > 0 + positions = positions[:, past_key_values_length:] + + return super().forward(positions + self.offset) + + +class OPTAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__( + self, + embed_dim: int, + num_heads: int, + dropout: float = 0.0, + is_decoder: bool = False, + bias: bool = True, + apply_lora: bool = False, + lora_r: int = None, + lora_alpha: int = None + ): + super().__init__() + self.embed_dim = embed_dim + self.num_heads = num_heads + self.dropout = dropout + self.head_dim = embed_dim // num_heads + + if (self.head_dim * num_heads) != self.embed_dim: + raise ValueError( + f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" + f" and `num_heads`: {num_heads})." + ) + self.scaling = self.head_dim**-0.5 + self.is_decoder = is_decoder + + if apply_lora: + self.q_proj = lora.Linear(embed_dim, embed_dim, lora_r, lora_alpha=lora_alpha, bias=bias) + else: + self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + if apply_lora: + self.v_proj = lora.Linear(embed_dim, embed_dim, lora_r, lora_alpha=lora_alpha, bias=bias) + else: + self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + # original OPT code + # self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + # self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + # self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def forward( + self, + hidden_states: torch.Tensor, + key_value_states: Optional[torch.Tensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + """Input shape: Batch x Time x Channel""" + + # if key_value_states are provided this layer is used as a cross-attention layer + # for the decoder + is_cross_attention = key_value_states is not None + + bsz, tgt_len, _ = hidden_states.size() + + # get query proj + query_states = self.q_proj(hidden_states) * self.scaling + # get key, value proj + if is_cross_attention and past_key_value is not None: + # reuse k,v, cross_attentions + key_states = past_key_value[0] + value_states = past_key_value[1] + elif is_cross_attention: + # cross_attentions + key_states = self._shape(self.k_proj(key_value_states), -1, bsz) + value_states = self._shape(self.v_proj(key_value_states), -1, bsz) + elif past_key_value is not None: + # reuse k, v, self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + else: + # self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + + if self.is_decoder: + # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. + # Further calls to cross_attention layer can then reuse all cross-attention + # key/value_states (first "if" case) + # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of + # all previous decoder key/value_states. Further calls to uni-directional self-attention + # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) + # if encoder bi-directional self-attention `past_key_value` is always `None` + past_key_value = (key_states, value_states) + + proj_shape = (bsz * self.num_heads, -1, self.head_dim) + query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape) + key_states = key_states.view(*proj_shape) + value_states = value_states.view(*proj_shape) + + src_len = key_states.size(1) + attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) + + if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len): + raise ValueError( + f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, tgt_len, src_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" + ) + attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask + attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437 + if attn_weights.dtype == torch.float16: + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16) + else: + attn_weights = nn.functional.softmax(attn_weights, dim=-1) + + if layer_head_mask is not None: + if layer_head_mask.size() != (self.num_heads,): + raise ValueError( + f"Head mask for a single layer should be of size {(self.num_heads,)}, but is" + f" {layer_head_mask.size()}" + ) + attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + if output_attentions: + # this operation is a bit awkward, but it's required to + # make sure that attn_weights keeps its gradient. + # In order to do so, attn_weights have to be reshaped + # twice and have to be reused in the following + attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len) + else: + attn_weights_reshaped = None + + attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) + + attn_output = torch.bmm(attn_probs, value_states) + + if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) + attn_output = attn_output.transpose(1, 2) + + # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be + # partitioned aross GPUs when using tensor-parallelism. + attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) + + attn_output = self.out_proj(attn_output) + + return attn_output, attn_weights_reshaped, past_key_value + + +class OPTDecoderLayer(nn.Module): + def __init__(self, config: OPTConfig): + super().__init__() + self.embed_dim = config.hidden_size + self.self_attn = OPTAttention( + embed_dim=self.embed_dim, + num_heads=config.num_attention_heads, + dropout=config.attention_dropout, + is_decoder=True, + apply_lora=config.apply_lora, + lora_r=config.lora_r, + lora_alpha=config.lora_alpha + ) + self.do_layer_norm_before = config.do_layer_norm_before + self.dropout = config.dropout + self.activation_fn = ACT2FN[config.activation_function] + + self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) + self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim) + self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim) + self.final_layer_norm = nn.LayerNorm(self.embed_dim) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size + `(encoder_attention_heads,)`. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + past_key_value=past_key_value, + attention_mask=attention_mask, + layer_head_mask=layer_head_mask, + output_attentions=output_attentions, + ) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + hidden_states = residual + hidden_states + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Fully Connected + hidden_states_shape = hidden_states.shape + hidden_states = hidden_states.reshape(-1, hidden_states.size(-1)) + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + hidden_states = self.fc1(hidden_states) + hidden_states = self.activation_fn(hidden_states) + + hidden_states = self.fc2(hidden_states) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + + hidden_states = (residual + hidden_states).view(hidden_states_shape) + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +OPT_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`OPTConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTPreTrainedModel(PreTrainedModel): + + config_class = OPTConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["OPTDecoderLayer"] + _keys_to_ignore_on_load_unexpected = [r"decoder\.version"] + + def _init_weights(self, module): + std = self.config.init_std + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, (OPTDecoder)): + module.gradient_checkpointing = value + + +OPT_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`GPT2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`OPTTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape + `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape + `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +class OPTDecoder(OPTPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`] + + Args: + config: OPTConfig + """ + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.dropout = config.dropout + self.layerdrop = config.layerdrop + self.padding_idx = config.pad_token_id + self.max_target_positions = config.max_position_embeddings + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.word_embed_proj_dim, self.padding_idx) + self.embed_positions = OPTLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size) + + if config.word_embed_proj_dim != config.hidden_size: + self.project_out = nn.Linear(config.hidden_size, config.word_embed_proj_dim, bias=False) + else: + self.project_out = None + + if config.word_embed_proj_dim != config.hidden_size: + self.project_in = nn.Linear(config.word_embed_proj_dim, config.hidden_size, bias=False) + else: + self.project_in = None + + # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility + # with checkpoints that have been fine-tuned before transformers v4.20.1 + # see https://github.com/facebookresearch/metaseq/pull/164 + if config.do_layer_norm_before and not config._remove_final_layer_norm: + self.final_layer_norm = nn.LayerNorm(config.hidden_size) + else: + self.final_layer_norm = None + + self.layers = nn.ModuleList([OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)]) + + self.gradient_checkpointing = False + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask + def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): + # create causal mask + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + combined_attention_mask = None + if input_shape[-1] > 1: + combined_attention_mask = _make_causal_mask( + input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length + ).to(inputs_embeds.device) + + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( + inputs_embeds.device + ) + combined_attention_mask = ( + expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask + ) + + return combined_attention_mask + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`OPTTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + """ + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + # embed positions + if attention_mask is None: + attention_mask = torch.ones(inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device) + pos_embeds = self.embed_positions(attention_mask, past_key_values_length) + + attention_mask = self._prepare_decoder_attention_mask( + attention_mask, input_shape, inputs_embeds, past_key_values_length + ) + + if self.project_in is not None: + inputs_embeds = self.project_in(inputs_embeds) + + hidden_states = inputs_embeds + pos_embeds + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + # check if head_mask has a correct number of layers specified if desired + for attn_mask, mask_name in zip([head_mask], ["head_mask"]): + if attn_mask is not None: + if attn_mask.size()[0] != (len(self.layers)): + raise ValueError( + f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" + f" {head_mask.size()[0]}." + ) + + for idx, decoder_layer in enumerate(self.layers): + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + if use_cache: + logger.warning( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + if self.final_layer_norm is not None: + hidden_states = self.final_layer_norm(hidden_states) + + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTModel(OPTPreTrainedModel): + def __init__(self, config: OPTConfig): + super().__init__(config) + self.decoder = OPTDecoder(config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.decoder.embed_tokens = value + + def get_decoder(self): + return self.decoder + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + processor_class=_TOKENIZER_FOR_DOC, + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=BaseModelOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_EXPECTED_OUTPUT_SHAPE, + ) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn) + decoder_outputs = self.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + if not return_dict: + return decoder_outputs + + return BaseModelOutputWithPast( + last_hidden_state=decoder_outputs.last_hidden_state, + past_key_values=decoder_outputs.past_key_values, + hidden_states=decoder_outputs.hidden_states, + attentions=decoder_outputs.attentions, + ) + + +class OPTForCausalLM(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = OPTModel(config) + + # the lm_head weight is automatically tied to the embed tokens weight + self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model.decoder = decoder + + def get_decoder(self): + return self.model.decoder + + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`OPTTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional + tensors are only required when the model is used as a decoder in a Sequence to Sequence model. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + + Returns: + + Example: + + ```python + >>> from transformers import GPT2Tokenizer, OPTForCausalLM + + >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m") + >>> tokenizer = GPT2Tokenizer.from_pretrained("facebook/opt-350m") + + >>> prompt = "Hey, are you consciours? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + outputs = self.model.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + logits = self.lm_head(outputs[0]).contiguous() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = nn.CrossEntropyLoss() + loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, use_cache=None, **kwargs): + # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly + if attention_mask is None: + attention_mask = input_ids.new_ones(input_ids.shape) + + if past: + input_ids = input_ids[:, -1:] + # first step, decoder_cached_states are empty + return { + "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed + "attention_mask": attention_mask, + "past_key_values": past, + "use_cache": use_cache, + } + + @staticmethod + def _reorder_cache(past, beam_idx): + reordered_past = () + for layer_past in past: + reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) + return reordered_past + + +@add_start_docstrings( + """ + The OPT Model transformer with a sequence classification head on top (linear layer). + + [`OPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + OPT_START_DOCSTRING, +) +class OPTForSequenceClassification(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.num_labels = config.num_labels + self.model = OPTModel(config) + self.score = nn.Linear(config.word_embed_proj_dim, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + processor_class=_TOKENIZER_FOR_DOC, + checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION, + output_type=SequenceClassifierOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_SEQ_CLASS_EXPECTED_OUTPUT, + expected_loss=_SEQ_CLASS_EXPECTED_LOSS, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size, sequence_length = input_ids.shape[:2] + else: + batch_size, sequence_length = inputs_embeds.shape[:2] + + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1 + else: + sequence_lengths = -1 + logger.warning( + f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " + "unexpected if using padding tokens in conjunction with `inputs_embeds.`" + ) + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = nn.MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = nn.CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = nn.BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + +@add_start_docstrings( + """ + The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD + (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + """, + OPT_START_DOCSTRING, +) +class OPTForQuestionAnswering(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.model = OPTModel(config) + self.qa_outputs = nn.Linear(config.word_embed_proj_dim, 2) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + start_positions: Optional[torch.LongTensor] = None, + end_positions: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, QuestionAnsweringModelOutput]: + r""" + start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + + Returns: + + Example: + + ```python + >>> from transformers import GPT2Tokenizer, OPTForQuestionAnswering + >>> import torch + + >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT + >>> tokenizer = GPT2Tokenizer.from_pretrained("facebook/opt-350m") + + >>> # note: we are loading a OPTForQuestionAnswering from the hub here, + >>> # so the head will be randomly initialized, hence the predictions will be random + >>> model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m") + + >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" + + >>> inputs = tokenizer(question, text, return_tensors="pt") + >>> with torch.no_grad(): + ... outputs = model(**inputs) + + >>> answer_start_index = outputs.start_logits.argmax() + >>> answer_end_index = outputs.end_logits.argmax() + + >>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] + >>> predicted = tokenizer.decode(predict_answer_tokens) + >>> predicted + ' Henson?' + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + + logits = self.qa_outputs(hidden_states) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + transformer_outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value diff --git a/baselines/loren/model/prompt_finetune.py b/baselines/loren/model/prompt_finetune.py new file mode 100644 index 0000000..d677f65 --- /dev/null +++ b/baselines/loren/model/prompt_finetune.py @@ -0,0 +1,503 @@ +import random +import logging +from typing import List, Optional, Tuple, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers.modeling_outputs import BaseModelOutputWithPast +from transformers.models.bert.modeling_bert import (BertModel, BertOnlyMLMHead, + BertPreTrainedModel) +from transformers.models.gpt2.modeling_gpt2 import GPT2LMHeadModel +from transformers.models.llama.modeling_llama import LlamaPreTrainedModel, LlamaForCausalLM + +from .opt import OPTDecoder, OPTForCausalLM, OPTModel +from .roberta import RobertaLMHead, RobertaModel, RobertaPreTrainedModel + + +logger = logging.getLogger(__name__) + + +def model_for_prompting_forward( + model, + input_ids=None, + attention_mask=None, + token_type_ids=None, + mask_pos=None, + labels=None, + sfc_input_ids=None, + sfc_attention_mask=None, + sfc_mask_pos=None +): + if sfc_input_ids is not None: + with torch.no_grad(): + logits = model_for_prompting_forward(model, input_ids=sfc_input_ids, + attention_mask=sfc_attention_mask, + mask_pos=sfc_mask_pos)[0] + # icl_sfc_bias = F.log_softmax(logits.detach().squeeze(0)) + + if mask_pos is not None: + mask_pos = mask_pos.squeeze() + + model_fn = model.get_model_fn() + # Encode everything + if token_type_ids is not None: + outputs = model_fn( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids + ) + else: + outputs = model_fn( + input_ids, + attention_mask=attention_mask, + ) + + # Get token representation + sequence_output = outputs[0] + if mask_pos is not None: + sequence_mask_output = sequence_output[torch.arange(sequence_output.size(0)), mask_pos] + else: + sequence_mask_output = sequence_output[:, 0] # representation + # sequence_mask_output = sequence_output.mean(dim=1) # average representation + + if model.label_word_list is not None: + # Logits over vocabulary tokens + head_fn = model.get_lm_head_fn() + prediction_mask_scores = head_fn(sequence_mask_output) + + # Exit early and only return mask logits. + if model.return_full_softmax: + if labels is not None: + return torch.zeros(1, out=prediction_mask_scores.new()), prediction_mask_scores + return prediction_mask_scores + + # Return logits for each label + logits = [] + # use MLM logit + if model.model_args.use_task_word: + vocab_logits = model.lm_head(sequence_mask_output) + for _id in model.label_word_list: + logits.append(vocab_logits[:, _id].unsqueeze(-1)) + # use learned linear head logit on top of task word representation (standard LM-BFF) + else: + for label_id in range(len(model.label_word_list)): + logits.append(prediction_mask_scores[:, model.label_word_list[label_id]].unsqueeze(-1)) + logits = torch.cat(logits, -1) + + # Regression task + if model.config.num_labels == 1: + logsoftmax = nn.LogSoftmax(-1) + logits = logsoftmax(logits) # Log prob of right polarity + else: + logits = model.classifier(sequence_mask_output) + + loss = None + if labels is not None: + if model.config.num_labels == 1: + # Regression task + if model.label_word_list is not None: + labels = torch.stack([1 - (labels.view(-1) - model.lb) / (model.ub - model.lb), (labels.view(-1) - model.lb) / (model.ub - model.lb)], -1) + loss = nn.KLDivLoss(log_target=True)(logits.view(-1, 2), labels) + else: + labels = (labels.float().view(-1) - model.lb) / (model.ub - model.lb) + loss = nn.MSELoss()(logits.view(-1), labels) + else: + # print('logits', logits.shape) + # print('labels', labels.shape) + + # if model.model_args.l2_loss: + # coords = torch.nn.functional.one_hot(labels.squeeze(), model.config.num_labels).float() + # loss = nn.MSELoss()(logits.view(-1, logits.size(-1)), coords) + # else: + loss = nn.CrossEntropyLoss()(logits.view(-1, logits.size(-1)), labels.view(-1)) + # print('loss', loss) + + if hasattr(model, "lr_weight"): + # Linear head + logits = torch.matmul(F.softmax(logits, -1), model.lr_weight) + if hasattr(model, "lr_bias"): + logits += model.lr_bias.unsqueeze(0) + + # if model.model_args.sfc and hasattr(model, "sfc_bias"): + # logits = F.log_softmax(logits, -1) - model.sfc_bias + # if sfc_input_ids is not None: + # logits = F.log_softmax(logits, -1) - icl_sfc_bias + + output = (logits,) + + # if model.model_args.use_task_word and model.num_labels == 1: + # # Regression output + # output = (torch.exp(logits[..., 1].unsqueeze(-1)) * (model.ub - model.lb) + model.lb,) + return ((loss,) + output) if loss is not None else output + + +def convert_opt_model(model: OPTModel, config, num_exclude_layers): + model.model.decoder = EfficientOPTDecoder(config, num_exclude_layers) + return model + + +class BertModelForPromptFinetuning(BertPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + self.bert = BertModel(config) + self.cls = BertOnlyMLMHead(config) + self.classifier = nn.Linear(config.hidden_size, self.num_labels) + + self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def get_model_fn(self): + return self.bert + + def get_lm_head_fn(self): + return self.cls + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels) + + +class RobertaModelForPromptFinetuning(RobertaPreTrainedModel): + def __init__(self, config): + super().__init__(config) + logger.warn("By default for RoBERTa models the input embeddings and the output embeddings " + "are NOT tied!!!!") + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + self.roberta = RobertaModel(config) + self.lm_head = RobertaLMHead(config) + self.classifier = nn.Linear(config.hidden_size, self.num_labels) + + self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def tie_emb(self): + output_embeddings = self.lm_head.decoder + self._tie_or_clone_weights(output_embeddings, self.roberta.get_input_embeddings()) + + def get_model_fn(self): + return self.roberta + + def get_lm_head_fn(self): + return self.lm_head + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels) + + +class OPTModelForPromptFinetuning(OPTForCausalLM): + def __init__(self, config): + super().__init__(config) + logger.warn("By default for OPT models the input embeddings and the output embeddings are tied!!!!") + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + # self.model = OPTModel(config) + # self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False) + # self.classifier = nn.Linear(config.hidden_size, self.num_labels) + # self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def get_model_fn(self): + return self.model + + def get_lm_head_fn(self): + return self.lm_head + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, + labels=None, sfc_input_ids=None, sfc_attention_mask=None, sfc_mask_pos=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, + mask_pos, labels, sfc_input_ids=sfc_input_ids, + sfc_attention_mask=sfc_attention_mask, + sfc_mask_pos=sfc_mask_pos) + + +class GPT2ModelForPromptFinetuning(GPT2LMHeadModel): + def __init__(self, config): + super().__init__(config) + raise NotImplementedError("Need to check if the lm head is properly loaded and whether it is tied.") + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + # self.transformer = GPT2Model(config) + # self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) + self.classifier = nn.Linear(config.hidden_size, self.num_labels) + + self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def get_model_fn(self): + return self.transformer + + def get_lm_head_fn(self): + return self.lm_head + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels) + + +class LlamaModelForPromptFinetuning(LlamaPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + self.model_type = config.model_type + + self.base_model = LlamaForCausalLM.from_pretrained(config._name_or_path, config=config) + + self.model_args = None + self.data_args = None + self.label_word_list = None + self.lb, self.ub = 0.0, 1.0 + self.return_full_softmax = None + + # self.classifier = nn.Linear(config.hidden_size, config.num_labels) + # self.init_weights() + + def get_model_fn(self): + return self.base_model.model.forward + + def get_lm_head_fn(self): + return lambda hidden: self.base_model.lm_head(hidden) + + def forward(self, input_ids=None, attention_mask=None, + token_type_ids=None, mask_pos=None, labels=None, + sfc_input_ids=None, sfc_attention_mask=None, sfc_mask_pos=None): + return model_for_prompting_forward( + self, + input_ids, attention_mask, token_type_ids, + mask_pos, labels, + sfc_input_ids=sfc_input_ids, + sfc_attention_mask=sfc_attention_mask, + sfc_mask_pos=sfc_mask_pos, + ) + + +class EfficientOPTDecoder(OPTDecoder): + def __init__(self, config, num_exclude): + super().__init__(config) + self.num_exclude = num_exclude # number of initial layers to operate with torch.no_grad + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + # embed positions + if attention_mask is None: + attention_mask = torch.ones(inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device) + pos_embeds = self.embed_positions(attention_mask, past_key_values_length) + + attention_mask = self._prepare_decoder_attention_mask( + attention_mask, input_shape, inputs_embeds, past_key_values_length + ) + + if self.project_in is not None: + inputs_embeds = self.project_in(inputs_embeds) + + hidden_states = inputs_embeds + pos_embeds + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + # check if head_mask has a correct number of layers specified if desired + for attn_mask, mask_name in zip([head_mask], ["head_mask"]): + if attn_mask is not None: + if attn_mask.size()[0] != (len(self.layers)): + raise ValueError( + f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" + f" {head_mask.size()[0]}." + ) + + # run first few layers without grad + with torch.no_grad(): + for idx, decoder_layer in enumerate(self.layers[:self.num_exclude]): + + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + # rest of the layers with grad + for idx, decoder_layer in enumerate(self.layers[self.num_exclude:]): + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + if self.final_layer_norm is not None: + hidden_states = self.final_layer_norm(hidden_states) + + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) diff --git a/baselines/loren/model/roberta.py b/baselines/loren/model/roberta.py new file mode 100644 index 0000000..2835e8d --- /dev/null +++ b/baselines/loren/model/roberta.py @@ -0,0 +1,1601 @@ +import math +from typing import List, Optional, Tuple, Union + +import loralib as lora +import torch +import torch.nn as nn +from transformers import BertConfig +from transformers.activations import ACT2FN, gelu +from transformers.modeling_outputs import ( + BaseModelOutputWithPastAndCrossAttentions, + BaseModelOutputWithPoolingAndCrossAttentions, + CausalLMOutputWithCrossAttentions, MaskedLMOutput, + MultipleChoiceModelOutput, QuestionAnsweringModelOutput, + SequenceClassifierOutput, TokenClassifierOutput) +from transformers.modeling_utils import PreTrainedModel +from transformers.pytorch_utils import (apply_chunking_to_forward, + find_pruneable_heads_and_indices, + prune_linear_layer) +from transformers.utils import (add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, logging, + replace_return_docstrings) + +logger = logging.get_logger(__name__) + +_CHECKPOINT_FOR_DOC = "roberta-base" +_CONFIG_FOR_DOC = "RobertaConfig" + +ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST = [ + "roberta-base", + "roberta-large", + "roberta-large-mnli", + "distilroberta-base", + "roberta-base-openai-detector", + "roberta-large-openai-detector", + # See all RoBERTa models at https://huggingface.co/models?filter=roberta +] + + +class RobertaConfig(BertConfig): + r""" + This is the configuration class to store the configuration of a :class:`~transformers.RobertaModel` or a + :class:`~transformers.TFRobertaModel`. It is used to instantiate a RoBERTa model according to the specified + arguments, defining the model architecture. + Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used to control the model + outputs. Read the documentation from :class:`~transformers.PretrainedConfig` for more information. + The :class:`~transformers.RobertaConfig` class directly inherits :class:`~transformers.BertConfig`. It reuses the + same defaults. Please check the parent class for more information. + Examples:: + >>> from transformers import RobertaConfig, RobertaModel + >>> # Initializing a RoBERTa configuration + >>> configuration = RobertaConfig() + >>> # Initializing a model from the configuration + >>> model = RobertaModel(configuration) + >>> # Accessing the model configuration + >>> configuration = model.config + """ + model_type = "roberta" + + def __init__(self, pad_token_id=1, bos_token_id=0, eos_token_id=2, apply_lora=False, + lora_r=None, lora_alpha=None, **kwargs): + """Constructs RobertaConfig.""" + super().__init__(pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + **kwargs) + + self.apply_lora = apply_lora + self.lora_r = lora_r + self.lora_alpha = lora_alpha + + +class RobertaEmbeddings(nn.Module): + """ + Same as BertEmbeddings with a tiny tweak for positional embeddings indexing. + """ + + # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__ + def __init__(self, config): + super().__init__() + self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) + self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) + self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) + + # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load + # any TensorFlow checkpoint file + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + # position_ids (1, len position emb) is contiguous in memory and exported when serialized + self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") + self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) + self.register_buffer( + "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False + ) + + # End copy + self.padding_idx = config.pad_token_id + self.position_embeddings = nn.Embedding( + config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx + ) + + def forward(self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, + past_key_values_length=0): + if position_ids is None: + if input_ids is not None: + # Create the position ids from the input token ids. Any padded tokens remain padded. + position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length) + else: + position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds) + + if input_ids is not None: + input_shape = input_ids.size() + else: + input_shape = inputs_embeds.size()[:-1] + + seq_length = input_shape[1] + + # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs + # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves + # issue #5664 + if token_type_ids is None: + if hasattr(self, "token_type_ids"): + buffered_token_type_ids = self.token_type_ids[:, :seq_length] + buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], + seq_length) + token_type_ids = buffered_token_type_ids_expanded + else: + token_type_ids = torch.zeros(input_shape, + dtype=torch.long, + device=self.position_ids.device) + + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + token_type_embeddings = self.token_type_embeddings(token_type_ids) + + embeddings = inputs_embeds + token_type_embeddings + if self.position_embedding_type == "absolute": + position_embeddings = self.position_embeddings(position_ids) + embeddings += position_embeddings + embeddings = self.LayerNorm(embeddings) + embeddings = self.dropout(embeddings) + return embeddings + + def create_position_ids_from_inputs_embeds(self, inputs_embeds): + """ + We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids. + + Args: + inputs_embeds: torch.Tensor + + Returns: torch.Tensor + """ + input_shape = inputs_embeds.size()[:-1] + sequence_length = input_shape[1] + + position_ids = torch.arange( + self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device + ) + return position_ids.unsqueeze(0).expand(input_shape) + + +# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Roberta +class RobertaSelfAttention(nn.Module): + def __init__(self, config, position_embedding_type=None): + super().__init__() + if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): + raise ValueError( + f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " + f"heads ({config.num_attention_heads})" + ) + + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + if getattr(config, "apply_lora", False): + self.query = lora.Linear(config.hidden_size, self.all_head_size, config.lora_r, lora_alpha=config.lora_alpha) + else: + self.query = nn.Linear(config.hidden_size, self.all_head_size) + + self.key = nn.Linear(config.hidden_size, self.all_head_size) + + if getattr(config, "apply_lora", False): + self.value = lora.Linear(config.hidden_size, self.all_head_size, config.lora_r, lora_alpha=config.lora_alpha) + else: + self.value = nn.Linear(config.hidden_size, self.all_head_size) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.position_embedding_type = position_embedding_type or getattr( + config, "position_embedding_type", "absolute" + ) + if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": + self.max_position_embeddings = config.max_position_embeddings + self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) + + self.is_decoder = config.is_decoder + + def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor: + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + x = x.view(new_x_shape) + return x.permute(0, 2, 1, 3) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + output_attentions: Optional[bool] = False, + output_key_value: Optional[bool] = False, + ) -> Tuple[torch.Tensor]: + mixed_query_layer = self.query(hidden_states) + + # If this is instantiated as a cross-attention module, the keys + # and values come from an encoder; the attention mask needs to be + # such that the encoder's padding tokens are not attended to. + is_cross_attention = encoder_hidden_states is not None + if is_cross_attention and past_key_value is not None: + # reuse k,v, cross_attentions + key_layer = past_key_value[0] + value_layer = past_key_value[1] + attention_mask = encoder_attention_mask + elif is_cross_attention: + key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) + value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) + attention_mask = encoder_attention_mask + elif past_key_value is not None: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + key_layer = torch.cat([past_key_value[0], key_layer], dim=2) + value_layer = torch.cat([past_key_value[1], value_layer], dim=2) + else: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + + query_layer = self.transpose_for_scores(mixed_query_layer) + + use_cache = past_key_value is not None + if self.is_decoder or output_key_value: + # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. + # Further calls to cross_attention layer can then reuse all cross-attention + # key/value_states (first "if" case) + # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of + # all previous decoder key/value_states. Further calls to uni-directional self-attention + # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) + # if encoder bi-directional self-attention `past_key_value` is always `None` + past_key_value = (key_layer, value_layer) + + # Take the dot product between "query" and "key" to get the raw attention scores. + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + + if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": + query_length, key_length = query_layer.shape[2], key_layer.shape[2] + if use_cache: + position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view( + -1, 1 + ) + else: + position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) + position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1) + distance = position_ids_l - position_ids_r + + positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) + positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility + + if self.position_embedding_type == "relative_key": + relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) + attention_scores = attention_scores + relative_position_scores + elif self.position_embedding_type == "relative_key_query": + relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) + relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) + attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key + + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + if attention_mask is not None: + # Apply the attention mask is (precomputed for all layers in RobertaModel forward() function) + attention_scores = attention_scores + attention_mask + + # Normalize the attention scores to probabilities. + attention_probs = nn.functional.softmax(attention_scores, dim=-1) + + # This is actually dropping out entire tokens to attend to, which might + # seem a bit unusual, but is taken from the original Transformer paper. + attention_probs = self.dropout(attention_probs) + + # Mask heads if we want to + if head_mask is not None: + attention_probs = attention_probs * head_mask + + context_layer = torch.matmul(attention_probs, value_layer) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) + + if self.is_decoder or output_key_value: + outputs = outputs + (past_key_value,) + return outputs + + +# Copied from transformers.models.bert.modeling_bert.BertSelfOutput +class RobertaSelfOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Roberta +class RobertaAttention(nn.Module): + def __init__(self, config, position_embedding_type=None): + super().__init__() + self.self = RobertaSelfAttention(config, position_embedding_type=position_embedding_type) + self.output = RobertaSelfOutput(config) + self.pruned_heads = set() + + def prune_heads(self, heads): + if len(heads) == 0: + return + heads, index = find_pruneable_heads_and_indices( + heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads + ) + + # Prune linear layers + self.self.query = prune_linear_layer(self.self.query, index) + self.self.key = prune_linear_layer(self.self.key, index) + self.self.value = prune_linear_layer(self.self.value, index) + self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) + + # Update hyper params and store pruned heads + self.self.num_attention_heads = self.self.num_attention_heads - len(heads) + self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads + self.pruned_heads = self.pruned_heads.union(heads) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + output_attentions: Optional[bool] = False, + output_key_value: Optional[bool] = False, + ) -> Tuple[torch.Tensor]: + self_outputs = self.self( + hidden_states, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + output_key_value=output_key_value + ) + attention_output = self.output(self_outputs[0], hidden_states) + outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them + return outputs + + +# Copied from transformers.models.bert.modeling_bert.BertIntermediate +class RobertaIntermediate(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertOutput +class RobertaOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Roberta +class RobertaLayer(nn.Module): + def __init__(self, config): + super().__init__() + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = RobertaAttention(config) + self.is_decoder = config.is_decoder + self.add_cross_attention = config.add_cross_attention + if self.add_cross_attention: + if not self.is_decoder: + raise ValueError(f"{self} should be used as a decoder model if cross attention is added") + self.crossattention = RobertaAttention(config, position_embedding_type="absolute") + self.intermediate = RobertaIntermediate(config) + self.output = RobertaOutput(config) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + output_attentions: Optional[bool] = False, + output_key_value: Optional[bool] = False, + ) -> Tuple[torch.Tensor]: + # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 + self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None + self_attention_outputs = self.attention( + hidden_states, + attention_mask, + head_mask, + output_attentions=output_attentions, + past_key_value=self_attn_past_key_value, + output_key_value=output_key_value + ) + attention_output = self_attention_outputs[0] + + # if decoder, the last output is tuple of self-attn cache + if self.is_decoder or output_key_value: + outputs = self_attention_outputs[1:-1] + present_key_value = self_attention_outputs[-1] + else: + outputs = self_attention_outputs[1:] # add self attentions if we output attention weights + + cross_attn_present_key_value = None + if self.is_decoder and encoder_hidden_states is not None: + if not hasattr(self, "crossattention"): + raise ValueError( + f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers" + " by setting `config.add_cross_attention=True`" + ) + + # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple + cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None + cross_attention_outputs = self.crossattention( + attention_output, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + cross_attn_past_key_value, + output_attentions, + ) + attention_output = cross_attention_outputs[0] + outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights + + # add cross-attn cache to positions 3,4 of present_key_value tuple + cross_attn_present_key_value = cross_attention_outputs[-1] + present_key_value = present_key_value + cross_attn_present_key_value + + layer_output = apply_chunking_to_forward( + self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output + ) + outputs = (layer_output,) + outputs + + # if decoder, return the attn key/values as the last output + if self.is_decoder or output_key_value: + outputs = outputs + (present_key_value,) + + return outputs + + def feed_forward_chunk(self, attention_output): + intermediate_output = self.intermediate(attention_output) + layer_output = self.output(intermediate_output, attention_output) + return layer_output + + +# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Roberta +class RobertaEncoder(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.layer = nn.ModuleList([RobertaLayer(config) for _ in range(config.num_hidden_layers)]) + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = False, + output_hidden_states: Optional[bool] = False, + return_dict: Optional[bool] = True, + ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]: + all_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + next_decoder_cache = () if use_cache else None + for i, layer_module in enumerate(self.layer): + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + layer_head_mask = head_mask[i] if head_mask is not None else None + past_key_value = past_key_values[i] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs, past_key_value, output_attentions) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(layer_module), + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + ) + else: + layer_outputs = layer_module( + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + output_key_value=use_cache + ) + + hidden_states = layer_outputs[0] + if use_cache: + next_decoder_cache += (layer_outputs[-1],) + if output_attentions: + all_self_attentions = all_self_attentions + (layer_outputs[1],) + if self.config.add_cross_attention: + all_cross_attentions = all_cross_attentions + (layer_outputs[2],) + + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + if not return_dict: + return tuple( + v + for v in [ + hidden_states, + next_decoder_cache, + all_hidden_states, + all_self_attentions, + all_cross_attentions, + ] + if v is not None + ) + return BaseModelOutputWithPastAndCrossAttentions( + last_hidden_state=hidden_states, + past_key_values=next_decoder_cache, + hidden_states=all_hidden_states, + attentions=all_self_attentions, + cross_attentions=all_cross_attentions, + ) + + +# Copied from transformers.models.bert.modeling_bert.BertPooler +class RobertaPooler(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.activation = nn.Tanh() + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + # We "pool" the model by simply taking the hidden state corresponding + # to the first token. + first_token_tensor = hidden_states[:, 0] + pooled_output = self.dense(first_token_tensor) + pooled_output = self.activation(pooled_output) + return pooled_output + + +class RobertaPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = RobertaConfig + base_model_prefix = "roberta" + supports_gradient_checkpointing = True + _no_split_modules = [] + + # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights + def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, nn.Linear): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, RobertaEncoder): + module.gradient_checkpointing = value + + def update_keys_to_ignore(self, config, del_keys_to_ignore): + """Remove some keys from ignore list""" + if not config.tie_word_embeddings: + # must make a new list, or the class variable gets modified! + self._keys_to_ignore_on_save = [k for k in self._keys_to_ignore_on_save if k not in del_keys_to_ignore] + self._keys_to_ignore_on_load_missing = [ + k for k in self._keys_to_ignore_on_load_missing if k not in del_keys_to_ignore + ] + + +ROBERTA_START_DOCSTRING = r""" + + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`RobertaConfig`]): Model configuration class with all the parameters of the + model. Initializing with a config file does not load the weights associated with the model, only the + configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + +ROBERTA_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `({0})`): + Indices of input sequence tokens in the vocabulary. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*): + Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`: + + - 0 corresponds to a *sentence A* token, + - 1 corresponds to a *sentence B* token. + This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value + >= 2. All the value in this tensor should be always < type_vocab_size. + + [What are token type IDs?](../glossary#token-type-ids) + position_ids (`torch.LongTensor` of shape `({0})`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.max_position_embeddings - 1]`. + + [What are position IDs?](../glossary#position-ids) + head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): + Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +@add_start_docstrings( + "The bare RoBERTa Model transformer outputting raw hidden-states without any specific head on top.", + ROBERTA_START_DOCSTRING, +) +class RobertaModel(RobertaPreTrainedModel): + """ + + The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of + cross-attention is added between the self-attention layers, following the architecture described in *Attention is + all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz + Kaiser and Illia Polosukhin. + + To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set + to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and + `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass. + + .. _*Attention is all you need*: https://arxiv.org/abs/1706.03762 + + """ + + _keys_to_ignore_on_load_missing = [r"position_ids"] + + # Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with Bert->Roberta + def __init__(self, config, add_pooling_layer=True): + super().__init__(config) + self.config = config + + self.embeddings = RobertaEmbeddings(config) + self.encoder = RobertaEncoder(config) + + self.pooler = RobertaPooler(config) if add_pooling_layer else None + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embeddings.word_embeddings + + def set_input_embeddings(self, value): + self.embeddings.word_embeddings = value + + def _prune_heads(self, heads_to_prune): + """ + Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base + class PreTrainedModel + """ + for layer, heads in heads_to_prune.items(): + self.encoder.layer[layer].attention.prune_heads(heads) + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=BaseModelOutputWithPoolingAndCrossAttentions, + config_class=_CONFIG_FOR_DOC, + ) + # Copied from transformers.models.bert.modeling_bert.BertModel.forward + def forward( + self, + input_ids: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + token_type_ids: Optional[torch.Tensor] = None, + position_ids: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + inputs_embeds: Optional[torch.Tensor] = None, + encoder_hidden_states: Optional[torch.Tensor] = None, + encoder_attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]: + r""" + encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + """ + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # if self.config.is_decoder: + # use_cache = use_cache if use_cache is not None else self.config.use_cache + # else: + # use_cache = False + + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + batch_size, seq_length = input_shape + device = input_ids.device if input_ids is not None else inputs_embeds.device + + # past_key_values_length + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + + if attention_mask is None: + attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) + + if token_type_ids is None: + if hasattr(self.embeddings, "token_type_ids"): + buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length] + buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length) + token_type_ids = buffered_token_type_ids_expanded + else: + token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) + + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape) + + # If a 2D or 3D attention mask is provided for the cross-attention + # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] + if self.config.is_decoder and encoder_hidden_states is not None: + encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() + encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) + if encoder_attention_mask is None: + encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) + encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) + else: + encoder_extended_attention_mask = None + + # Prepare head mask if needed + # 1.0 in head_mask indicate we keep the head + # attention_probs has shape bsz x n_heads x N x N + # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] + # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] + head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) + + embedding_output = self.embeddings( + input_ids=input_ids, + position_ids=position_ids, + token_type_ids=token_type_ids, + inputs_embeds=inputs_embeds, + past_key_values_length=past_key_values_length, + ) + encoder_outputs = self.encoder( + embedding_output, + attention_mask=extended_attention_mask, + head_mask=head_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_extended_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + sequence_output = encoder_outputs[0] + pooled_output = self.pooler(sequence_output) if self.pooler is not None else None + + if not return_dict: + return (sequence_output, pooled_output) + encoder_outputs[1:] + + return BaseModelOutputWithPoolingAndCrossAttentions( + last_hidden_state=sequence_output, + pooler_output=pooled_output, + past_key_values=encoder_outputs.past_key_values, + hidden_states=encoder_outputs.hidden_states, + attentions=encoder_outputs.attentions, + cross_attentions=encoder_outputs.cross_attentions, + ) + + +@add_start_docstrings( + """RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.""", ROBERTA_START_DOCSTRING +) +class RobertaForCausalLM(RobertaPreTrainedModel): + _keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_unexpected = [r"pooler"] + + def __init__(self, config): + super().__init__(config) + + if not config.is_decoder: + logger.warning("If you want to use `RobertaLMHeadModel` as a standalone, add `is_decoder=True.`") + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.lm_head = RobertaLMHead(config) + + # The LM head weights require special treatment only when they are tied with the word embeddings + self.update_keys_to_ignore(config, ["lm_head.decoder.weight"]) + + # Initialize weights and apply final processing + self.post_init() + + def get_output_embeddings(self): + return self.lm_head.decoder + + def set_output_embeddings(self, new_embeddings): + self.lm_head.decoder = new_embeddings + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + past_key_values: Tuple[Tuple[torch.FloatTensor]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]: + r""" + encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in + `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are + ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` + past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, RobertaForCausalLM, AutoConfig + >>> import torch + + >>> tokenizer = AutoTokenizer.from_pretrained("roberta-base") + >>> config = AutoConfig.from_pretrained("roberta-base") + >>> config.is_decoder = True + >>> model = RobertaForCausalLM.from_pretrained("roberta-base", config=config) + + >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + >>> outputs = model(**inputs) + + >>> prediction_logits = outputs.logits + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + if labels is not None: + use_cache = False + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + sequence_output = outputs[0] + prediction_scores = self.lm_head(sequence_output) + + lm_loss = None + if labels is not None: + # we are doing next-token prediction; shift prediction scores and input ids by one + shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous() + labels = labels[:, 1:].contiguous() + loss_fct = nn.CrossEntropyLoss() + lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) + + if not return_dict: + output = (prediction_scores,) + outputs[2:] + return ((lm_loss,) + output) if lm_loss is not None else output + + return CausalLMOutputWithCrossAttentions( + loss=lm_loss, + logits=prediction_scores, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + cross_attentions=outputs.cross_attentions, + ) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs): + input_shape = input_ids.shape + # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly + if attention_mask is None: + attention_mask = input_ids.new_ones(input_shape) + + # cut decoder_input_ids if past is used + if past_key_values is not None: + input_ids = input_ids[:, -1:] + + return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values} + + def _reorder_cache(self, past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) + return reordered_past + + +@add_start_docstrings("""RoBERTa Model with a `language modeling` head on top.""", ROBERTA_START_DOCSTRING) +class RobertaForMaskedLM(RobertaPreTrainedModel): + _keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_unexpected = [r"pooler"] + + def __init__(self, config): + super().__init__(config) + + if config.is_decoder: + logger.warning( + "If you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for " + "bi-directional self-attention." + ) + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.lm_head = RobertaLMHead(config) + + # The LM head weights require special treatment only when they are tied with the word embeddings + self.update_keys_to_ignore(config, ["lm_head.decoder.weight"]) + + # Initialize weights and apply final processing + self.post_init() + + def get_output_embeddings(self): + return self.lm_head.decoder + + def set_output_embeddings(self, new_embeddings): + self.lm_head.decoder = new_embeddings + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=MaskedLMOutput, + config_class=_CONFIG_FOR_DOC, + mask="", + expected_output="' Paris'", + expected_loss=0.1, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., + config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the + loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` + kwargs (`Dict[str, any]`, optional, defaults to *{}*): + Used to hide legacy arguments that have been deprecated. + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + sequence_output = outputs[0] + prediction_scores = self.lm_head(sequence_output) + + masked_lm_loss = None + if labels is not None: + loss_fct = nn.CrossEntropyLoss() + masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) + + if not return_dict: + output = (prediction_scores,) + outputs[2:] + return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output + + return MaskedLMOutput( + loss=masked_lm_loss, + logits=prediction_scores, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class RobertaLMHead(nn.Module): + """Roberta Head for masked language modeling.""" + + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + self.decoder = nn.Linear(config.hidden_size, config.vocab_size) + self.bias = nn.Parameter(torch.zeros(config.vocab_size)) + self.decoder.bias = self.bias + + def forward(self, features, **kwargs): + x = self.dense(features) + x = gelu(x) + x = self.layer_norm(x) + + # project back to size of vocabulary with bias + x = self.decoder(x) + + return x + + def _tie_weights(self): + # To tie those two weights if they get disconnected (on TPU or when the bias is resized) + # For accelerate compatibility and to not break backward compatibility + if self.decoder.bias.device.type == "meta": + self.decoder.bias = self.bias + else: + self.bias = self.decoder.bias + + +@add_start_docstrings( + """ + RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the + pooled output) e.g. for GLUE tasks. + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForSequenceClassification(RobertaPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + self.config = config + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.classifier = RobertaClassificationHead(config) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint="cardiffnlp/twitter-roberta-base-emotion", + output_type=SequenceClassifierOutput, + config_class=_CONFIG_FOR_DOC, + expected_output="'optimism'", + expected_loss=0.08, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + sequence_output = outputs[0] + logits = self.classifier(sequence_output) + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = nn.MSELoss() + if self.num_labels == 1: + loss = loss_fct(logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = nn.CrossEntropyLoss() + loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = nn.BCEWithLogitsLoss() + loss = loss_fct(logits, labels) + + if not return_dict: + output = (logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +@add_start_docstrings( + """ + Roberta Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a + softmax) e.g. for RocStories/SWAG tasks. + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForMultipleChoice(RobertaPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + + self.roberta = RobertaModel(config) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + self.classifier = nn.Linear(config.hidden_size, 1) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=MultipleChoiceModelOutput, + config_class=_CONFIG_FOR_DOC, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., + num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See + `input_ids` above) + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1] + + flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None + flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None + flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None + flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None + flat_inputs_embeds = ( + inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1)) + if inputs_embeds is not None + else None + ) + + outputs = self.roberta( + flat_input_ids, + position_ids=flat_position_ids, + token_type_ids=flat_token_type_ids, + attention_mask=flat_attention_mask, + head_mask=head_mask, + inputs_embeds=flat_inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + pooled_output = outputs[1] + + pooled_output = self.dropout(pooled_output) + logits = self.classifier(pooled_output) + reshaped_logits = logits.view(-1, num_choices) + + loss = None + if labels is not None: + loss_fct = nn.CrossEntropyLoss() + loss = loss_fct(reshaped_logits, labels) + + if not return_dict: + output = (reshaped_logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return MultipleChoiceModelOutput( + loss=loss, + logits=reshaped_logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +@add_start_docstrings( + """ + Roberta Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for + Named-Entity-Recognition (NER) tasks. + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForTokenClassification(RobertaPreTrainedModel): + _keys_to_ignore_on_load_unexpected = [r"pooler"] + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + + self.roberta = RobertaModel(config, add_pooling_layer=False) + classifier_dropout = ( + config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob + ) + self.dropout = nn.Dropout(classifier_dropout) + self.classifier = nn.Linear(config.hidden_size, config.num_labels) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint="Jean-Baptiste/roberta-large-ner-english", + output_type=TokenClassifierOutput, + config_class=_CONFIG_FOR_DOC, + expected_output="['O', 'ORG', 'ORG', 'O', 'O', 'O', 'O', 'O', 'LOC', 'O', 'LOC', 'LOC']", + expected_loss=0.01, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + sequence_output = outputs[0] + + sequence_output = self.dropout(sequence_output) + logits = self.classifier(sequence_output) + + loss = None + if labels is not None: + loss_fct = nn.CrossEntropyLoss() + loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return TokenClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class RobertaClassificationHead(nn.Module): + """Head for sentence-level classification tasks.""" + + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + classifier_dropout = ( + config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob + ) + self.dropout = nn.Dropout(classifier_dropout) + self.out_proj = nn.Linear(config.hidden_size, config.num_labels) + + def forward(self, features, **kwargs): + x = features[:, 0, :] # take token (equiv. to [CLS]) + x = self.dropout(x) + x = self.dense(x) + x = torch.tanh(x) + x = self.dropout(x) + x = self.out_proj(x) + return x + + +@add_start_docstrings( + """ + Roberta Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear + layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForQuestionAnswering(RobertaPreTrainedModel): + _keys_to_ignore_on_load_unexpected = [r"pooler"] + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint="deepset/roberta-base-squad2", + output_type=QuestionAnsweringModelOutput, + config_class=_CONFIG_FOR_DOC, + expected_output="' puppet'", + expected_loss=0.86, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + start_positions: Optional[torch.LongTensor] = None, + end_positions: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]: + r""" + start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + sequence_output = outputs[0] + + logits = self.qa_outputs(sequence_output) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0): + """ + Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols + are ignored. This is modified from fairseq's `utils.make_positions`. + + Args: + x: torch.Tensor x: + + Returns: torch.Tensor + """ + # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA. + mask = input_ids.ne(padding_idx).int() + incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask + return incremental_indices.long() + padding_idx diff --git a/baselines/loren/native.py b/baselines/loren/native.py new file mode 100644 index 0000000..89c3939 --- /dev/null +++ b/baselines/loren/native.py @@ -0,0 +1,71 @@ +"""Run the original entry point with shared local assets. No optimizer rewrite.""" +import argparse +from datetime import datetime,timezone +import json +import os +from pathlib import Path +import runpy +import sys + +HERE=Path(__file__).resolve().parent +ROOT=HERE.parents[1] +sys.path.insert(0,str(ROOT/'src')) +from experiments_codebase.paths import paths,model_path,save + +def main(): + p=argparse.ArgumentParser(description=__doc__,add_help=False) + p.add_argument('--asset-model',default='facebook/opt-1.3b') + p.add_argument('--asset-task',choices=['sst2','drop'],default='sst2') + p.add_argument('--asset-out',type=Path) + args,rest=p.parse_known_args();method=HERE.name + roots=paths();os.environ.setdefault('WANDB_MODE','disabled');os.environ['WANDB_DIR']=str(roots['results']/'wandb') + out=(args.asset_out or roots['results']/f'native_{method}_{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}').resolve() + if not out.is_relative_to(roots['results'].resolve()):raise ValueError('Output must be under shared results') + # Both local datasets are supplied through the HF Dataset API expected by authors. + import datasets + original=datasets.load_dataset + def local_dataset(name,*pos,**kw): + config=pos[0] if pos else kw.get('name') + alias='sst2' if (name in ('glue','nyu-mll/glue') and config=='sst2') or name=='sst2' else ('drop' if name in ('drop','ucinlp/drop') else None) + if alias: + ds=datasets.load_from_disk(str(roots['data']/alias)) + split=kw.get('split');return ds[split] if split else ds + return original(name,*pos,**kw) + datasets.load_dataset=local_dataset + model=str(model_path(args.asset_model)) + if method=='loren': + if args.asset_task=='drop':raise ValueError('Official LOREN has no DROP task; use run_compatible.py with the modern group for a labeled task extension') + if 'Qwen' in args.asset_model:raise ValueError('Official LOREN has no Qwen model branch; use the modern compatibility entry') + entry=HERE/'main.py' + defaults=['--model_name',model,'--task',args.asset_task,'--algorithm','LOREN','--results',str(out),'--full_parameter'] + else: + work=HERE/('zo-bench' if method=='agzo' else 'large_models') + entry=work/('run_lozo.py' if method=='lozo' else 'run.py') + task='SST2' if args.asset_task=='sst2' else 'DROP' + defaults=['--model_name',model,'--task_name',task,'--output_dir',str(out),'--trainer',{'mezo':'zo','lozo':'LOZO','agzo':'agzo'}[method], + '--report_to','none','--train_set_seed','42','--train_as_classification',str(task=='SST2'),'--lr_scheduler_type','constant'] + defaults+=['--result_file',str(out/'result.json')] + # User's original HF/author flags appear last and override wrapper defaults. + if '--help' not in rest: + out.mkdir(parents=True,exist_ok=False) + save(out/'launch.json',dict(method=method,entry=str(entry),argv=defaults+rest,executable=sys.executable,adapter='Local assets and paths only; original Trainer/optimizer',pid=os.getpid())) + sys.path.insert(0,str(entry.parent));os.chdir(out if out.exists() else HERE) + sys.argv=[str(entry),*defaults,*rest] + if method=='agzo': + import torch + if torch.cuda.is_available() and not hasattr(torch,'npu'): + # The author's NPU helper has incomplete CUDA branches. Only device + # plumbing is adapted; trainer.py and AGZO numerical methods are intact. + import npu_compat as devices + devices.device_count=torch.cuda.device_count + devices.mem_get_info=torch.cuda.mem_get_info + devices.get_active_device_info=lambda:('cuda',torch.cuda.current_device(),torch.cuda.get_device_properties(0).total_memory/2**30,torch.cuda.get_device_name()) + devices.safe_set_device=lambda index:(torch.cuda.set_device(int(index or 0)) or int(index or 0),torch.cuda.device_count()) + devices.to_device=lambda tensor:tensor.cuda() + source=entry.read_text().replace('torch.npu.manual_seed_all(seed)','torch.cuda.manual_seed_all(seed)').replace('torch.npu.device_count()','torch.cuda.device_count()') + if out.exists():save(out/'compatibility_changes.json',{'scope':'CUDA device plumbing only','source_modified_on_disk':False,'numerical_optimizer_modified':False,'changes':['NPU seed -> CUDA seed','NPU device count -> CUDA count','device helper memory/info/count/set/to_device CUDA callbacks']}) + exec(compile(source,str(entry),'exec'),dict(__name__='__main__',__file__=str(entry))) + return + runpy.run_path(str(entry),run_name='__main__') + +if __name__=='__main__':main() diff --git a/baselines/loren/pyproject.toml b/baselines/loren/pyproject.toml new file mode 100644 index 0000000..a15fa31 --- /dev/null +++ b/baselines/loren/pyproject.toml @@ -0,0 +1,14 @@ +[project] +name = "official-loren-experiment" +version = "0.1.0" +requires-python = ">=3.11,<3.12" +dependencies = ["torch==2.13.0", "loguru==0.7.3", "setuptools==80.9.0", "numpy==1.26.4", "matplotlib==3.10.7", "psutil==7.1.3", "scikit-learn==1.7.2", "sentencepiece==0.2.1", "wandb==0.23.1", "rouge==1.0.1", "nltk==3.9.2", "einops==0.8.1", "lightning==2.5.6", "torchmetrics==1.8.2", "loralib==0.1.2", "tensorboard==2.20.0", "tensorboardX==2.6.4", "peft==0.13.2", "termcolor==3.2.0", "bitsandbytes==0.48.2"] + +[dependency-groups] +native = ["transformers==4.44.2", "datasets==2.21.0", "pyarrow==17.0.0", "accelerate==1.12.0", "huggingface-hub==0.36.0"] +modern = ["transformers==4.57.1", "datasets==3.6.0", "pyarrow==20.0.0", "accelerate==1.12.0", "huggingface-hub==0.36.0"] + +[tool.uv] +package = false +default-groups = ["native"] +conflicts = [[{group="native"}, {group="modern"}]] diff --git a/baselines/loren/requirements.txt b/baselines/loren/requirements.txt new file mode 100644 index 0000000..79167cc --- /dev/null +++ b/baselines/loren/requirements.txt @@ -0,0 +1,17 @@ +numpy +datasets +lightning +matplotlib +scikit-learn +scipy +torch +torchmetrics +transformers +torchvision +loralib +wandb +tensorboard +tensorboardX +peft +termcolor +bitsandbytes \ No newline at end of file diff --git a/baselines/loren/run_compatible.py b/baselines/loren/run_compatible.py new file mode 100644 index 0000000..561d3e6 --- /dev/null +++ b/baselines/loren/run_compatible.py @@ -0,0 +1,7 @@ +"""Modern task adapter calling pinned official numerical methods; not the original Trainer.""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'src')) +from experiments_codebase.runner import main +if __name__ == '__main__': + main(forced_method='loren') diff --git a/baselines/loren/trainer/__init__.py b/baselines/loren/trainer/__init__.py new file mode 100644 index 0000000..158be87 --- /dev/null +++ b/baselines/loren/trainer/__init__.py @@ -0,0 +1,5 @@ +from .train_loop import finetune_ZO +from .train_loop import finetune_FO + + +__all__ = ['finetune_ZO', 'finetune_FO'] diff --git a/baselines/loren/trainer/train_loop.py b/baselines/loren/trainer/train_loop.py new file mode 100644 index 0000000..512edaa --- /dev/null +++ b/baselines/loren/trainer/train_loop.py @@ -0,0 +1,219 @@ +import numpy as np +import torch +import lightning as L +from lightning.pytorch import Trainer + +from common.logging import logger as logging + + +def reset_log_dict(log_dict): + log_dict['train_loss'] = 0.0 + log_dict['val_loss'] = 0.0 + log_dict['val_acc'] = 0.0 + log_dict['time'] = 0.0 + #log_dict['memory'] = 0.0 + +def finetune_FO(args, + device: torch.device, + dm: L.LightningDataModule, + transformer: L.LightningModule, tb_writer=None): + train_dataloader = dm.train_dataloader() + val_dataloader = dm.val_dataloader() + + log_dict = {} + + if args.bf16: + transformer.to(torch.bfloat16) + + model = transformer.model.to(device) + + transformer.configure_params() + optimizer = transformer.configure_optimizers() + + transformer.model.eval() + if args.early_stopping: + best_val_acc = 0 + patience_counter = 0 + + global_step = 0 + + for epoch in range(args.epochs): + log_dict['epoch'] = epoch + + if (epoch + 1) % args.eval_every == 0: + # validation loop + reset_log_dict(log_dict) + val_loss_sums, val_correct, total_val_samples = [], 0, 0 + for batch in val_dataloader: + b = {k: v.to(device) for k, v in batch.items()} + + loss_sum, correct, total_samples = transformer.forward_ZO_val(b) + val_loss_sums.append(loss_sum.item()) + val_correct += correct + total_val_samples += total_samples + + val_loss_mean = np.sum(val_loss_sums) / total_val_samples + val_acc = val_correct / total_val_samples * 100.0 + + log_dict['val_loss'] = val_loss_mean + log_dict['val_acc'] = val_acc + + if args.early_stopping: + if val_acc >= best_val_acc: + best_val_acc = val_acc + patience_counter = 0 + else: + patience_counter += 1 + + log_dict["best_val_acc"] = best_val_acc + + tb_writer.log_metrics(log_dict, step=global_step) + + if args.early_stopping and patience_counter >= args.patience: + logging.info( + f"Early stopping at epoch {epoch+1}. Best validation accuracy: {best_val_acc}" + ) + break + + # training loop + transformer.model.train() + train_loss = 0.0 + for batch_idx, batch in enumerate(train_dataloader): + reset_log_dict(log_dict) + b = {k: v.to(device) for k, v in batch.items()} + + optimizer.zero_grad() + outputs = model(**b) + loss = outputs[0] + loss.backward() + alloc_mem = transformer.measure_memory_usage() + optimizer.step() + + train_loss += loss.item() + global_step += 1 + + log_dict['train_loss'] = loss.item() + log_dict['time'] = 0.0 # or measure if you like + + if tb_writer: + tb_writer.log_metrics(log_dict, step=global_step) + logging.info(f"[{epoch + 1:}] val_loss: {val_loss_mean:.5f}, val_acc: {val_acc:.3f}, " + f"mem: {alloc_mem:.5f}") + avg_train_loss = train_loss / len(train_dataloader) + logging.info(f'Avg. train loss: {avg_train_loss:.5f}') + + if args.logging == "tensorboard" and tb_writer is not None: + tb_writer.close() + +def finetune_ZO(args, + device: torch.device, + dm: L.LightningDataModule, + transformer: L.LightningModule, tb_writer=None): + train_dataloader = dm.train_dataloader() + val_dataloader = dm.val_dataloader() + + log_dict = {} + kwargs = {'log': log_dict} + + if args.bf16: + transformer.to(torch.bfloat16) + + model = transformer.model.to(device) + + # Algorithm-specific routines + if args.algorithm == 'ZOSVRG': + total_batches = len(train_dataloader) + fb_train_loader = dm.train_full_dataloader() + kwargs['full_batch_size'] = total_batches + elif args.algorithm == 'ZOAdam': + if args.low_bit_adam == 8: + import bitsandbytes as bnb + optimizer = bnb.optim.Adam8bit(model.parameters(), + lr=args.lr, + eps=args.eps, + weight_decay=0) + else: + optimizer = torch.optim.Adam(model.parameters(), lr=args.lr, eps=args.eps) + kwargs['optimizer'] = optimizer + + transformer.configure_params() + + transformer.model.eval() + if args.early_stopping: + best_val_acc = 0 + patience_counter = 0 + + for epoch in range(args.epochs): + log_dict['epoch'] = epoch + + if (epoch + 1) % args.eval_every == 0: + # validation loop + reset_log_dict(log_dict) + val_loss_sums, val_correct, total_val_samples = [], 0, 0 + for batch in val_dataloader: + b = {k: v.to(device) for k, v in batch.items()} + + loss_sum, correct, total_samples = transformer.forward_ZO_val(b) + val_loss_sums.append(loss_sum.item()) + val_correct += correct + total_val_samples += total_samples + + val_loss_mean = np.sum(val_loss_sums) / total_val_samples + val_acc = val_correct / total_val_samples * 100.0 + + log_dict['val_loss'] = val_loss_mean + log_dict['val_acc'] = val_acc + + if args.early_stopping: + if val_acc >= best_val_acc: + best_val_acc = val_acc + patience_counter = 0 + else: + patience_counter += 1 + + log_dict["best_val_acc"] = best_val_acc + + tb_writer.log_metrics(log_dict, step=transformer.state.global_training_steps) + + if args.early_stopping and patience_counter >= args.patience: + logging.info( + f"Early stopping at epoch {epoch+1}. Best validation accuracy: {best_val_acc}" + ) + break + + # training loop + transformer.model.train() + train_loss = 0.0 + + for batch_idx, batch in enumerate(train_dataloader): + reset_log_dict(log_dict) + + if args.algorithm == 'ZOSVRG': + curr_iter = epoch * total_batches + batch_idx + kwargs['curr_iter'] = curr_iter + + if (curr_iter % args.q) == 0: + batch = next(iter(fb_train_loader)) + kwargs['is_full_batch'] = True + else: + kwargs['is_full_batch'] = False + + b = {k: v.to(device) for k, v in batch.items()} + transformer.training_step(model, b, tb_writer=tb_writer, **kwargs) + + if kwargs.get('is_full_batch', False): + train_loss += log_dict.get('fb_train_loss', 0.0) + else: + train_loss += log_dict.get('train_loss', 0.0) + + if tb_writer: + tb_writer.log_metrics(log_dict, step=transformer.state.global_training_steps) + + alloc_mem = transformer.measure_memory_usage() + logging.info(f"[{epoch + 1:}] val_loss: {val_loss_mean:.5f}, val_acc: {val_acc:.3f}, " + f"mem: {alloc_mem:.5f}") + train_loss /= len(train_dataloader) + logging.info(f'Avg. train loss: {train_loss:.5f}') + + if args.logging == "tensorboard" and tb_writer is not None: + tb_writer.close() diff --git a/baselines/loren/uv.lock b/baselines/loren/uv.lock new file mode 100644 index 0000000..8a8b31b --- /dev/null +++ b/baselines/loren/uv.lock @@ -0,0 +1,1941 @@ +version = 1 +revision = 3 +requires-python = "==3.11.*" +resolution-markers = [ + "sys_platform == 'linux' and extra != 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native'", + "sys_platform == 'win32' and extra != 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native'", + "sys_platform == 'emscripten' and extra != 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32' and extra != 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native'", + "sys_platform == 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform == 'win32' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform == 'emscripten' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform == 'linux' and extra != 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform != 'linux' and extra != 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", +] +conflicts = [[ + { package = "official-loren-experiment", group = "modern" }, + { package = "official-loren-experiment", group = "native" }, +]] + +[[package]] +name = "absl-py" +version = "2.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/1d/58e2b5a6e4d703ccb2a029943d665974cb3d5a4fb2b3e3675dd03a9df10e/absl_py-2.5.1.tar.gz", hash = "sha256:286e71c82c1a38e75bbcf185f9b37d0305ad7786535107cb49bf4df9ff2e1f95", size = 118387, upload-time = "2026-10-09T08:38:58.037Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b3/7d/01e62f59e4166af1be6238d9f2b7f3453630c51b8044b412d05b5606532a/absl_py-2.5.1-py3-none-any.whl", hash = "sha256:721200f2f0e9960f2ca9dc3a2a706b201f5f75d812c158f059cbbe29eeafbdb8", size = 137673, upload-time = "2026-10-09T08:38:56.629Z" }, +] + +[[package]] +name = "accelerate" +version = "1.12.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyyaml" }, + { name = "safetensors" }, + { name = "torch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4a/8e/ac2a9566747a93f8be36ee08532eb0160558b07630a081a6056a9f89bf1d/accelerate-1.12.0.tar.gz", hash = "sha256:70988c352feb481887077d2ab845125024b2a137a5090d6d7a32b57d03a45df6", size = 398399, upload-time = "2025-11-21T11:27:46.973Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/d2/c581486aa6c4fbd7394c23c47b83fa1a919d34194e16944241daf9e762dd/accelerate-1.12.0-py3-none-any.whl", hash = "sha256:3e2091cd341423207e2f084a6654b1efcd250dc326f2a37d6dde446e07cabb11", size = 380935, upload-time = "2025-11-21T11:27:44.522Z" }, +] + +[[package]] +name = "aiohappyeyeballs" +version = "2.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/f4/eec0465c2f67b2664688d0240b3212d5196fd89e741df67ddb81f8d35658/aiohappyeyeballs-2.7.1.tar.gz", hash = "sha256:065665c041c42a5938ed220bdcd7230f22527fbec085e1853d2402c8a3615d9d", size = 24757, upload-time = "2026-07-01T17:11:55.501Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/43/1947f06babed6b3f1d7f38b0c767f52df66bfb2bc10b468c4a7de9eceff2/aiohappyeyeballs-2.7.1-py3-none-any.whl", hash = "sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472", size = 15038, upload-time = "2026-07-01T17:11:54.055Z" }, +] + +[[package]] +name = "aiohttp" +version = "3.14.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohappyeyeballs" }, + { name = "aiosignal" }, + { name = "attrs" }, + { name = "frozenlist" }, + { name = "multidict" }, + { name = "propcache" }, + { name = "typing-extensions" }, + { name = "yarl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6c/4c/bdccd81e9ee225b69c60e7766c9a5b05364f118f4d383713b89a682d772d/aiohttp-3.14.5.tar.gz", hash = "sha256:5558a7f5a05af9ecf744af91e5baefc436f93c9333e656c27ec253f9a6bbe178", size = 8078052, upload-time = "2026-10-11T01:05:12.408Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d8/f3/8997f18890a92c79f77fcfbb4f78ca17c2d4ab109e9eb6d31b4e9de194a0/aiohttp-3.14.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d51db97c96384fbfcaf8f4c65922183a68b94f891c3c10c862ef5f6df2adbb1f", size = 832358, upload-time = "2026-10-11T00:59:42.195Z" }, + { url = "https://files.pythonhosted.org/packages/8e/42/084651e9efb5cadb99265f786df60f2a7b353cead7bfd2c87003cb4867ad/aiohttp-3.14.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ae53924aa853a7a2ca20ed4142c7c6b56338e4d4cd999e2980075b9efc2e257a", size = 559636, upload-time = "2026-10-11T00:59:43.677Z" }, + { url = "https://files.pythonhosted.org/packages/3d/fe/92838944e601f0fe195fd3f3ada37e29fbee3d19bfd323fe15937ec79d36/aiohttp-3.14.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a2c473a355f9239efcb72c92d5abfd8fcdb0cc78c8e9af607e72ca12dbb36593", size = 552588, upload-time = "2026-10-11T00:59:45.592Z" }, + { url = "https://files.pythonhosted.org/packages/8f/b8/dd9b95c5c20ceae1b47738e656bd79e9883e3117a9cc8b143901eb604e9a/aiohttp-3.14.5-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:32e8fa6644e541fcd7e02430588c7fc93b602c1778ea0bc345505db76b61cfb4", size = 1928224, upload-time = "2026-10-11T00:59:47.294Z" }, + { url = "https://files.pythonhosted.org/packages/c6/47/70010cd2ba8746968d53d433ff328c33f06a66c99da5f3de759c64a6b2eb/aiohttp-3.14.5-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:579f97d5120f2971876d2ddca2968135f6944d00c44c3a6590ad7d86ca9b403f", size = 1877674, upload-time = "2026-10-11T00:59:49.472Z" }, + { url = "https://files.pythonhosted.org/packages/c5/a1/b026f071dbd87f0bdba86b92d47e46f3899e3ad7143b6e0fe7e7887090b4/aiohttp-3.14.5-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:24409db442e2fb6e766bc7f3943851a8381dec3098140e43bb2e843b79e31b12", size = 1985850, upload-time = "2026-10-11T00:59:51.296Z" }, + { url = "https://files.pythonhosted.org/packages/36/d1/f7b6f6f8c3cb5a71b53baeddc2e70c224c28b12a23a55c42994c504019b7/aiohttp-3.14.5-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5e8f97c0488ffda3082766ac0f2c8150a9a58c4d05788330e479cfd449b37939", size = 2105471, upload-time = "2026-10-11T00:59:53.191Z" }, + { url = "https://files.pythonhosted.org/packages/42/74/2a2b22953de15c6c8a80debf26db3047e4e8a5a5db6dd7c2c6c01eec0605/aiohttp-3.14.5-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50a195903119008fe9cc68710535eb37f556ffffd6a7759afe70a2c145587045", size = 1929915, upload-time = "2026-10-11T00:59:55.609Z" }, + { url = "https://files.pythonhosted.org/packages/33/ad/f80e8d33933d0eacd0217efa3b7fb32c9f48ed480ed0db53cf9948bf474f/aiohttp-3.14.5-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0133c3c3b54a0bf1e71fa5c1ad95c93f07fd54e24ef1fe182f5122e1573d2bf1", size = 1773832, upload-time = "2026-10-11T00:59:57.611Z" }, + { url = "https://files.pythonhosted.org/packages/04/a4/0273d239f3e3bb69438f209c64c82e1f98dc60d5db264795e41f7dd05dcb/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c172db893e516e1358e65a95ee20b7ce7173963eefe318b6ab2a2220688b999e", size = 1901001, upload-time = "2026-10-11T01:00:00.605Z" }, + { url = "https://files.pythonhosted.org/packages/16/ed/7dd439d26c654645bc34ca3c9a822fc11c1c51801fed1cefdfe1cc41c1f6/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:f2a7966bda23dd85051f1661ce0ace38d6890e05ec6c357ecae9d2479cba377e", size = 1907218, upload-time = "2026-10-11T01:00:02.699Z" }, + { url = "https://files.pythonhosted.org/packages/32/dd/86249c3b8248562a17fd3e22ee0c164378d65766f01aceef62cf52783710/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:4887d130a7bbfed3a85493bb5a25e5b5b558d40c1d986dd16970d2bb26d63793", size = 1958650, upload-time = "2026-10-11T01:00:04.851Z" }, + { url = "https://files.pythonhosted.org/packages/bc/0b/ca4d53d68f683ce195807fd0aeb063bf6d1c6b39343fff234c9524e8d5a9/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:225c579c23b68b343cccea27a7e06e3bd8ec23a09c30b427eb3f1e4ca6239b20", size = 1760057, upload-time = "2026-10-11T01:00:06.978Z" }, + { url = "https://files.pythonhosted.org/packages/6b/42/005437ffd7fa56c2ce3347add40404b654a32754ce91f2e2a14b9e5ab2bc/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:ab52d8f1fc1b64821c1fbad64a647ed6203627004059a6d1ed4f0858a1499703", size = 1978081, upload-time = "2026-10-11T01:00:08.868Z" }, + { url = "https://files.pythonhosted.org/packages/03/71/3a5b66fe1b7b23d3c6524350817ed55de5feb7fbb4cccba7cbe044d118dd/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:cb131d775a1573c1aee66656bd78b023577bbdb6cb8349a07773bd4f73e68a6e", size = 1922954, upload-time = "2026-10-11T01:00:11.035Z" }, + { url = "https://files.pythonhosted.org/packages/69/84/d08a554f281d42fd7c6b2b6dd7738f3e3a7a9f657ddd87e11ca2091cdfe3/aiohttp-3.14.5-cp311-cp311-win32.whl", hash = "sha256:e87046c8ff77a8decdb6a41d8ab25824b47531b2da933aeab0c1e21c7acff329", size = 488101, upload-time = "2026-10-11T01:00:12.933Z" }, + { url = "https://files.pythonhosted.org/packages/0f/15/52b5e65f02b33686ae49f1518548ae4f5a7adaf31d9d3c54fa12a143137b/aiohttp-3.14.5-cp311-cp311-win_amd64.whl", hash = "sha256:6f275c11d1aa6d4c458e05a68be084efe3c55a113d99e3f46a318098e52948fc", size = 512575, upload-time = "2026-10-11T01:00:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/b0/b9/bb75012635f3defb0f7cbb7c4ae391e36bb9cb3fbdca3b9944e2ebebf743/aiohttp-3.14.5-cp311-cp311-win_arm64.whl", hash = "sha256:b032a0023eb41d768ce77d83210ab2a3c389bc0b09313273c7e1eca48c10a755", size = 493179, upload-time = "2026-10-11T01:00:16.961Z" }, + { url = "https://files.pythonhosted.org/packages/68/30/173960c42b05a6c59f7558e4b12a4b0d9ba376cf6aa9bde7f9e08a30ca8d/aiohttp-3.14.5-py3-none-any.whl", hash = "sha256:efc21a454892828368b11c2c780de0ff8bc991f73f6b99c6b66e56205470929b", size = 279517, upload-time = "2026-10-11T01:05:08.523Z" }, +] + +[[package]] +name = "aiosignal" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "frozenlist" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, +] + +[[package]] +name = "annotated-types" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "bitsandbytes" +version = "0.48.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "packaging" }, + { name = "torch" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/d5/56/e58f1eeb41c71d3789d401ad147fc0fa78fa7004ea58616ba6abc50889c8/bitsandbytes-0.48.2-py3-none-manylinux_2_24_aarch64.whl", hash = "sha256:defbfa374d93809de3811cd2bca6978d1d51ecaa39f5bdd2018e1394a4886603", size = 33764723, upload-time = "2025-10-29T21:40:36.389Z" }, + { url = "https://files.pythonhosted.org/packages/3b/72/f6934097c94e023967bf7eb24e50987aca8a40f4cabf4e0282957f6258c2/bitsandbytes-0.48.2-py3-none-manylinux_2_24_x86_64.whl", hash = "sha256:cd289562cb7308ee2a707e6884fecca9bbbcfc9ec33a86df2a45e0779692c1a3", size = 59399452, upload-time = "2025-10-29T21:40:39.941Z" }, + { url = "https://files.pythonhosted.org/packages/17/2d/309b3ba276d1fe5f3db4fb5e0a6926d10654656cdbfe49881aa95f4cfcc2/bitsandbytes-0.48.2-py3-none-win_amd64.whl", hash = "sha256:a048c285eb6ff53a8d189880e9dfa421d2bfb54e8cab263311757cf5b742d865", size = 58992447, upload-time = "2025-10-29T21:40:43.921Z" }, +] + +[[package]] +name = "certifi" +version = "2026.10.23" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/67/6a0b94a7960d5e1b5eacd2fb529f3fccc47db4644f7f0a7cfdcfc3be578a/charset_normalizer-3.5.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6", size = 370642, upload-time = "2026-09-30T04:35:06.91Z" }, + { url = "https://files.pythonhosted.org/packages/fb/94/01009e13b94041599004edf32e56e382c24e570f60f79bab8efe45cfe1eb/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5", size = 259280, upload-time = "2026-09-30T04:35:08.448Z" }, + { url = "https://files.pythonhosted.org/packages/66/85/3b5358f60a13210f0b67d3755c168ef758701b021e655d88d4da28554467/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74", size = 245335, upload-time = "2026-09-30T04:35:10.104Z" }, + { url = "https://files.pythonhosted.org/packages/74/75/77c1c479b09ecd751d1e767b251ea5c14d4d50ff757bf404afab2692f600/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab", size = 291707, upload-time = "2026-09-30T04:35:11.575Z" }, + { url = "https://files.pythonhosted.org/packages/0b/0d/363f78cacb70f58f15f4b083961bbd9d292f335d3f5c66fc4f1cfe69cb90/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c", size = 286747, upload-time = "2026-09-30T04:35:13.022Z" }, + { url = "https://files.pythonhosted.org/packages/e4/ed/cf505d3011ffceb12c2067a7a5d3cfe92b875d4d44bb0ff0d69375e2c184/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f", size = 269972, upload-time = "2026-09-30T04:35:14.606Z" }, + { url = "https://files.pythonhosted.org/packages/15/d8/f0a93a431d170e7ca681d4f6650fee3de934d18560e474e7267eb4b0f987/charset_normalizer-3.5.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288", size = 269339, upload-time = "2026-09-30T04:35:16.087Z" }, + { url = "https://files.pythonhosted.org/packages/86/bd/9b2bd1c5b7af02462c9752d33994834ff972a96b4c483eefde9e594488e2/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400", size = 261683, upload-time = "2026-09-30T04:35:17.488Z" }, + { url = "https://files.pythonhosted.org/packages/76/a5/cac540ab0fd61f3fec88ad3dbb64509e71424593d73cfdfff5ab3e4db279/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd", size = 248143, upload-time = "2026-09-30T04:35:18.849Z" }, + { url = "https://files.pythonhosted.org/packages/71/7a/ff467301deef2089fad87f72df9e000a26a78fec7acbb18e1999371b8369/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37", size = 292358, upload-time = "2026-09-30T04:35:20.326Z" }, + { url = "https://files.pythonhosted.org/packages/ad/77/22d7e785d1e210afc2e2f58600dd1799d17a35665faf84383f002826c5f8/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac", size = 268766, upload-time = "2026-09-30T04:35:21.72Z" }, + { url = "https://files.pythonhosted.org/packages/ae/91/e8e946267f1c2d9e2bd651726e2fbd2addf02c4d36cea5069e32ca9d7bb5/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a", size = 287432, upload-time = "2026-09-30T04:35:23.273Z" }, + { url = "https://files.pythonhosted.org/packages/4e/88/7561d8a88d555e7df6623abe7c0070b4baf47549b9408783a2ae0a1a6cf7/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640", size = 272470, upload-time = "2026-09-30T04:35:24.655Z" }, + { url = "https://files.pythonhosted.org/packages/35/7e/578c702301ec036f01455f30744a08d2b42f6ab35b9b2d4bf8cae0ef2a80/charset_normalizer-3.5.2-cp311-cp311-win32.whl", hash = "sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d", size = 186688, upload-time = "2026-09-30T04:35:26.225Z" }, + { url = "https://files.pythonhosted.org/packages/e8/fc/fdf8cf52ff21cd5bf158f20978991cf985325842f74283eb6df26c8a39d8/charset_normalizer-3.5.2-cp311-cp311-win_amd64.whl", hash = "sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96", size = 214932, upload-time = "2026-09-30T04:35:27.796Z" }, + { url = "https://files.pythonhosted.org/packages/97/66/3e45a506d8110b632541faf9a9470185aa9878f1ed44020f31346c1c5e5b/charset_normalizer-3.5.2-cp311-cp311-win_arm64.whl", hash = "sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1", size = 202828, upload-time = "2026-09-30T04:35:29.259Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" }, + { url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" }, + { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" }, + { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" }, + { url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" }, +] + +[[package]] +name = "click" +version = "8.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, +] + +[[package]] +name = "cloudpickle" +version = "3.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/27/fb/576f067976d320f5f0114a8d9fa1215425441bb35627b1993e5afd8111e5/cloudpickle-3.1.2.tar.gz", hash = "sha256:7fda9eb655c9c230dab534f1983763de5835249750e85fbcef43aaa30a9a2414", size = 22330, upload-time = "2025-11-03T09:25:26.604Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/39/799be3f2f0f38cc727ee3b4f1445fe6d5e4133064ec2e4115069418a5bb6/cloudpickle-3.1.2-py3-none-any.whl", hash = "sha256:9acb47f6afd73f60dc1df93bb801b472f05ff42fa6c84167d25cb206be1fbf4a", size = 22228, upload-time = "2025-11-03T09:25:25.534Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "contourpy" +version = "1.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/91/2e/c4390a31919d8a78b90e8ecf87cd4b4c4f05a5b48d05ec17db8e5404c6f4/contourpy-1.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:709a48ef9a690e1343202916450bc48b9e51c049b089c7f79a267b46cffcdaa1", size = 288773, upload-time = "2025-07-26T12:01:02.277Z" }, + { url = "https://files.pythonhosted.org/packages/0d/44/c4b0b6095fef4dc9c420e041799591e3b63e9619e3044f7f4f6c21c0ab24/contourpy-1.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:23416f38bfd74d5d28ab8429cc4d63fa67d5068bd711a85edb1c3fb0c3e2f381", size = 270149, upload-time = "2025-07-26T12:01:04.072Z" }, + { url = "https://files.pythonhosted.org/packages/30/2e/dd4ced42fefac8470661d7cb7e264808425e6c5d56d175291e93890cce09/contourpy-1.3.3-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:929ddf8c4c7f348e4c0a5a3a714b5c8542ffaa8c22954862a46ca1813b667ee7", size = 329222, upload-time = "2025-07-26T12:01:05.688Z" }, + { url = "https://files.pythonhosted.org/packages/f2/74/cc6ec2548e3d276c71389ea4802a774b7aa3558223b7bade3f25787fafc2/contourpy-1.3.3-cp311-cp311-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e999574eddae35f1312c2b4b717b7885d4edd6cb46700e04f7f02db454e67c1", size = 377234, upload-time = "2025-07-26T12:01:07.054Z" }, + { url = "https://files.pythonhosted.org/packages/03/b3/64ef723029f917410f75c09da54254c5f9ea90ef89b143ccadb09df14c15/contourpy-1.3.3-cp311-cp311-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0bf67e0e3f482cb69779dd3061b534eb35ac9b17f163d851e2a547d56dba0a3a", size = 380555, upload-time = "2025-07-26T12:01:08.801Z" }, + { url = "https://files.pythonhosted.org/packages/5f/4b/6157f24ca425b89fe2eb7e7be642375711ab671135be21e6faa100f7448c/contourpy-1.3.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e79c1f7470158e838808d4a996fa9bac72c498e93d8ebe5119bc1e6becb0db", size = 355238, upload-time = "2025-07-26T12:01:10.319Z" }, + { url = "https://files.pythonhosted.org/packages/98/56/f914f0dd678480708a04cfd2206e7c382533249bc5001eb9f58aa693e200/contourpy-1.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:598c3aaece21c503615fd59c92a3598b428b2f01bfb4b8ca9c4edeecc2438620", size = 1326218, upload-time = "2025-07-26T12:01:12.659Z" }, + { url = "https://files.pythonhosted.org/packages/fb/d7/4a972334a0c971acd5172389671113ae82aa7527073980c38d5868ff1161/contourpy-1.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:322ab1c99b008dad206d406bb61d014cf0174df491ae9d9d0fac6a6fda4f977f", size = 1392867, upload-time = "2025-07-26T12:01:15.533Z" }, + { url = "https://files.pythonhosted.org/packages/75/3e/f2cc6cd56dc8cff46b1a56232eabc6feea52720083ea71ab15523daab796/contourpy-1.3.3-cp311-cp311-win32.whl", hash = "sha256:fd907ae12cd483cd83e414b12941c632a969171bf90fc937d0c9f268a31cafff", size = 183677, upload-time = "2025-07-26T12:01:17.088Z" }, + { url = "https://files.pythonhosted.org/packages/98/4b/9bd370b004b5c9d8045c6c33cf65bae018b27aca550a3f657cdc99acdbd8/contourpy-1.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:3519428f6be58431c56581f1694ba8e50626f2dd550af225f82fb5f5814d2a42", size = 225234, upload-time = "2025-07-26T12:01:18.256Z" }, + { url = "https://files.pythonhosted.org/packages/d9/b6/71771e02c2e004450c12b1120a5f488cad2e4d5b590b1af8bad060360fe4/contourpy-1.3.3-cp311-cp311-win_arm64.whl", hash = "sha256:15ff10bfada4bf92ec8b31c62bf7c1834c244019b4a33095a68000d7075df470", size = 193123, upload-time = "2025-07-26T12:01:19.848Z" }, + { url = "https://files.pythonhosted.org/packages/a5/29/8dcfe16f0107943fa92388c23f6e05cff0ba58058c4c95b00280d4c75a14/contourpy-1.3.3-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:cd5dfcaeb10f7b7f9dc8941717c6c2ade08f587be2226222c12b25f0483ed497", size = 278809, upload-time = "2025-07-26T12:02:52.74Z" }, + { url = "https://files.pythonhosted.org/packages/85/a9/8b37ef4f7dafeb335daee3c8254645ef5725be4d9c6aa70b50ec46ef2f7e/contourpy-1.3.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:0c1fc238306b35f246d61a1d416a627348b5cf0648648a031e14bb8705fcdfe8", size = 261593, upload-time = "2025-07-26T12:02:54.037Z" }, + { url = "https://files.pythonhosted.org/packages/0a/59/ebfb8c677c75605cc27f7122c90313fd2f375ff3c8d19a1694bda74aaa63/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f9aad7de812d6541d29d2bbf8feb22ff7e1c299523db288004e3157ff4674e", size = 302202, upload-time = "2025-07-26T12:02:55.947Z" }, + { url = "https://files.pythonhosted.org/packages/3c/37/21972a15834d90bfbfb009b9d004779bd5a07a0ec0234e5ba8f64d5736f4/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5ed3657edf08512fc3fe81b510e35c2012fbd3081d2e26160f27ca28affec989", size = 329207, upload-time = "2025-07-26T12:02:57.468Z" }, + { url = "https://files.pythonhosted.org/packages/0c/58/bd257695f39d05594ca4ad60df5bcb7e32247f9951fd09a9b8edb82d1daa/contourpy-1.3.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:3d1a3799d62d45c18bafd41c5fa05120b96a28079f2393af559b843d1a966a77", size = 225315, upload-time = "2025-07-26T12:02:58.801Z" }, +] + +[[package]] +name = "cuda-bindings" +version = "13.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-pathfinder", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/09/74e159fbe67b081cca842871addce6d2b493f9bb48ce85124f023eb5f1c9/cuda_bindings-13.5.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71c15ed97099a8ef416515d80ddd10770e0f6339234e16855a526d2896516631", size = 7434875, upload-time = "2026-11-05T12:05:50.666Z" }, + { url = "https://files.pythonhosted.org/packages/f6/0d/ca24317a31118b90fd60126aec5c0a92a191a7fdd39524032d43328b49b5/cuda_bindings-13.5.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:08b7e8d674c3266facb00453a7e34ea7d3ea965c2f594bb728f269f45f39fbe2", size = 8390178, upload-time = "2026-11-05T12:05:52.653Z" }, + { url = "https://files.pythonhosted.org/packages/a6/7b/455b204f07dcbac810bc48b558d3febff8adb81b6036efac315bd5a4aa33/cuda_bindings-13.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:0d7a5d92be00b2a618fd7c62482f6c69584fd5ac498193b236600810d7ebaf74", size = 8097474, upload-time = "2026-11-05T12:05:59.207Z" }, + { url = "https://files.pythonhosted.org/packages/a0/70/9ab184a434f47dacedd47a49901c0be1a81080e8b57d1d3f0e5445bb1277/cuda_bindings-13.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:4d850299e6ba1ca9caec78b3d87b6b7590ed1d6c9a404272798f40b1e19e3f24", size = 7010633, upload-time = "2026-11-05T12:06:00.913Z" }, +] + +[[package]] +name = "cuda-pathfinder" +version = "1.8.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/9e/08555797c979322def080814686417ea93f66d38f5c48ebab6867a85a21e/cuda_pathfinder-1.8.6-py3-none-any.whl", hash = "sha256:bf6b3b06323cf95a11d671818392da5da23ddbbb4dfc4b77ca10622783c25980", size = 62603, upload-time = "2026-11-05T21:22:51.229Z" }, +] + +[[package]] +name = "cuda-toolkit" +version = "13.0.3.0" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/c7/a79086a62c98befcdb8349656c6f114e2db3b8b2422f6e25c97a7f2a9a3c/cuda_toolkit-13.0.3.0-py2.py3-none-any.whl", hash = "sha256:d693caaa261214ddd7dbb60d68e71cbed884e68c2be7509778f3051da0b91c3f", size = 2512, upload-time = "2026-04-14T00:50:08.173Z" }, +] + +[package.optional-dependencies] +cublas = [ + { name = "nvidia-cublas", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +cudart = [ + { name = "nvidia-cuda-runtime", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +cufft = [ + { name = "nvidia-cufft", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +cufile = [ + { name = "nvidia-cufile", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +cupti = [ + { name = "nvidia-cuda-cupti", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +curand = [ + { name = "nvidia-curand", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +cusolver = [ + { name = "nvidia-cublas", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-cusolver", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-cusparse", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +cusparse = [ + { name = "nvidia-cusparse", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +nvjitlink = [ + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +nvrtc = [ + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +nvtx = [ + { name = "nvidia-nvtx", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] + +[[package]] +name = "cycler" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, +] + +[[package]] +name = "datasets" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "aiohttp" }, + { name = "dill" }, + { name = "filelock" }, + { name = "fsspec", extra = ["http"], marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "huggingface-hub" }, + { name = "multiprocess" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pyarrow", version = "17.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "xxhash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e5/a5/38719e5cff7aa0537a6be37d21cc1fdd7096e9565e8fce2d46a822e10b5b/datasets-2.21.0.tar.gz", hash = "sha256:998f85a8460f1bd982e5bd058f8a0808eef424249e3df1e8cdd594ccd0dc8ba2", size = 2215317, upload-time = "2024-08-14T06:40:44.314Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/b3/33c4ad44fa020e3757e9b2fad8a5de53d9079b501e6bbc45bdd18f82f893/datasets-2.21.0-py3-none-any.whl", hash = "sha256:25e4e097110ce28824b746a107727ada94024cba11db8bc588d468414692b65a", size = 527251, upload-time = "2024-08-14T06:40:39.612Z" }, +] + +[[package]] +name = "datasets" +version = "3.6.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "dill" }, + { name = "filelock" }, + { name = "fsspec", extra = ["http"], marker = "extra == 'group-25-official-loren-experiment-modern'" }, + { name = "huggingface-hub" }, + { name = "multiprocess" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pyarrow", version = "20.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "xxhash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1a/89/d3d6fef58a488f8569c82fd293ab7cbd4250244d67f425dcae64c63800ea/datasets-3.6.0.tar.gz", hash = "sha256:1b2bf43b19776e2787e181cfd329cb0ca1a358ea014780c3581e0f276375e041", size = 569336, upload-time = "2025-05-07T15:15:02.659Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/34/a08b0ee99715eaba118cbe19a71f7b5e2425c2718ef96007c325944a1152/datasets-3.6.0-py3-none-any.whl", hash = "sha256:25000c4a2c0873a710df127d08a202a06eab7bf42441a6bc278b499c2f72cd1b", size = 491546, upload-time = "2025-05-07T15:14:59.742Z" }, +] + +[[package]] +name = "dill" +version = "0.3.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/17/4d/ac7ffa80c69ea1df30a8aa11b3578692a5118e7cd1aa157e3ef73b092d15/dill-0.3.8.tar.gz", hash = "sha256:3ebe3c479ad625c4553aca177444d89b486b1d84982eeacded644afc0cf797ca", size = 184847, upload-time = "2024-01-27T23:42:16.145Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/7a/cef76fd8438a42f96db64ddaa85280485a9c395e7df3db8158cfec1eee34/dill-0.3.8-py3-none-any.whl", hash = "sha256:c36ca9ffb54365bdd2f8eb3eff7d2a21237f8452b57ace88b1ac615b7e815bd7", size = 116252, upload-time = "2024-01-27T23:42:14.239Z" }, +] + +[[package]] +name = "einops" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e5/81/df4fbe24dff8ba3934af99044188e20a98ed441ad17a274539b74e82e126/einops-0.8.1.tar.gz", hash = "sha256:de5d960a7a761225532e0f1959e5315ebeafc0cd43394732f103ca44b9837e84", size = 54805, upload-time = "2025-02-09T03:17:00.434Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/62/9773de14fe6c45c23649e98b83231fffd7b9892b6cf863251dc2afa73643/einops-0.8.1-py3-none-any.whl", hash = "sha256:919387eb55330f5757c6bea9165c5ff5cfe63a642682ea788a6d472576d81737", size = 64359, upload-time = "2025-02-09T03:17:01.998Z" }, +] + +[[package]] +name = "filelock" +version = "4.2.10" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/cf/05bcdacabdc0aec7dc8e19d76281bd82325df62dae3b6430e9ba57397689/filelock-4.2.10.tar.gz", hash = "sha256:fcc3c0cb8bfe7f4b3bb0e231c04b15dbad068cb3c2515f343d8fde4dce93bd5d", size = 670595, upload-time = "2026-11-09T18:58:00.54Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/90/5d0096a325aa0f83ba7a3968bfb485b67e32c947bdf9cd0fcb4b485be718/filelock-4.2.10-py3-none-any.whl", hash = "sha256:9479aaeb4db20b5a53e3da28493edd24720b66b8a0b84030aa56ccdf243d6857", size = 218040, upload-time = "2026-11-09T18:57:59.088Z" }, +] + +[[package]] +name = "fonttools" +version = "4.68.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0c/b5/672312ae80ce8b8eb9779c56052a24c8f36652aa7293a1a420553bcf03e5/fonttools-4.68.0.tar.gz", hash = "sha256:73294e233070f71e2b3653b6bd8564af676d57f26d075761fb06d1ab2e4a7a5d", size = 3848583, upload-time = "2026-10-27T16:30:26.451Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/21/51/7c725115425be01aa0fac87eb38f8e8c8c04de80d49a99b08a74898b25ee/fonttools-4.68.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:362443ab355701d6fd26b10d022cd6c8456e1e248f80103c44cbe5ef0228f87f", size = 3135538, upload-time = "2026-10-27T16:28:02.169Z" }, + { url = "https://files.pythonhosted.org/packages/2e/d5/0a04cbde3e3e997d7bda216f77566bea2eb79018e4ca2adb13ce3c9a7206/fonttools-4.68.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:664dfa7a4869b3c827dfc2c38dbbb7a58d53e97933d1bd51ee6729792ee73d50", size = 2632853, upload-time = "2026-10-27T16:28:04.962Z" }, + { url = "https://files.pythonhosted.org/packages/d8/8c/aa4c7b38f4814d6bcb3378276bff802c9610a1227f1d24965a9f23f0a48c/fonttools-4.68.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:53f2387d7e3816763f30e08d14263be18e28ead53d4dc20a82f9280d0c99d88a", size = 5530571, upload-time = "2026-10-27T16:28:06.952Z" }, + { url = "https://files.pythonhosted.org/packages/00/01/e0f5b3d648ddd2eae35c4bcddcc2cffc059279e9d2cdb325bed10458f606/fonttools-4.68.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4b9c89b5876f1a74b1341632dfaf4c4c2be565d76c060445df401ebe7a4ceefa", size = 5493829, upload-time = "2026-10-27T16:28:09.127Z" }, + { url = "https://files.pythonhosted.org/packages/ea/bb/9c5568659275c86e6eebb060d98e8ea77c56fb78ee77ea5654a057f72bde/fonttools-4.68.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:054a4d5de7e1f973ab9789e9ae3f20238774783ca9bf7ee0359aebae4de9400c", size = 5496373, upload-time = "2026-10-27T16:28:11.378Z" }, + { url = "https://files.pythonhosted.org/packages/b0/32/0a35ffd35bfc1b0a754563a45500e87d651e0f336cf006a25e0bc460ba2f/fonttools-4.68.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b5a015b322275d3d745b06d5e69cf74ef4b1ce2dae02afbe4826cb186d8527a3", size = 5634196, upload-time = "2026-10-27T16:28:13.783Z" }, + { url = "https://files.pythonhosted.org/packages/93/76/3454e20f07dbe4b308b7bc99117292109bb7775a1b595ead768110144553/fonttools-4.68.0-cp311-cp311-win32.whl", hash = "sha256:bd5b047ed8f16b83d0344fef053668712ab9c88e2e46d8612ec41df83c5222e1", size = 1624232, upload-time = "2026-10-27T16:28:16.001Z" }, + { url = "https://files.pythonhosted.org/packages/46/87/4ba592099172764aa56e66919b0c3ddaf944c775433e806e36e165062095/fonttools-4.68.0-cp311-cp311-win_amd64.whl", hash = "sha256:35425bba603cf9d72c9f3c173ea6c98632164f3bdfb1ce1a3dcc928979c6ec6d", size = 1681821, upload-time = "2026-10-27T16:28:17.757Z" }, + { url = "https://files.pythonhosted.org/packages/e1/54/004f12709b21a56bb944fdca6d165b0d90cf9366143675dbc7bb46784ddd/fonttools-4.68.0-cp311-cp311-win_arm64.whl", hash = "sha256:04365b897c9ee29a048b6d4db74c75c38b70aa6d1074726fbdd7ea1a23aa8ed2", size = 1649151, upload-time = "2026-10-27T16:28:19.502Z" }, + { url = "https://files.pythonhosted.org/packages/35/74/4ea331ecc65ba05a58b1e4e8ccd604c8a15565f876dfbf93fc2a2ea2e22b/fonttools-4.68.0-py3-none-any.whl", hash = "sha256:d76f8fdcb6936f5e1045a0c9dd721a4bf11112e60d1e243bfa1d39f06a8b3104", size = 1248357, upload-time = "2026-10-27T16:30:24.389Z" }, +] + +[[package]] +name = "frozenlist" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/03/077f869d540370db12165c0aa51640a873fb661d8b315d1d4d67b284d7ac/frozenlist-1.8.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:09474e9831bc2b2199fad6da3c14c7b0fbdd377cce9d3d77131be28906cb7d84", size = 86912, upload-time = "2025-10-06T05:35:45.98Z" }, + { url = "https://files.pythonhosted.org/packages/df/b5/7610b6bd13e4ae77b96ba85abea1c8cb249683217ef09ac9e0ae93f25a91/frozenlist-1.8.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:17c883ab0ab67200b5f964d2b9ed6b00971917d5d8a92df149dc2c9779208ee9", size = 50046, upload-time = "2025-10-06T05:35:47.009Z" }, + { url = "https://files.pythonhosted.org/packages/6e/ef/0e8f1fe32f8a53dd26bdd1f9347efe0778b0fddf62789ea683f4cc7d787d/frozenlist-1.8.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:fa47e444b8ba08fffd1c18e8cdb9a75db1b6a27f17507522834ad13ed5922b93", size = 50119, upload-time = "2025-10-06T05:35:48.38Z" }, + { url = "https://files.pythonhosted.org/packages/11/b1/71a477adc7c36e5fb628245dfbdea2166feae310757dea848d02bd0689fd/frozenlist-1.8.0-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2552f44204b744fba866e573be4c1f9048d6a324dfe14475103fd51613eb1d1f", size = 231067, upload-time = "2025-10-06T05:35:49.97Z" }, + { url = "https://files.pythonhosted.org/packages/45/7e/afe40eca3a2dc19b9904c0f5d7edfe82b5304cb831391edec0ac04af94c2/frozenlist-1.8.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:957e7c38f250991e48a9a73e6423db1bb9dd14e722a10f6b8bb8e16a0f55f695", size = 233160, upload-time = "2025-10-06T05:35:51.729Z" }, + { url = "https://files.pythonhosted.org/packages/a6/aa/7416eac95603ce428679d273255ffc7c998d4132cfae200103f164b108aa/frozenlist-1.8.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8585e3bb2cdea02fc88ffa245069c36555557ad3609e83be0ec71f54fd4abb52", size = 228544, upload-time = "2025-10-06T05:35:53.246Z" }, + { url = "https://files.pythonhosted.org/packages/8b/3d/2a2d1f683d55ac7e3875e4263d28410063e738384d3adc294f5ff3d7105e/frozenlist-1.8.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:edee74874ce20a373d62dc28b0b18b93f645633c2943fd90ee9d898550770581", size = 243797, upload-time = "2025-10-06T05:35:54.497Z" }, + { url = "https://files.pythonhosted.org/packages/78/1e/2d5565b589e580c296d3bb54da08d206e797d941a83a6fdea42af23be79c/frozenlist-1.8.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c9a63152fe95756b85f31186bddf42e4c02c6321207fd6601a1c89ebac4fe567", size = 247923, upload-time = "2025-10-06T05:35:55.861Z" }, + { url = "https://files.pythonhosted.org/packages/aa/c3/65872fcf1d326a7f101ad4d86285c403c87be7d832b7470b77f6d2ed5ddc/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b6db2185db9be0a04fecf2f241c70b63b1a242e2805be291855078f2b404dd6b", size = 230886, upload-time = "2025-10-06T05:35:57.399Z" }, + { url = "https://files.pythonhosted.org/packages/a0/76/ac9ced601d62f6956f03cc794f9e04c81719509f85255abf96e2510f4265/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:f4be2e3d8bc8aabd566f8d5b8ba7ecc09249d74ba3c9ed52e54dc23a293f0b92", size = 245731, upload-time = "2025-10-06T05:35:58.563Z" }, + { url = "https://files.pythonhosted.org/packages/b9/49/ecccb5f2598daf0b4a1415497eba4c33c1e8ce07495eb07d2860c731b8d5/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:c8d1634419f39ea6f5c427ea2f90ca85126b54b50837f31497f3bf38266e853d", size = 241544, upload-time = "2025-10-06T05:35:59.719Z" }, + { url = "https://files.pythonhosted.org/packages/53/4b/ddf24113323c0bbcc54cb38c8b8916f1da7165e07b8e24a717b4a12cbf10/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:1a7fa382a4a223773ed64242dbe1c9c326ec09457e6b8428efb4118c685c3dfd", size = 241806, upload-time = "2025-10-06T05:36:00.959Z" }, + { url = "https://files.pythonhosted.org/packages/a7/fb/9b9a084d73c67175484ba2789a59f8eebebd0827d186a8102005ce41e1ba/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:11847b53d722050808926e785df837353bd4d75f1d494377e59b23594d834967", size = 229382, upload-time = "2025-10-06T05:36:02.22Z" }, + { url = "https://files.pythonhosted.org/packages/95/a3/c8fb25aac55bf5e12dae5c5aa6a98f85d436c1dc658f21c3ac73f9fa95e5/frozenlist-1.8.0-cp311-cp311-win32.whl", hash = "sha256:27c6e8077956cf73eadd514be8fb04d77fc946a7fe9f7fe167648b0b9085cc25", size = 39647, upload-time = "2025-10-06T05:36:03.409Z" }, + { url = "https://files.pythonhosted.org/packages/0a/f5/603d0d6a02cfd4c8f2a095a54672b3cf967ad688a60fb9faf04fc4887f65/frozenlist-1.8.0-cp311-cp311-win_amd64.whl", hash = "sha256:ac913f8403b36a2c8610bbfd25b8013488533e71e62b4b4adce9c86c8cea905b", size = 44064, upload-time = "2025-10-06T05:36:04.368Z" }, + { url = "https://files.pythonhosted.org/packages/5d/16/c2c9ab44e181f043a86f9a8f84d5124b62dbcb3a02c0977ec72b9ac1d3e0/frozenlist-1.8.0-cp311-cp311-win_arm64.whl", hash = "sha256:d4d3214a0f8394edfa3e303136d0575eece0745ff2b47bd2cb2e66dd92d4351a", size = 39937, upload-time = "2025-10-06T05:36:05.669Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, +] + +[[package]] +name = "fsspec" +version = "2024.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/90/b6/eba5024a9889fcfff396db543a34bef0ab9d002278f163129f9f01005960/fsspec-2024.6.1.tar.gz", hash = "sha256:fad7d7e209dd4c1208e3bbfda706620e0da5142bebbd9c384afb95b07e798e49", size = 284584, upload-time = "2024-06-27T14:35:45.467Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5e/44/73bea497ac69bafde2ee4269292fa3b41f1198f4bb7bbaaabde30ad29d4a/fsspec-2024.6.1-py3-none-any.whl", hash = "sha256:3cb443f8bcd2efb31295a5b9fdb02aee81d8452c80d28f97a6d0959e6cee101e", size = 177561, upload-time = "2024-06-27T14:35:42.023Z" }, +] + +[package.optional-dependencies] +http = [ + { name = "aiohttp" }, +] + +[[package]] +name = "gitdb" +version = "4.0.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "smmap" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/94/63b0fc47eb32792c7ba1fe1b694daec9a63620db1e313033d18140c2320a/gitdb-4.0.12.tar.gz", hash = "sha256:5ef71f855d191a3326fcfbc0d5da835f26b13fbcba60c32c21091c349ffdb571", size = 394684, upload-time = "2025-01-02T07:20:46.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/61/5c78b91c3143ed5c14207f463aecfc8f9dbb5092fb2869baf37c273b2705/gitdb-4.0.12-py3-none-any.whl", hash = "sha256:67073e15955400952c6565cc3e707c554a4eea2e428946f7a4c162fab9bd9bcf", size = 62794, upload-time = "2025-01-02T07:20:43.624Z" }, +] + +[[package]] +name = "gitpython" +version = "3.2.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "gitdb" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/ff/fee293f1ec3e1b64db6eb270e00964f29c086d769201474cedb8d1608930/gitpython-3.2.1.tar.gz", hash = "sha256:0f1229ec5c057bdabdeeda8bda4f17bda679ab33dbccc00f24e6a480553c8613", size = 241688, upload-time = "2026-10-14T12:20:20.589Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6b/50/2a923c4dc02522ff9567f07c67ed1deca6d5fa9474f4708168b8088dfa37/gitpython-3.2.1-py3-none-any.whl", hash = "sha256:d66b0832aa8755c1a84892937282df0befb16c97e5a64aeebd68be9c5e323f53", size = 231548, upload-time = "2026-10-14T12:20:18.844Z" }, +] + +[[package]] +name = "grpcio" +version = "1.85.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f0/03/f9e805772d4d01da2a1754a5f63c58601eacaf8f1e878729217188de7d16/grpcio-1.85.1.tar.gz", hash = "sha256:5f530287d5de5f7f66089ead81de44f6787162944dab3922efa65dfdff108a1d", size = 14091456, upload-time = "2026-10-30T16:01:16.909Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/3c/ab73cb485967ac57f00350fef66c8180400c6a832436cf39811cc7d41f8d/grpcio-1.85.1-cp311-cp311-linux_armv7l.whl", hash = "sha256:d2a776b113e7bd6d139e679f5da281193d6410cce361e4180c9da0d553e01927", size = 6823898, upload-time = "2026-10-30T15:59:12.079Z" }, + { url = "https://files.pythonhosted.org/packages/81/0f/80bd2a767a8cb78e9c257b9062f9786b67c3ce26d403825545ba2e9a79ad/grpcio-1.85.1-cp311-cp311-macosx_11_0_universal2.whl", hash = "sha256:cfa9bf4daed57dd5bd5fac4be3276f5dc1703f41abf4df0737f4e7952705cbc6", size = 12654220, upload-time = "2026-10-30T15:59:14.324Z" }, + { url = "https://files.pythonhosted.org/packages/f8/a0/efb97c6639f59907fe3c17270904918b37cdc406eba2dbe97feacf309a86/grpcio-1.85.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:9885436e83eab92dd0d476642baf08a17c55ef2b1db430adcba3e89bb6938a5d", size = 7215807, upload-time = "2026-10-30T15:59:17.395Z" }, + { url = "https://files.pythonhosted.org/packages/f7/f2/2b0900585deed45e126a1d5939acbaba94f6f4c62a787949cdc03329979d/grpcio-1.85.1-cp311-cp311-manylinux2014_i686.manylinux_2_17_i686.whl", hash = "sha256:3bbf7ae798e38eccb1b7abf169d9e228514418da6f68caec69a295fde899ec17", size = 8200549, upload-time = "2026-10-30T15:59:19.657Z" }, + { url = "https://files.pythonhosted.org/packages/1a/4f/30f66cedfec6c03bc304b28fbe073ed53179cf37a511b8ee8e8e7e2d3f17/grpcio-1.85.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:83aced2a1c05648cee0de34e531351118b14c58238f0a61b43559ac8851647a8", size = 7392335, upload-time = "2026-10-30T15:59:21.917Z" }, + { url = "https://files.pythonhosted.org/packages/4a/ad/5dee0e6e5a57f88379bc2820aa6e3098a2174e21a40bfb961c6d5f5b28d0/grpcio-1.85.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b364bc3daa601eb1cb0023e90b1309cbf6da0de6ca40a19f2d5a31edeb9990e3", size = 7955183, upload-time = "2026-10-30T15:59:24.197Z" }, + { url = "https://files.pythonhosted.org/packages/43/d8/93b729c8fc1aee6232906cffd44a9dfcb6f8387e6279a1238cd972ff468a/grpcio-1.85.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:c9a4a4e504bd914e10c0d6190ffac59b9e21f1c962366b72293075ade097793d", size = 9212733, upload-time = "2026-10-30T15:59:26.388Z" }, + { url = "https://files.pythonhosted.org/packages/08/4d/d6339c51032649a90c347a67ad41b56f2f1a564f4960efcc72409fe03eba/grpcio-1.85.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:83b09ca3f9602caf4f1b4295b4bb002b10477789ff9797feeedc811b9a6be0b7", size = 8332651, upload-time = "2026-10-30T15:59:29.113Z" }, + { url = "https://files.pythonhosted.org/packages/b4/bf/085116e89db4f758af02eca2da9ad3a1890fb1691f5e2fc882c402ed9622/grpcio-1.85.1-cp311-cp311-win32.whl", hash = "sha256:bbc678a2b8d10e0dea666d948f36237e681be3686079564937df689bac386bc5", size = 4779959, upload-time = "2026-10-30T15:59:31.001Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b8/fb80401f9eaf51eb2fc8c5dbf8e4f8cbfeebc21bf837f7c6576790ce433e/grpcio-1.85.1-cp311-cp311-win_amd64.whl", hash = "sha256:27b519f6594da04cf2dda1378f46811b2b6160d60a01f88a0ec4de009bbbfa46", size = 5615553, upload-time = "2026-10-30T15:59:33.252Z" }, +] + +[[package]] +name = "hf-xet" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" }, + { url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" }, + { url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" }, + { url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" }, + { url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" }, +] + +[[package]] +name = "huggingface-hub" +version = "0.36.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "filelock" }, + { name = "fsspec" }, + { name = "hf-xet", marker = "platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/63/4910c5fa9128fdadf6a9c5ac138e8b1b6cee4ca44bf7915bbfbce4e355ee/huggingface_hub-0.36.0.tar.gz", hash = "sha256:47b3f0e2539c39bf5cde015d63b72ec49baff67b6931c3d97f3f84532e2b8d25", size = 463358, upload-time = "2025-10-23T12:12:01.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/bd/1a875e0d592d447cbc02805fd3fe0f497714d6a2583f59d14fa9ebad96eb/huggingface_hub-0.36.0-py3-none-any.whl", hash = "sha256:7bcc9ad17d5b3f07b57c78e79d527102d08313caa278a641993acddcb894548d", size = 566094, upload-time = "2025-10-23T12:11:59.557Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "joblib" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cloudpickle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d5/1d/537ab090f302b838943a1b56497dd53059b9a9b46a074936470173a2e207/joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03", size = 327903, upload-time = "2026-08-31T09:39:04.122Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115, upload-time = "2026-08-31T09:39:02.298Z" }, +] + +[[package]] +name = "kiwisolver" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea041ef5bba3ed21a003522fa088834b069b1909981f30/kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a", size = 104395, upload-time = "2026-08-28T10:28:27.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/7b/2de6908edc668427c149af5f93112e931f87e1fa4cab80bac32c5844dccc/kiwisolver-1.5.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b3d78f7bb2b9d9a30345be1474b9aaa8685430b54afb51ba3639b5c6c11e9ed6", size = 123364, upload-time = "2026-08-28T10:25:04.359Z" }, + { url = "https://files.pythonhosted.org/packages/8a/24/e70914415c77c97be7e22c80a0740869cb7428768cc380fdcdf6703e7084/kiwisolver-1.5.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5025e36fb4fb275cef0a4e30dbb11cb4ae61d1c83deb90189cb5d7e4cafd6b55", size = 66558, upload-time = "2026-08-28T10:25:05.506Z" }, + { url = "https://files.pythonhosted.org/packages/e8/2b/8b08b11833db4d475b8ef1f36174f8d8a7abd31bedd7e794be78e8814b48/kiwisolver-1.5.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dc1a26b8e53395a01c2c611e58602fa47461f136fba7cd5542e6db6d64be1839", size = 64071, upload-time = "2026-08-28T10:25:06.7Z" }, + { url = "https://files.pythonhosted.org/packages/89/00/05c2d0369ac322d22d5c05f84b5c4a6856fa6207fbae42869108a28f0383/kiwisolver-1.5.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:95a02752aa032eef4aed01cda6d9b687c669bd0396bf4519eef8bba22a286720", size = 1438206, upload-time = "2026-08-28T10:25:08.254Z" }, + { url = "https://files.pythonhosted.org/packages/c0/05/c941a139f27438c1910d630fdc3ccfdab7c8407c72052299ead12ece086e/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:719a35fa1156db3640555f95ebb94f60a444e64d1c69626b0edef5df78eba225", size = 1248975, upload-time = "2026-08-28T10:25:10.053Z" }, + { url = "https://files.pythonhosted.org/packages/58/a1/2669ee5512e39b9d4de25faacaedf788c957f93730c5f7c63993ec4f5933/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:febcce10f2bcdbb80b4ea919238a6a4ac13dbc4c7cadbe8d5d75c3682f8b5404", size = 1266301, upload-time = "2026-08-28T10:25:11.754Z" }, + { url = "https://files.pythonhosted.org/packages/28/b8/353f52f2c7f861a9e90cd2e8f90f85b3ad03060835f823e08298d094c463/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1d852545c4d0e35a72728d072cbaa59e2fa7dd84bdf01e068d670dd0ceb58eb6", size = 1319708, upload-time = "2026-08-28T10:25:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/21/0e/14b83200eadc2c1d63b76bac01c1813bf072aecf567429f303e00b70258e/kiwisolver-1.5.1-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:2e10ae1bba1899188b33557c10d73affcc12033edd18adddb57d209039976a4c", size = 971720, upload-time = "2026-08-28T10:25:14.934Z" }, + { url = "https://files.pythonhosted.org/packages/86/91/9d43d84d23b1cbff72a142d387ead1ea03db0cba8ff86ed5335addad3cc9/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b69602970994a2ed8bbfa78c2f0394a7435226c6040489702d9f0a0ad0c07052", size = 2200119, upload-time = "2026-08-28T10:25:16.636Z" }, + { url = "https://files.pythonhosted.org/packages/ff/7c/f2bd9616f27ffb5e17cecc0baa5d0bbcee7e55aeddc0ccc871d69e2fc3ee/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d50de98e8d807dc31822fff96f50293163a62418eb65487a21b42713d72ed0b7", size = 2295005, upload-time = "2026-08-28T10:25:18.374Z" }, + { url = "https://files.pythonhosted.org/packages/ba/17/ee671b72bf8f46a08379d4392c65582541759a542428197562f2898294ad/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3221f78211074f561c44ca42eac0619828171bec15a2c4cf6f7747d07df76e8e", size = 1960982, upload-time = "2026-08-28T10:25:19.893Z" }, + { url = "https://files.pythonhosted.org/packages/2e/f7/0e26b4c05bee3bdb0f048dfa305e4fe701999ea17b51e9c616ef91035bbe/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0ba9527afc80ae3d7814ed98b6572d02bf85eaf48065678342c5f0c6dab7a8c7", size = 2464918, upload-time = "2026-08-28T10:25:21.65Z" }, + { url = "https://files.pythonhosted.org/packages/ae/62/6eb431133d30ce656ac1e5ff72fac70dd34d54c3984f4011b9ac8bf77d54/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e12dfea7f5fc2a34a9080efbf79c4c44eb380ec5b9c6fea09407e08f0d1e941d", size = 2270967, upload-time = "2026-08-28T10:25:23.643Z" }, + { url = "https://files.pythonhosted.org/packages/bf/9f/6f9e489c188200e6fb3193935501894811e8c97577c8ffe9033589bf3521/kiwisolver-1.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:1a7587dc335f2c0f5bd577fd0540bd16c66006bdb60f759a1059f025e6c4f071", size = 70744, upload-time = "2026-08-28T10:25:25.061Z" }, + { url = "https://files.pythonhosted.org/packages/c6/6d/dfc430d1d43957061599adea3f08ea982bb6f4ab601a8c974bedcf2ba850/kiwisolver-1.5.1-cp311-cp311-win_arm64.whl", hash = "sha256:e4e4523d6f336708d732516e6cfca7796cf3d96c9474eb5aecf6165f2f1fefc3", size = 68404, upload-time = "2026-08-28T10:25:26.186Z" }, + { url = "https://files.pythonhosted.org/packages/b5/1d/59ba570b1774e95e97fde3a0981b2e22118a7a495f73bf74cedc538566a0/kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:416ba7ff9f233b7036689bb5a3783537e838ad483f63558d2a800f75afe738b1", size = 59450, upload-time = "2026-08-28T10:28:20.383Z" }, + { url = "https://files.pythonhosted.org/packages/22/98/a6849f04dc18b5400e8b98affa2cd8fd86ed583085f036e57b32e571f4fa/kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:8af9b142ad719ae3a911ebf616bc4b78b32bbab84d6a40d3ad2f129670509957", size = 57400, upload-time = "2026-08-28T10:28:21.632Z" }, + { url = "https://files.pythonhosted.org/packages/f4/ce/a7dc71353dd06a4cbe02222773f52d4a28c81e5a452a75797f8ed113dc99/kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5daa1f19e097050b9c4d9a78fcc9263cb96c9dfae08037ddc1b7c4ad1889f2a2", size = 79891, upload-time = "2026-08-28T10:28:22.936Z" }, + { url = "https://files.pythonhosted.org/packages/10/b1/d61c61a84ff85d1a36a99df2c152b59ffedb1d356c598902aba44abcdb60/kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cdaeeb6c350106df6bf9d873395973e5f066a9713200b72cd64f55d0a3eafab6", size = 77605, upload-time = "2026-08-28T10:28:24.322Z" }, + { url = "https://files.pythonhosted.org/packages/d3/52/5aef56f21a460a6e43ab3cdfc7697d59d7b87deb0ec97a0f7b91aa4a521b/kiwisolver-1.5.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:17851e5dad4484be0cbccbde3b15331deae036de9aebd45eed964487802b172f", size = 98465, upload-time = "2026-08-28T10:28:25.696Z" }, +] + +[[package]] +name = "lightning" +version = "2.5.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "fsspec", extra = ["http"] }, + { name = "lightning-utilities" }, + { name = "packaging" }, + { name = "pytorch-lightning" }, + { name = "pyyaml" }, + { name = "torch" }, + { name = "torchmetrics" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e9/da/289e17b2d4631b885771ce10ab7fe19c6c0ab2b1208d1dda418818ffbbfd/lightning-2.5.6.tar.gz", hash = "sha256:57b6abe87080895bc237fb7f36b7b4abaa2793760cbca00e3907e56607e0ed27", size = 640106, upload-time = "2025-11-05T20:53:06.823Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/23/dc/d7804f13928b6a81a0e948cfecbf0071e8cc74e3f341c704e23e75e504ad/lightning-2.5.6-py3-none-any.whl", hash = "sha256:25bb2053078c2efc57c082fda89dfbd975dfa76beb08def191947c2b571a8c8a", size = 827915, upload-time = "2025-11-05T20:53:03.169Z" }, +] + +[[package]] +name = "lightning-utilities" +version = "0.15.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "packaging" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f1/45/7fa8f56b17dc0f0a41ec70dd307ecd6787254483549843bef4c30ab5adce/lightning_utilities-0.15.3.tar.gz", hash = "sha256:792ae0204c79f6859721ac7f386c237a33b0ed06ba775009cb894e010a842033", size = 33553, upload-time = "2026-02-22T14:48:53.348Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/25/f4/ead6e0e37209b07c9baa3e984ccdb0348ca370b77cea3aaea8ddbb097e00/lightning_utilities-0.15.3-py3-none-any.whl", hash = "sha256:6c55f1bee70084a1cbeaa41ada96e4b3a0fea5909e844dd335bd80f5a73c5f91", size = 31906, upload-time = "2026-02-22T14:48:52.488Z" }, +] + +[[package]] +name = "loguru" +version = "0.7.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "win32-setctime", marker = "sys_platform == 'win32' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/3a/05/a1dae3dffd1116099471c643b8924f5aa6524411dc6c63fdae648c4f1aca/loguru-0.7.3.tar.gz", hash = "sha256:19480589e77d47b8d85b2c827ad95d49bf31b0dcde16593892eb51dd18706eb6", size = 63559, upload-time = "2024-12-06T11:20:56.608Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/29/0348de65b8cc732daa3e33e67806420b2ae89bdce2b04af740289c5c6c8c/loguru-0.7.3-py3-none-any.whl", hash = "sha256:31a33c10c8e1e10422bfd431aeb5d351c7cf7fa671e3c4df004162264b28220c", size = 61595, upload-time = "2024-12-06T11:20:54.538Z" }, +] + +[[package]] +name = "loralib" +version = "0.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/3d/da/117193e94c47dc5288b17443d53d8c4b373c59e37d2ffda7e275e0cea717/loralib-0.1.2.tar.gz", hash = "sha256:22ccff494a6254b973ddaee9f9aad4657941cab4221c75c5a04e0cac4fbd4567", size = 14552, upload-time = "2023-08-27T16:48:19.333Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f1/e7/a4362bf791bca17d2d91e7c69483185ab03d5aa05dd10391eff2e179a685/loralib-0.1.2-py3-none-any.whl", hash = "sha256:e341c9a507b180f3b8e70914efef9f6b19d1aa3996dec546b180cfbd027059e9", size = 10390, upload-time = "2023-08-27T16:48:17.723Z" }, +] + +[[package]] +name = "markdown" +version = "3.11.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ca/eb/dc0fd6eff604bfb870b7fb68b90985a32caaf3c76f67736bbf7f438acd59/markdown-3.11.3.tar.gz", hash = "sha256:81eb91631dc97ad1efbc76019ef0f80fe90ca49ddf81546752d79989c3bfff3e", size = 498810, upload-time = "2026-11-05T20:30:52.926Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/81/6f/1fa8970e960e5c832874399e6efa564870ade8206d57fef5d5e296b834f5/markdown-3.11.3-py3-none-any.whl", hash = "sha256:e1a31a112232504d753e5c01bb8c2de90d3f0ba986b063e10770cf7695b09e73", size = 116758, upload-time = "2026-11-05T20:30:51.775Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/55/18dbb4778b30ada5ce071608503cc3edc9e14e13d868c17a6d178fc30f7a/markupsafe-3.0.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9e25feb9e330b63edb0278a0acdf85e50d0cb0fbf49c3084abbe4e24ae195346", size = 11520, upload-time = "2026-10-02T23:04:36.299Z" }, + { url = "https://files.pythonhosted.org/packages/6c/14/0b05f79b4733e264a18d08fe08fa1df7347630ff32a6cb82180d9dccec55/markupsafe-3.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7d3391b2188d18737cb2fa147028b1096236eaa7e156446c650a489fa2cadc91", size = 12063, upload-time = "2026-10-02T23:04:37.291Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3a/63ba10b6c1463216b3e4df669a9f0e5a3b0c3071557d2e8229e3968c79fb/markupsafe-3.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849dd2bb0e5e4ab2b71c7191726a4a8d5aa8a610daa584728cbee0b710ddc4ef", size = 24321, upload-time = "2026-10-02T23:04:38.262Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/5f015261b76ad633d187ef6f388b413aedd64a8773c4df59e530a0be5525/markupsafe-3.0.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:befb4158af32106b9a93db8d6d1d1cbbd418c0d5aca0cabb7b1780abf0c89169", size = 28845, upload-time = "2026-10-02T23:04:39.295Z" }, + { url = "https://files.pythonhosted.org/packages/33/cf/26e594b26be40c2f1fec63ccf8a8b99d0335a5b2cbe84835c7d82a994375/markupsafe-3.0.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:71f88e749ea29f67f21f3b36433c1dc54c7729ed2a6d9e2da2e0d9e0d7b224eb", size = 24701, upload-time = "2026-10-02T23:04:40.348Z" }, + { url = "https://files.pythonhosted.org/packages/81/a5/a513b76c139a3915b43404324e55c0b7979ae4f0d39eb6f075b0282e90a8/markupsafe-3.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6da83a088f8ef93b2d483a8232a4dbf4d69d3d8496b568a03c56becac43e1808", size = 22961, upload-time = "2026-10-02T23:04:41.372Z" }, + { url = "https://files.pythonhosted.org/packages/46/cf/4c66192c100b4542bcbe392ae06696b670f66927be3ac38a213234778ff9/markupsafe-3.0.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8f0fac8b13d14bb06c68195f849371924ae53dd7b1c00fed24650f704383b692", size = 21920, upload-time = "2026-10-02T23:04:42.429Z" }, + { url = "https://files.pythonhosted.org/packages/cb/17/ac3662678bfbad649893117ada2ba44dc30bf56884e84f13154a792b10f1/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4a7cdc2a420ca01058182da4253329764d4bfa055564d1eced90e6ba1e8b1d3d", size = 23726, upload-time = "2026-10-02T23:04:43.531Z" }, + { url = "https://files.pythonhosted.org/packages/f7/af/fe47cee339180a69ebca3c57fb3483d0f5cbd1e8337d1871fb1d9c1aebee/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:83b3944fea42a8400edf92fd1770fb8d0d4f7de651353bd2d8525a92dba69a21", size = 22539, upload-time = "2026-10-02T23:04:44.618Z" }, + { url = "https://files.pythonhosted.org/packages/12/32/d55440ba140442800e02d799c9cb5ab597bf6ebdb1177b5ea39a11f797bd/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8138eb83940ec7299024d92d4dee45f601b9e6c5ffde9d25f4e35e326203c707", size = 23963, upload-time = "2026-10-02T23:04:45.656Z" }, + { url = "https://files.pythonhosted.org/packages/50/9d/9c86042cb364c2ad4c971e6d1247929effd25f714cd7ee11b05e6316445b/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:811d02d5122171c1941357efd8f9bf4ffe907b7f0a1a4e729a880e4be3f46e3e", size = 21506, upload-time = "2026-10-02T23:04:46.671Z" }, + { url = "https://files.pythonhosted.org/packages/75/ef/5b824f03ba40c3b3652b6272d083d2fc4fcdd440de519a3a39ba2c3e7262/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:50b5bedc9ed8a94fc8857a42ef4f84a81ea88f8d4f05dc8705fb23ee6d8dcca7", size = 22955, upload-time = "2026-10-02T23:04:47.698Z" }, + { url = "https://files.pythonhosted.org/packages/1e/e8/44cfcb5ea40e5e43cec7793ef90704ed0c475280839076c4345757eb8e59/markupsafe-3.0.4-cp311-cp311-win32.whl", hash = "sha256:2e5a7cd7fdd14fcb1ae5d7d8bf23d24fbd1daefd1fbca2580132e1ea75f098b5", size = 14094, upload-time = "2026-10-02T23:04:48.788Z" }, + { url = "https://files.pythonhosted.org/packages/91/89/f2b509f7bf79352e40117824c1070dbeafd4df67031d3fa98165a3134228/markupsafe-3.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3", size = 14328, upload-time = "2026-10-02T23:04:49.801Z" }, + { url = "https://files.pythonhosted.org/packages/2b/5a/ccf22672a0f64dc682306e288f0dabcb06c7a201f3bb6e6cbf86d9e8ad03/markupsafe-3.0.4-cp311-cp311-win_arm64.whl", hash = "sha256:569d65055d367e3dcdf30c3f41119467b73d9ee9faf332bdf40402644f5ac08e", size = 14188, upload-time = "2026-10-02T23:04:50.847Z" }, +] + +[[package]] +name = "matplotlib" +version = "3.10.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "contourpy" }, + { name = "cycler" }, + { name = "fonttools" }, + { name = "kiwisolver" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "pyparsing" }, + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ae/e2/d2d5295be2f44c678ebaf3544ba32d20c1f9ef08c49fe47f496180e1db15/matplotlib-3.10.7.tar.gz", hash = "sha256:a06ba7e2a2ef9131c79c49e63dad355d2d878413a0376c1727c8b9335ff731c7", size = 34804865, upload-time = "2025-10-09T00:28:00.669Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/bc/0fb489005669127ec13f51be0c6adc074d7cf191075dab1da9fe3b7a3cfc/matplotlib-3.10.7-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:53b492410a6cd66c7a471de6c924f6ede976e963c0f3097a3b7abfadddc67d0a", size = 8257507, upload-time = "2025-10-09T00:26:19.073Z" }, + { url = "https://files.pythonhosted.org/packages/e2/6a/d42588ad895279ff6708924645b5d2ed54a7fb2dc045c8a804e955aeace1/matplotlib-3.10.7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d9749313deb729f08207718d29c86246beb2ea3fdba753595b55901dee5d2fd6", size = 8119565, upload-time = "2025-10-09T00:26:21.023Z" }, + { url = "https://files.pythonhosted.org/packages/10/b7/4aa196155b4d846bd749cf82aa5a4c300cf55a8b5e0dfa5b722a63c0f8a0/matplotlib-3.10.7-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2222c7ba2cbde7fe63032769f6eb7e83ab3227f47d997a8453377709b7fe3a5a", size = 8692668, upload-time = "2025-10-09T00:26:22.967Z" }, + { url = "https://files.pythonhosted.org/packages/e6/e7/664d2b97016f46683a02d854d730cfcf54ff92c1dafa424beebef50f831d/matplotlib-3.10.7-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e91f61a064c92c307c5a9dc8c05dc9f8a68f0a3be199d9a002a0622e13f874a1", size = 9521051, upload-time = "2025-10-09T00:26:25.041Z" }, + { url = "https://files.pythonhosted.org/packages/a8/a3/37aef1404efa615f49b5758a5e0261c16dd88f389bc1861e722620e4a754/matplotlib-3.10.7-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6f1851eab59ca082c95df5a500106bad73672645625e04538b3ad0f69471ffcc", size = 9576878, upload-time = "2025-10-09T00:26:27.478Z" }, + { url = "https://files.pythonhosted.org/packages/33/cd/b145f9797126f3f809d177ca378de57c45413c5099c5990de2658760594a/matplotlib-3.10.7-cp311-cp311-win_amd64.whl", hash = "sha256:6516ce375109c60ceec579e699524e9d504cd7578506f01150f7a6bc174a775e", size = 8115142, upload-time = "2025-10-09T00:26:29.774Z" }, + { url = "https://files.pythonhosted.org/packages/2e/39/63bca9d2b78455ed497fcf51a9c71df200a11048f48249038f06447fa947/matplotlib-3.10.7-cp311-cp311-win_arm64.whl", hash = "sha256:b172db79759f5f9bc13ef1c3ef8b9ee7b37b0247f987fbbbdaa15e4f87fd46a9", size = 7992439, upload-time = "2025-10-09T00:26:40.32Z" }, + { url = "https://files.pythonhosted.org/packages/58/8f/76d5dc21ac64a49e5498d7f0472c0781dae442dd266a67458baec38288ec/matplotlib-3.10.7-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:15112bcbaef211bd663fa935ec33313b948e214454d949b723998a43357b17b0", size = 8252283, upload-time = "2025-10-09T00:27:54.739Z" }, + { url = "https://files.pythonhosted.org/packages/27/0d/9c5d4c2317feb31d819e38c9f947c942f42ebd4eb935fc6fd3518a11eaa7/matplotlib-3.10.7-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d2a959c640cdeecdd2ec3136e8ea0441da59bcaf58d67e9c590740addba2cb68", size = 8116733, upload-time = "2025-10-09T00:27:56.406Z" }, + { url = "https://files.pythonhosted.org/packages/9a/cc/3fe688ff1355010937713164caacf9ed443675ac48a997bab6ed23b3f7c0/matplotlib-3.10.7-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3886e47f64611046bc1db523a09dd0a0a6bed6081e6f90e13806dd1d1d1b5e91", size = 8693919, upload-time = "2025-10-09T00:27:58.41Z" }, +] + +[[package]] +name = "mpmath" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, +] + +[[package]] +name = "multidict" +version = "7.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/6b/29ef8e752f5854dcc267ded0652c475bec99b86f255957a0d4fcad657b18/multidict-7.2.1.tar.gz", hash = "sha256:e8af3e6f1bdbc31fd762b094133b478b89988eaebc63cbe82b1d9e3bbd15cede", size = 369994, upload-time = "2026-10-24T20:41:35.457Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/24/4347a7502ad47cb05a1b8d4e219514b4f0b1e38d4e4734c053c20328949f/multidict-7.2.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:fd24c4425fdb8e822601335602375c6d0cb020f7a368e1d5842eb7925a9c8748", size = 173141, upload-time = "2026-10-24T20:40:02.481Z" }, + { url = "https://files.pythonhosted.org/packages/8d/f2/2a8fcfe4c2c435101f9227b7f7ea81d786ffef993cadd2394e6926020ca9/multidict-7.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cecb2c778f00a65c6ca01410dd194d0e797a9eebb7c6dea0db87718719f293c7", size = 97197, upload-time = "2026-10-24T20:40:06.534Z" }, + { url = "https://files.pythonhosted.org/packages/7a/57/39be4ac4fa9c20e3af7dd7e89adf7dd404b4547fb4453c5c96082e197b9c/multidict-7.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:0d852d3d9638f852158d7de7200dd77f7ff8d77fc8f3d396032f3d847883f631", size = 104843, upload-time = "2026-10-24T20:40:05.829Z" }, + { url = "https://files.pythonhosted.org/packages/63/da/6a5c78daa34e458ced17573b7527395c4c39ebb253220274382d361a1493/multidict-7.2.1-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:76a4f5132b8dc29eb3c768ee9b47e132a1d24fbc2e9259854c01af9beaff1d49", size = 490713, upload-time = "2026-10-24T20:40:41.715Z" }, + { url = "https://files.pythonhosted.org/packages/8a/75/b8252bc6411f7f4b9649b83e143789b7bc1dda44f656b09ce74f894ca027/multidict-7.2.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:295a15ccb8cfde9351dd6062b80af4e839460636b3c46813b4aa443905ded86a", size = 504189, upload-time = "2026-10-24T20:40:04.042Z" }, + { url = "https://files.pythonhosted.org/packages/c0/45/38e8191d0a7c7b56015dfc4c2910b731aa719c5ad3f369b2357567f03434/multidict-7.2.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:987f65f6c9321402bc7012f6c6d09ba501b88ddb1640f5b0b4a19f2caafe24a5", size = 465834, upload-time = "2026-10-24T20:40:08.058Z" }, + { url = "https://files.pythonhosted.org/packages/9f/55/378869573886f7efcac24d2c698938dadf973e0da40b812c8b0df847fc46/multidict-7.2.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:36b868758fb11cfa748c788b793994e73660abec90f83c780a678539c2c468bf", size = 522423, upload-time = "2026-10-24T20:40:07.427Z" }, + { url = "https://files.pythonhosted.org/packages/af/c5/8936fe02c11196994ac05c4876ad62336a66ef353ea2d1a2ca3adce71678/multidict-7.2.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5b944091cfa7da4f7a9bd2587569cd90c94b89ec4721f8e87fe62504f2432b67", size = 544512, upload-time = "2026-10-24T20:40:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/d0/38/b8403d97ae5273002fa664c3c440c5cc186082fa0ba20fcc93885d13a686/multidict-7.2.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3b7542fad2706595c1b1853b46f2c3c4ae5cc5a6252b7225f294d607a29e1bdf", size = 510054, upload-time = "2026-10-24T20:40:05.525Z" }, + { url = "https://files.pythonhosted.org/packages/18/5d/473e1436ea8577cdfb42371c0507a244d51f8d8ef08bea0f9e6e63906478/multidict-7.2.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:363e5db93fc3f65f3218a79fe108d217b9d264181a4e993c77552bfe275d0393", size = 452816, upload-time = "2026-10-24T20:40:09.49Z" }, + { url = "https://files.pythonhosted.org/packages/1e/b7/67376e6821fb28c21de1fb37731efd2e3a6a523bdefc4af6997bd043da7a/multidict-7.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5deadf03fb4a7842696d551f9f9a06dd4445bb43ca06b5f9736e4e1885561333", size = 490712, upload-time = "2026-10-24T20:40:09.097Z" }, + { url = "https://files.pythonhosted.org/packages/1a/89/5144d8b36f133109ff36408089a475b9a3a3c1840176a39a9a8fb67a0000/multidict-7.2.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:0ec95a02f9f08246cc7f1d85ac425e4d5c233fd3f098f5be1b2cca16aa690186", size = 462856, upload-time = "2026-10-24T20:40:44.771Z" }, + { url = "https://files.pythonhosted.org/packages/ff/7f/38310388c4c5e351dfc419a04e4c7a26cde14b0e1019bc72bbd1b0d95613/multidict-7.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:3d6fce7cc4ef63d9a7633cbae43e737798412805a4c3ba876cdf472dc6ff9c51", size = 490108, upload-time = "2026-10-24T20:40:06.965Z" }, + { url = "https://files.pythonhosted.org/packages/ce/0d/94162600e5bbf24bf33398f3b33ae2f78211375313dbdaaf1513b2554a66/multidict-7.2.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:37b161535e92776788957a165fcf38a80b33c1efde7b18cab287db4e4574df78", size = 508935, upload-time = "2026-10-24T20:40:10.882Z" }, + { url = "https://files.pythonhosted.org/packages/1d/40/a0cae932493346cb0d442ffa380e65491fdae8df338d8cdf2f39695c0947/multidict-7.2.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:e47d058c2db95010f5d2e1f6037acebdfb0e2fa4507650e1041437985c91db38", size = 447620, upload-time = "2026-10-24T20:40:10.548Z" }, + { url = "https://files.pythonhosted.org/packages/5e/a5/6ec5cd1c15574aca277ab08920f7e78a6a1e1c15912bfaf59b48683230f7/multidict-7.2.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:7238f7135481926d52a94c18a8cca633a9e72c1cbfccd5796548298a479b0656", size = 523896, upload-time = "2026-10-24T20:40:46.258Z" }, + { url = "https://files.pythonhosted.org/packages/ae/60/d164a2583548561f7e596f13bbd1c3492ea33a77d499d3ceaa2acf76d850/multidict-7.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:c10ac5e3e76837180656079008f71add8339b00c3c26314092bcd1e8e449049f", size = 502961, upload-time = "2026-10-24T20:40:08.732Z" }, + { url = "https://files.pythonhosted.org/packages/30/6b/474aee537e0c87210ce8f4fd21558b461e8a8e74c79440de036022a9eeda/multidict-7.2.1-cp311-cp311-win32.whl", hash = "sha256:2b4d0c4e13d329ffee73d46128e32dd3b4aeb2f9c6ac9c8a89eb28d3b82dcea8", size = 84159, upload-time = "2026-10-24T20:40:12.222Z" }, + { url = "https://files.pythonhosted.org/packages/1f/02/41d769148f32c9bd535fd0ddd946c4e42f38acaddf7899f3bf49d9e67703/multidict-7.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:a789e3d27fc5665cc0477f10a35a89383313e4c9cf8b5e6af7ea71f039cdcc0e", size = 94895, upload-time = "2026-10-24T20:40:12.036Z" }, + { url = "https://files.pythonhosted.org/packages/23/be/e04fcf29542d0db25cdec79acbe5662481c3ba6b760353c393f9c46156f2/multidict-7.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:2022bd3194968a027f64ed16f9779e62e71a823a9df3971a7328c1d45dfeb9ab", size = 92384, upload-time = "2026-10-24T20:40:47.827Z" }, + { url = "https://files.pythonhosted.org/packages/9d/96/1aaad0e5df33f1f5af21775c411349c0234a6edd581ea403bc81919a6eab/multidict-7.2.1-py3-none-any.whl", hash = "sha256:08ea94663d9e7c25d14d78222f7aee906c472d4837766bec62477c38f6e419dc", size = 28145, upload-time = "2026-10-24T20:40:59.159Z" }, +] + +[[package]] +name = "multiprocess" +version = "0.70.16" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dill" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b5/ae/04f39c5d0d0def03247c2893d6f2b83c136bf3320a2154d7b8858f2ba72d/multiprocess-0.70.16.tar.gz", hash = "sha256:161af703d4652a0e1410be6abccecde4a7ddffd19341be0a7011b94aeb171ac1", size = 1772603, upload-time = "2024-01-28T18:52:34.85Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/f7/7ec7fddc92e50714ea3745631f79bd9c96424cb2702632521028e57d3a36/multiprocess-0.70.16-py310-none-any.whl", hash = "sha256:c4a9944c67bd49f823687463660a2d6daae94c289adff97e0f9d696ba6371d02", size = 134824, upload-time = "2024-01-28T18:52:26.062Z" }, + { url = "https://files.pythonhosted.org/packages/50/15/b56e50e8debaf439f44befec5b2af11db85f6e0f344c3113ae0be0593a91/multiprocess-0.70.16-py311-none-any.whl", hash = "sha256:af4cabb0dac72abfb1e794fa7855c325fd2b55a10a44628a3c1ad3311c04127a", size = 143519, upload-time = "2024-01-28T18:52:28.115Z" }, + { url = "https://files.pythonhosted.org/packages/ea/89/38df130f2c799090c978b366cfdf5b96d08de5b29a4a293df7f7429fa50b/multiprocess-0.70.16-py38-none-any.whl", hash = "sha256:a71d82033454891091a226dfc319d0cfa8019a4e888ef9ca910372a446de4435", size = 132628, upload-time = "2024-01-28T18:52:30.853Z" }, + { url = "https://files.pythonhosted.org/packages/da/d9/f7f9379981e39b8c2511c9e0326d212accacb82f12fbfdc1aa2ce2a7b2b6/multiprocess-0.70.16-py39-none-any.whl", hash = "sha256:a0bafd3ae1b732eac64be2e72038231c1ba97724b60b09400d68f229fcc2fbf3", size = 133351, upload-time = "2024-01-28T18:52:31.981Z" }, +] + +[[package]] +name = "networkx" +version = "3.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c9/b2622292ea83fbb4ec318f5b9ab867d0a28ab43c5717bb85b0a5f6b3b0a4/networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762", size = 2068504, upload-time = "2025-12-08T17:02:38.159Z" }, +] + +[[package]] +name = "nltk" +version = "3.9.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "joblib" }, + { name = "regex" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f9/76/3a5e4312c19a028770f86fd7c058cf9f4ec4321c6cf7526bab998a5b683c/nltk-3.9.2.tar.gz", hash = "sha256:0f409e9b069ca4177c1903c3e843eef90c7e92992fa4931ae607da6de49e1419", size = 2887629, upload-time = "2025-10-01T07:19:23.764Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/90/81ac364ef94209c100e12579629dc92bf7a709a84af32f8c551b02c07e94/nltk-3.9.2-py3-none-any.whl", hash = "sha256:1e209d2b3009110635ed9709a67a1a3e33a10f799490fa71cf4bec218c11c88a", size = 1513404, upload-time = "2025-10-01T07:19:21.648Z" }, +] + +[[package]] +name = "numpy" +version = "1.26.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/65/6e/09db70a523a96d25e115e71cc56a6f9031e7b8cd166c1ac8438307c14058/numpy-1.26.4.tar.gz", hash = "sha256:2a02aba9ed12e4ac4eb3ea9421c420301a0c6460d9830d74a9df87efa4912010", size = 15786129, upload-time = "2024-02-06T00:26:44.495Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/57/baae43d14fe163fa0e4c47f307b6b2511ab8d7d30177c491960504252053/numpy-1.26.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4c66707fabe114439db9068ee468c26bbdf909cac0fb58686a42a24de1760c71", size = 20630554, upload-time = "2024-02-05T23:51:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/151484f49fd03944c4a3ad9c418ed193cfd02724e138ac8a9505d056c582/numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:edd8b5fe47dab091176d21bb6de568acdd906d1887a4584a15a9a96a1dca06ef", size = 13997127, upload-time = "2024-02-05T23:52:15.314Z" }, + { url = "https://files.pythonhosted.org/packages/79/ae/7e5b85136806f9dadf4878bf73cf223fe5c2636818ba3ab1c585d0403164/numpy-1.26.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7ab55401287bfec946ced39700c053796e7cc0e3acbef09993a9ad2adba6ca6e", size = 14222994, upload-time = "2024-02-05T23:52:47.569Z" }, + { url = "https://files.pythonhosted.org/packages/3a/d0/edc009c27b406c4f9cbc79274d6e46d634d139075492ad055e3d68445925/numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:666dbfb6ec68962c033a450943ded891bed2d54e6755e35e5835d63f4f6931d5", size = 18252005, upload-time = "2024-02-05T23:53:15.637Z" }, + { url = "https://files.pythonhosted.org/packages/09/bf/2b1aaf8f525f2923ff6cfcf134ae5e750e279ac65ebf386c75a0cf6da06a/numpy-1.26.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:96ff0b2ad353d8f990b63294c8986f1ec3cb19d749234014f4e7eb0112ceba5a", size = 13885297, upload-time = "2024-02-05T23:53:42.16Z" }, + { url = "https://files.pythonhosted.org/packages/df/a0/4e0f14d847cfc2a633a1c8621d00724f3206cfeddeb66d35698c4e2cf3d2/numpy-1.26.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:60dedbb91afcbfdc9bc0b1f3f402804070deed7392c23eb7a7f07fa857868e8a", size = 18093567, upload-time = "2024-02-05T23:54:11.696Z" }, + { url = "https://files.pythonhosted.org/packages/d2/b7/a734c733286e10a7f1a8ad1ae8c90f2d33bf604a96548e0a4a3a6739b468/numpy-1.26.4-cp311-cp311-win32.whl", hash = "sha256:1af303d6b2210eb850fcf03064d364652b7120803a0b872f5211f5234b399f20", size = 5968812, upload-time = "2024-02-05T23:54:26.453Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6b/5610004206cf7f8e7ad91c5a85a8c71b2f2f8051a0c0c4d5916b76d6cbb2/numpy-1.26.4-cp311-cp311-win_amd64.whl", hash = "sha256:cd25bcecc4974d09257ffcd1f098ee778f7834c3ad767fe5db785be9a4aa9cb2", size = 15811913, upload-time = "2024-02-05T23:54:53.933Z" }, +] + +[[package]] +name = "nvidia-cublas" +version = "13.1.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cuda-nvrtc", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" }, + { url = "https://files.pythonhosted.org/packages/3b/cd/154ca20c38269e05eff77c1464e6c1da89f50a6390b565e9d82e06bc11e1/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:37936a16db8fe4ac1f065c2139360608a543a09275cb1a1af612e08cfa065436", size = 423138758, upload-time = "2026-04-08T18:46:58.655Z" }, + { url = "https://files.pythonhosted.org/packages/45/9e/2f562daf80eb8f7a685fb7bea4fda71f6048e4f359d6fdd1b6e70206cb2f/nvidia_cublas-13.1.1.3-py3-none-win_amd64.whl", hash = "sha256:b6cdce694e47ff6aadf0a69df1cab6628d696f5ff56e8d16af50309d855fa20f", size = 404358158, upload-time = "2026-04-08T18:47:26.987Z" }, +] + +[[package]] +name = "nvidia-cuda-cupti" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/2a/80353b103fc20ce05ef51e928daed4b6015db4aaa9162ed0997090fe2250/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_aarch64.whl", hash = "sha256:796bd679890ee55fb14a94629b698b6db54bcfd833d391d5e94017dd9d7d3151", size = 10310827, upload-time = "2025-09-04T08:26:42.012Z" }, + { url = "https://files.pythonhosted.org/packages/33/6d/737d164b4837a9bbd202f5ae3078975f0525a55730fe871d8ed4e3b952b0/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_x86_64.whl", hash = "sha256:4eb01c08e859bf924d222250d2e8f8b8ff6d3db4721288cf35d14252a4d933c8", size = 10715597, upload-time = "2025-09-04T08:26:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/ad/df/b74b10025c1205695c5676373f2edd3e87a7202cc62ead0dfbc373b0f6ea/nvidia_cuda_cupti-13.0.85-py3-none-win_amd64.whl", hash = "sha256:683f58d301548deeefcb8f6fac1b8d907691b9d8b18eccab417f51e362102f00", size = 7736776, upload-time = "2025-09-04T08:38:08.38Z" }, +] + +[[package]] +name = "nvidia-cuda-nvrtc" +version = "13.0.88" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/68/483a78f5e8f31b08fb1bb671559968c0ca3a065ac7acabfc7cee55214fd6/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:ad9b6d2ead2435f11cbb6868809d2adeeee302e9bb94bcf0539c7a40d80e8575", size = 90215200, upload-time = "2025-09-04T08:28:44.204Z" }, + { url = "https://files.pythonhosted.org/packages/b7/dc/6bb80850e0b7edd6588d560758f17e0550893a1feaf436807d64d2da040f/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d27f20a0ca67a4bb34268a5e951033496c5b74870b868bacd046b1b8e0c3267b", size = 43015449, upload-time = "2025-09-04T08:28:20.239Z" }, + { url = "https://files.pythonhosted.org/packages/4a/af/345fedb9f4c76c84ab4fa445b36bd4048a4d9db60e6bc76b4f913ff4b852/nvidia_cuda_nvrtc-13.0.88-py3-none-win_amd64.whl", hash = "sha256:6bcd4e7f8e205cbe644f5a98f2f799bef9556fefc89dd786e79a16312ce49872", size = 76807835, upload-time = "2025-09-04T08:39:15.274Z" }, +] + +[[package]] +name = "nvidia-cuda-runtime" +version = "13.0.96" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/4f/17d7b9b8e285199c58ce28e31b5c5bbaa4d8271af06a89b6405258245de2/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ef9bcbe90493a2b9d810e43d249adb3d02e98dd30200d86607d8d02687c43f55", size = 2261060, upload-time = "2025-10-09T08:55:15.78Z" }, + { url = "https://files.pythonhosted.org/packages/2e/24/d1558f3b68b1d26e706813b1d10aa1d785e4698c425af8db8edc3dced472/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7f82250d7782aa23b6cfe765ecc7db554bd3c2870c43f3d1821f1d18aebf0548", size = 2243632, upload-time = "2025-10-09T08:55:36.117Z" }, + { url = "https://files.pythonhosted.org/packages/b7/94/6b867483bec07da24ffa32736c79fabb94ef3a7af4d787a9d4a974868576/nvidia_cuda_runtime-13.0.96-py3-none-win_amd64.whl", hash = "sha256:f79298c8a098cec150a597c8eba58ecdab96e3bdc4b9bc4f9983635031740492", size = 2927037, upload-time = "2025-10-09T09:04:23.782Z" }, +] + +[[package]] +name = "nvidia-cudnn-cu13" +version = "9.20.0.48" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cublas", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/c5/83384d846b2fd17c44bd499b36c75a45ed4f095fbbb2252294e89cea5c5c/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:e31454ae00094b0c55319d9d15b6fa2fc50a9e1c0f5c8c80fb75258234e731e1", size = 444574296, upload-time = "2026-03-09T19:28:27.751Z" }, + { url = "https://files.pythonhosted.org/packages/6e/5e/edb9c0ae051602c3ccaffe424256463636d639e27d7f302dde9975ef9e7a/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0c45dd8eeb50b603f07995b1b300c62ffe6a1980482b82b3bcf94a4ca9d49304", size = 366173588, upload-time = "2026-03-09T19:29:34.474Z" }, + { url = "https://files.pythonhosted.org/packages/78/39/21507455b1bca8b5702a9e9fc6ce73735f216f558dac2c9ede58e4d456b8/nvidia_cudnn_cu13-9.20.0.48-py3-none-win_amd64.whl", hash = "sha256:af8139732b99c0118be65ea5aac97f0d46018f8c552889e49d2fb0c6261a4a24", size = 350712614, upload-time = "2026-03-09T19:31:11.398Z" }, +] + +[[package]] +name = "nvidia-cufft" +version = "12.0.0.61" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, + { url = "https://files.pythonhosted.org/packages/a8/2f/7b57e29836ea8714f81e9898409196f47d772d5ddedddf1592eadb8ab743/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6c44f692dce8fd5ffd3e3df134b6cdb9c2f72d99cf40b62c32dde45eea9ddad3", size = 214085489, upload-time = "2025-09-04T08:31:56.044Z" }, + { url = "https://files.pythonhosted.org/packages/85/b2/f8af21a2ed1beed337a6a02c5a28aeb85441f4d578ec3d529543c775ea4b/nvidia_cufft-12.0.0.61-py3-none-win_amd64.whl", hash = "sha256:2abce5b39d2f5ae12730fb7e5db6696533e36c26e2d3e8fd1750bdd2853364eb", size = 213342123, upload-time = "2025-09-04T08:40:51.145Z" }, +] + +[[package]] +name = "nvidia-cufile" +version = "1.15.1.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/70/4f193de89a48b71714e74602ee14d04e4019ad36a5a9f20c425776e72cd6/nvidia_cufile-1.15.1.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:08a3ecefae5a01c7f5117351c64f17c7c62efa5fffdbe24fc7d298da19cd0b44", size = 1223672, upload-time = "2025-09-04T08:32:22.779Z" }, + { url = "https://files.pythonhosted.org/packages/ab/73/cc4a14c9813a8a0d509417cf5f4bdaba76e924d58beb9864f5a7baceefbf/nvidia_cufile-1.15.1.6-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:bdc0deedc61f548bddf7733bdc216456c2fdb101d020e1ab4b88d232d5e2f6d1", size = 1136992, upload-time = "2025-09-04T08:32:14.119Z" }, +] + +[[package]] +name = "nvidia-curand" +version = "10.4.0.35" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/72/7c2ae24fb6b63a32e6ae5d241cc65263ea18d08802aaae087d9f013335a2/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:133df5a7509c3e292aaa2b477afd0194f06ce4ea24d714d616ff36439cee349a", size = 61962106, upload-time = "2025-08-04T10:21:41.128Z" }, + { url = "https://files.pythonhosted.org/packages/a5/9f/be0a41ca4a4917abf5cb9ae0daff1a6060cc5de950aec0396de9f3b52bc5/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:1aee33a5da6e1db083fe2b90082def8915f30f3248d5896bcec36a579d941bfc", size = 59544258, upload-time = "2025-08-04T10:22:03.992Z" }, + { url = "https://files.pythonhosted.org/packages/99/27/72103153b1ffc00e09fdc40ac970235343dcd1ea8bd762e84d2d73219ffa/nvidia_curand-10.4.0.35-py3-none-win_amd64.whl", hash = "sha256:65b1710aa6961d326b411e314b374290904c5ddf41dc3f766ebc3f1d7d4ca69f", size = 55242481, upload-time = "2025-08-04T10:30:41.831Z" }, +] + +[[package]] +name = "nvidia-cusolver" +version = "12.0.4.66" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cublas", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-cusparse", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, + { url = "https://files.pythonhosted.org/packages/5f/67/cba3777620cdacb99102da4042883709c41c709f4b6323c10781a9c3aa34/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0a759da5dea5c0ea10fd307de75cdeb59e7ea4fcb8add0924859b944babf1112", size = 200941980, upload-time = "2025-09-04T08:33:22.767Z" }, + { url = "https://files.pythonhosted.org/packages/99/ef/332a0101260ca78a1daef046bf0b06199e8ed4dac1d2aa698289c358169c/nvidia_cusolver-12.0.4.66-py3-none-win_amd64.whl", hash = "sha256:16515bd33a8e76bb54d024cfa068fa68d30e80fc34b9e1090813ea9362e0cb65", size = 193551444, upload-time = "2025-09-04T08:41:46.813Z" }, +] + +[[package]] +name = "nvidia-cusparse" +version = "12.6.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, + { url = "https://files.pythonhosted.org/packages/fa/18/623c77619c31d62efd55302939756966f3ecc8d724a14dab2b75f1508850/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2b3c89c88d01ee0e477cb7f82ef60a11a4bcd57b6b87c33f789350b59759360b", size = 145942937, upload-time = "2025-09-04T08:33:58.029Z" }, + { url = "https://files.pythonhosted.org/packages/02/b0/b043d6f3480f102f885cf87fc3ffd3edcb5e23b855025a50e2ef4d059185/nvidia_cusparse-12.6.3.3-py3-none-win_amd64.whl", hash = "sha256:cbcf42feb737bd7ec15b4c0a63e62351886bd3f975027b8815d7f720a2b5ea79", size = 143783033, upload-time = "2025-09-04T08:42:12.391Z" }, +] + +[[package]] +name = "nvidia-cusparselt-cu13" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/e1/cdc1797eadf82d3a9a575a19b33fdc871a97edbec42c00b5b5e914f4aff4/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:4dca476c50bf4780d46cd0bfbd82e2bc10a08e4fef7950917ce8d7578d22a23f", size = 221051344, upload-time = "2025-09-05T18:49:51.289Z" }, + { url = "https://files.pythonhosted.org/packages/34/7d/2661f2fb3ac4302f3a246f5fc030213ac60c1fe0bce84f9783dbd831dbb7/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:786ce87568c303fadb5afcc7102d454cd3040d75f6f8626f5db460d1871f4dd0", size = 170148586, upload-time = "2025-09-05T18:50:50.248Z" }, + { url = "https://files.pythonhosted.org/packages/31/83/f3647ce26916c94a6ca4ff1810623e2c405cff2dea6e78d29516b2514df9/nvidia_cusparselt_cu13-0.8.1-py3-none-win_amd64.whl", hash = "sha256:dccbd362f91a7b9024d1f55ee9f548ac065027ff15d8c8b0db889ab3a8f31215", size = 156885108, upload-time = "2025-09-05T18:51:35.958Z" }, +] + +[[package]] +name = "nvidia-nccl-cu13" +version = "2.29.7" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/0d/daf50d44177ee0cbc7ff0a0c91eb5ff676c82be42f9a970bc7597f440c3a/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_aarch64.whl", hash = "sha256:674a12383e3c38a1bcccae7d4f3633b37852230b6047883cb2f4c2d1b36d9bf5", size = 206014712, upload-time = "2026-03-03T05:34:20.843Z" }, + { url = "https://files.pythonhosted.org/packages/67/f4/58e4e91b6919367c7aafb8e36fce9aad1a3047e536bf7e2fd560927d3a4c/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:edd81538446786ec3b73972543e53bb43bcaf0bfc8ef76cb679fcc390ffe136d", size = 205976000, upload-time = "2026-03-03T05:36:24.472Z" }, +] + +[[package]] +name = "nvidia-nvjitlink" +version = "13.5.37" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cc/1f/2321702b8d60b4b4dd18b957f61612dbac9cb1c07e940cf6582106b7c8b8/nvidia_nvjitlink-13.5.37-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:280d7cb9649704145f074b8dbde500de04ce02d0872e066e20a83c17bcaa93eb", size = 46642491, upload-time = "2026-11-04T23:33:31.696Z" }, + { url = "https://files.pythonhosted.org/packages/24/15/dd228f798cd01d7aeaf19d872b2b20f9aeafc1a7d8b6bfaa878b30b8d6f7/nvidia_nvjitlink-13.5.37-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:893f6f9a55b2720ed94913b5ba3332e972da8c78dfa2863d0244403dbd528ffc", size = 45253761, upload-time = "2026-11-04T23:33:22.854Z" }, + { url = "https://files.pythonhosted.org/packages/a7/53/c43398492e8374880d5e01c23c4dac33ba0c3bd03515d6ecc574254c0967/nvidia_nvjitlink-13.5.37-py3-none-win_amd64.whl", hash = "sha256:4465d4e8f2212118220b580c82523c5654f93a62906bd51d29d79bdfc12376c1", size = 41467665, upload-time = "2026-11-04T23:38:44.689Z" }, + { url = "https://files.pythonhosted.org/packages/d7/4a/1ff9ab7d0c961a1b5539f8291c881bea82adbbf8ba40a9e81f9c9b3a8d5d/nvidia_nvjitlink-13.5.37-py3-none-win_arm64.whl", hash = "sha256:eb30348ae64c525180a280025dd12a089c3e2e1dc4e19cdd58f68c6edc622404", size = 38552904, upload-time = "2026-11-04T23:43:27.658Z" }, +] + +[[package]] +name = "nvidia-nvshmem-cu13" +version = "3.4.5" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/0f/05cc9c720236dcd2db9c1ab97fff629e96821be2e63103569da0c9b72f19/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dc2a197f38e5d0376ad52cd1a2a3617d3cdc150fd5966f4aee9bcebb1d68fe9", size = 60215947, upload-time = "2025-09-06T00:32:20.022Z" }, + { url = "https://files.pythonhosted.org/packages/3c/35/a9bf80a609e74e3b000fef598933235c908fcefcef9026042b8e6dfde2a9/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:290f0a2ee94c9f3687a02502f3b9299a9f9fe826e6d0287ee18482e78d495b80", size = 60412546, upload-time = "2025-09-06T00:32:41.564Z" }, +] + +[[package]] +name = "nvidia-nvtx" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c2/f3/d86c845465a2723ad7e1e5c36dcd75ddb82898b3f53be47ebd429fb2fa5d/nvidia_nvtx-13.0.85-py3-none-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4936d1d6780fbe68db454f5e72a42ff64d1fd6397df9f363ae786930fd5c1cd4", size = 148047, upload-time = "2025-09-04T08:29:01.761Z" }, + { url = "https://files.pythonhosted.org/packages/a8/64/3708a90d1ebe202ffdeb7185f878a3c84d15c2b2c31858da2ce0583e2def/nvidia_nvtx-13.0.85-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb7780edb6b14107373c835bf8b72e7a178bac7367e23da7acb108f973f157a6", size = 148878, upload-time = "2025-09-04T08:28:53.627Z" }, + { url = "https://files.pythonhosted.org/packages/d2/50/0e2220f8620a177de994211186ffc5bfa9f2ce1e1282797f8f90096f9f88/nvidia_nvtx-13.0.85-py3-none-win_amd64.whl", hash = "sha256:d66ea44254dd3c6eacc300047af6e1288d2269dd072b417e0adffbf479e18519", size = 137066, upload-time = "2025-09-04T08:39:25.649Z" }, +] + +[[package]] +name = "official-loren-experiment" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "bitsandbytes" }, + { name = "einops" }, + { name = "lightning" }, + { name = "loguru" }, + { name = "loralib" }, + { name = "matplotlib" }, + { name = "nltk" }, + { name = "numpy" }, + { name = "peft" }, + { name = "psutil" }, + { name = "rouge" }, + { name = "scikit-learn" }, + { name = "sentencepiece" }, + { name = "setuptools" }, + { name = "tensorboard" }, + { name = "tensorboardx" }, + { name = "termcolor" }, + { name = "torch" }, + { name = "torchmetrics" }, + { name = "wandb" }, +] + +[package.dev-dependencies] +modern = [ + { name = "accelerate" }, + { name = "datasets", version = "3.6.0", source = { registry = "https://pypi.org/simple" } }, + { name = "huggingface-hub" }, + { name = "pyarrow", version = "20.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "transformers", version = "4.57.1", source = { registry = "https://pypi.org/simple" } }, +] +native = [ + { name = "accelerate" }, + { name = "datasets", version = "2.21.0", source = { registry = "https://pypi.org/simple" } }, + { name = "huggingface-hub" }, + { name = "pyarrow", version = "17.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "transformers", version = "4.44.2", source = { registry = "https://pypi.org/simple" } }, +] + +[package.metadata] +requires-dist = [ + { name = "bitsandbytes", specifier = "==0.48.2" }, + { name = "einops", specifier = "==0.8.1" }, + { name = "lightning", specifier = "==2.5.6" }, + { name = "loguru", specifier = "==0.7.3" }, + { name = "loralib", specifier = "==0.1.2" }, + { name = "matplotlib", specifier = "==3.10.7" }, + { name = "nltk", specifier = "==3.9.2" }, + { name = "numpy", specifier = "==1.26.4" }, + { name = "peft", specifier = "==0.13.2" }, + { name = "psutil", specifier = "==7.1.3" }, + { name = "rouge", specifier = "==1.0.1" }, + { name = "scikit-learn", specifier = "==1.7.2" }, + { name = "sentencepiece", specifier = "==0.2.1" }, + { name = "setuptools", specifier = "==80.9.0" }, + { name = "tensorboard", specifier = "==2.20.0" }, + { name = "tensorboardx", specifier = "==2.6.4" }, + { name = "termcolor", specifier = "==3.2.0" }, + { name = "torch", specifier = "==2.13.0" }, + { name = "torchmetrics", specifier = "==1.8.2" }, + { name = "wandb", specifier = "==0.23.1" }, +] + +[package.metadata.requires-dev] +modern = [ + { name = "accelerate", specifier = "==1.12.0" }, + { name = "datasets", specifier = "==3.6.0" }, + { name = "huggingface-hub", specifier = "==0.36.0" }, + { name = "pyarrow", specifier = "==20.0.0" }, + { name = "transformers", specifier = "==4.57.1" }, +] +native = [ + { name = "accelerate", specifier = "==1.12.0" }, + { name = "datasets", specifier = "==2.21.0" }, + { name = "huggingface-hub", specifier = "==0.36.0" }, + { name = "pyarrow", specifier = "==17.0.0" }, + { name = "transformers", specifier = "==4.44.2" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pandas" +version = "3.0.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e2/17/d7b106e05bfa642e8694451e7d3d759c6a241c5386a5d962e4f66c047e06/pandas-3.0.6.tar.gz", hash = "sha256:66b07ef7315a31bfe1089cd3d71a7de781c9dca986762d0b4fe7c0ef17465d10", size = 4667686, upload-time = "2026-09-17T23:23:18.345Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7d/48/88e8d250d28efa8163294f6809a71683c7ee67f63ac7c33021c0503b3547/pandas-3.0.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:085e3786ae6b2e82b406266bce36690f72b9dc1421903ba9296b2981a9fcf586", size = 10391798, upload-time = "2026-09-17T23:20:20.96Z" }, + { url = "https://files.pythonhosted.org/packages/55/a6/39db5d41f3eb5d7846626312cb30e0cea48e988fc47a3725698bc931ad3c/pandas-3.0.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d7564d86a94c2eb8ab290b07f63ddaae5c032fa53897c29a2ff2197d43aee8af", size = 10023718, upload-time = "2026-09-17T23:20:25.094Z" }, + { url = "https://files.pythonhosted.org/packages/54/b7/707e966129f77ee8a39d41a41bbd989b790b3fef581c6e26b821315cba6b/pandas-3.0.6-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e7c0afdcaf6661d795fcefc2f647ddd1136f62cdc153fba177c685d97a87808", size = 10612800, upload-time = "2026-09-17T23:20:27.99Z" }, + { url = "https://files.pythonhosted.org/packages/63/be/dfb6cc9329d0bbe76dadda8a1113d026bb996ec76c509221368dc68349f4/pandas-3.0.6-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:47121f9571503f724c9b93e297ab6254ac99c77adf5e9ed085ea419fd585c258", size = 11108900, upload-time = "2026-09-17T23:20:30.65Z" }, + { url = "https://files.pythonhosted.org/packages/1a/6f/3d58f15bbe972f3d7bfa13ee06d731785a76fe8d232c92b2655a8de14127/pandas-3.0.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:994a79608263fe1c14cc48ffa7300e2b834b7d1cb406ffe96a08828cb0cdd79b", size = 11630226, upload-time = "2026-09-17T23:20:33.582Z" }, + { url = "https://files.pythonhosted.org/packages/58/54/9b494de4a3dd92fc6eb19187db1b21afb50fdc21962f32ea1aca9f270cb2/pandas-3.0.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a3a22e07fe75347eaacc75b0e85297947af4fba6b4aae23916bd8b6828d0bba3", size = 12146942, upload-time = "2026-09-17T23:20:36.792Z" }, + { url = "https://files.pythonhosted.org/packages/d3/dc/d2df02854aec5d47659acfb2be352eecc691845b2f86e99c84f1010a8671/pandas-3.0.6-cp311-cp311-win_amd64.whl", hash = "sha256:2e5fa32ff162dfdbc280157d664f44d23049ae414725af9676df339c501d82cd", size = 9859246, upload-time = "2026-09-17T23:20:43.976Z" }, + { url = "https://files.pythonhosted.org/packages/79/1e/2a30df0d7dede5c195300a1820b0bc21cea3aa24e4c8b6c4431565ecc79a/pandas-3.0.6-cp311-cp311-win_arm64.whl", hash = "sha256:5e75072773c1b2f7cb63faa3a6f562aede11f3976f68ed34cb538bc091a28171", size = 9106923, upload-time = "2026-09-17T23:20:46.611Z" }, +] + +[[package]] +name = "peft" +version = "0.13.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "accelerate" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyyaml" }, + { name = "safetensors" }, + { name = "torch" }, + { name = "tqdm" }, + { name = "transformers", version = "4.44.2", source = { registry = "https://pypi.org/simple" }, marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "transformers", version = "4.57.1", source = { registry = "https://pypi.org/simple" }, marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/97/e1/aab80b861b4c18e85482940d504b3a7ee525bdf6ed93a1a2871881a180f1/peft-0.13.2.tar.gz", hash = "sha256:0e0cbd40ebdf5fe4ea79f255880d02f96712d18899509369a2cc5768ad46d672", size = 350390, upload-time = "2024-10-11T11:42:21.874Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/9d/5f95bfb298c8d3b4e3a107701f9a4e7774a0d4d1f8eb0c9d5420b80f7c9d/peft-0.13.2-py3-none-any.whl", hash = "sha256:d4e0951ec78eac11c45a051801c569913436888c578d48e5ce86996b715bc6ef", size = 320731, upload-time = "2024-10-11T11:42:18.905Z" }, +] + +[[package]] +name = "pillow" +version = "13.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/d7/af6af1b8cc55e07cb0489d5b0950bf5a9bb1461eeba825700b6d8d0e26ea/pillow-13.0.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb", size = 5592324, upload-time = "2026-10-16T22:15:24.672Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d2/2c12cb4fbb5d95f38d1001ff3d95fafcb830077018cba40e56a8f932dfbc/pillow-13.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061", size = 4856298, upload-time = "2026-10-16T22:15:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/229b27472483a4801ea94990815e710391836afdf987b4b722b62bd75db6/pillow-13.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0", size = 6517304, upload-time = "2026-10-16T22:15:29.43Z" }, + { url = "https://files.pythonhosted.org/packages/36/46/f509b74787f40ce0627501089d630b2c741b63b244c1f40b640b3b01e181/pillow-13.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c", size = 7140667, upload-time = "2026-10-16T22:15:31.368Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/5a398b8ec2c37145397d6461c0b551c23ec03072aa64f357aed25e582b00/pillow-13.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f", size = 6610583, upload-time = "2026-10-16T22:15:34.025Z" }, + { url = "https://files.pythonhosted.org/packages/4f/7b/f2f1109b230fd4e2d57ab2305de31adc37ea9b4ff8719436c623cb484415/pillow-13.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806", size = 7218241, upload-time = "2026-10-16T22:15:36.214Z" }, + { url = "https://files.pythonhosted.org/packages/ab/d3/069edb9083b267746baf59756282cacef904d3475c5288c7216fb5195a98/pillow-13.0.0-cp311-cp311-win32.whl", hash = "sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5", size = 6515278, upload-time = "2026-10-16T22:15:38.129Z" }, + { url = "https://files.pythonhosted.org/packages/7d/f6/6e2d96413e4c9dbec12ea584d9e646d602877d4cce3ea669099f959deac6/pillow-13.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3", size = 7278471, upload-time = "2026-10-16T22:15:40.286Z" }, + { url = "https://files.pythonhosted.org/packages/70/e7/baff21f8cb60496c8c250609501b88919eeedb4088d3da106f6c62f3f3c0/pillow-13.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13", size = 2698981, upload-time = "2026-10-16T22:15:42.637Z" }, + { url = "https://files.pythonhosted.org/packages/68/c0/fb7b1caf25ed5ac5d46116f09b8b0706b9559833c65c667cecb1a53153f2/pillow-13.0.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca", size = 5521630, upload-time = "2026-10-16T22:17:50.008Z" }, + { url = "https://files.pythonhosted.org/packages/1a/e6/4d11d5b1137f4fc080605cce410cfaae4f303ad400bdec75d27d3083fa29/pillow-13.0.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039", size = 4806023, upload-time = "2026-10-16T22:17:51.932Z" }, + { url = "https://files.pythonhosted.org/packages/f1/45/0923202a658e8ff6aafd72c1a4395ebadcdebaa182c437d8595d3dd3db32/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad", size = 5464831, upload-time = "2026-10-16T22:17:53.742Z" }, + { url = "https://files.pythonhosted.org/packages/07/52/d3e38f0cad1dadea2a658b9a7d6ba8a04048f5ae14f011b806e5c3bd6bcb/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2", size = 6043133, upload-time = "2026-10-16T22:17:55.625Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f9/2ed7685980c1d64f8131a7d87a19c369424747577152622b73ddeff163b7/pillow-13.0.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c", size = 7365208, upload-time = "2026-10-16T22:17:57.509Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.14.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/9a/8475be631fb33ca1466915e70fd594c42a4e84b512db650eaa14f90fe75d/platformdirs-4.14.5.tar.gz", hash = "sha256:32e9921db7385aa8169bee4fe9501923e5715ba9fb7ea3b9c69b0d8e0639f7a1", size = 71464, upload-time = "2026-11-04T16:54:50.358Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7c/ae/ecbbbfd0e4343a6a521d49b3c8656fb4643dee2a4f6eaf941cf3280391a8/platformdirs-4.14.5-py3-none-any.whl", hash = "sha256:8e778c6fa421516f4d3369449f8df3b0e1b72c0e0005fe88e3ec772d0a14e750", size = 35402, upload-time = "2026-11-04T16:54:48.875Z" }, +] + +[[package]] +name = "propcache" +version = "0.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b3/9a/9fbf4e4ec0c2d7f1c32519fff782ef467859b8faa9fbc5331a96f6395d43/propcache-0.5.4.tar.gz", hash = "sha256:ff6b113f50bc066a698db5d944d2c6dc7507168dd3341e255a8892fd0715a558", size = 61545, upload-time = "2026-09-16T00:17:14.386Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/40/14b21e505b7921617466576423f188a5c9caddfdaa1cf4b2b8a83d8fe216/propcache-0.5.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:897d1ddf6716e8f47200f7aad9a0efa6cc7586df66c6defa572f9eab379c078e", size = 86393, upload-time = "2026-09-16T00:14:06.9Z" }, + { url = "https://files.pythonhosted.org/packages/e7/4b/5a52e1a7b43563f7d408814194bb23cc8bf214eb6b86639b667a33a8d0d0/propcache-0.5.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9cbfff4423eef4cc6cafc021469641a2b835f610b2647a6c5281903e21b8670d", size = 50431, upload-time = "2026-09-16T00:14:08.025Z" }, + { url = "https://files.pythonhosted.org/packages/05/cf/b5248180bf056cc76acc60c9c6e8c0ebbfdbd1c6cffd31fd14996927b7c8/propcache-0.5.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3fc24f209c1b7f7f688b66b98293954f5504279760999b58920ee12dd8471c1d", size = 52116, upload-time = "2026-09-16T00:14:09.114Z" }, + { url = "https://files.pythonhosted.org/packages/86/a8/7c6cd6bfead1a11f2e411e688640e6d26574cb0bde7dcaa7423b0b65ed7a/propcache-0.5.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:62530ca89187827e4a4fe733f971abe81a7542eeea48ff61995f19b64d7199c8", size = 238729, upload-time = "2026-09-16T00:14:10.357Z" }, + { url = "https://files.pythonhosted.org/packages/5c/b4/442715b2e980df51be52d203549279e027728f24c80b00b5e525e31cd5ea/propcache-0.5.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:56fc3f7599528db40b1efa0889a620116e2704144495273d66066e8164e45838", size = 246121, upload-time = "2026-09-16T00:14:11.735Z" }, + { url = "https://files.pythonhosted.org/packages/bc/5d/df0684fc2b1732a01a7bec26d7897369022712422d25b09c37ce7dbc88a2/propcache-0.5.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4f2d880ff60f45898f4acfa152aac8d04e3ee627d90ff4003491bf92239d5757", size = 251735, upload-time = "2026-09-16T00:14:13.053Z" }, + { url = "https://files.pythonhosted.org/packages/c7/06/519a5ebb48b6f94beb48396e55c905f12246a25c3a3608a7ec7bceabf50e/propcache-0.5.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6e9368e87a3efc285e559131092c5db643eb8e56de4ee42064d5baec22ef2bb5", size = 235381, upload-time = "2026-09-16T00:14:14.398Z" }, + { url = "https://files.pythonhosted.org/packages/3c/07/1e0a9bb310830f2245edbd5cd3c6d24a783c053c4efd8e08e386e513c940/propcache-0.5.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:004e685b315646c410771836e72a44f143bbe624f29653a42687815069a303d5", size = 208973, upload-time = "2026-09-16T00:14:15.715Z" }, + { url = "https://files.pythonhosted.org/packages/62/5c/9324fab27d6088eecc47fe4332bf7aaf8c1ded93c36f558391e8a06d41a7/propcache-0.5.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:594eb4c6ec35e7179b058481f4e9f02521b56de16fa577c4b85c76fb1bf8a9f8", size = 233897, upload-time = "2026-09-16T00:14:17.25Z" }, + { url = "https://files.pythonhosted.org/packages/9c/a3/570d92fc952eae93b676f3a1568f4b89264102abd3c982ab6a9ebec58dcf/propcache-0.5.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:2dba2f02d2d5c09ef8a0e6c1a42aeaa451f4be9898cb00b04fe98717da2eb23b", size = 223512, upload-time = "2026-09-16T00:14:18.87Z" }, + { url = "https://files.pythonhosted.org/packages/65/47/26810d889d89bba31db397e6a88f8984af775f5ed6bad0a29dce84324cff/propcache-0.5.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:c3ef2818d63bc86071e9d2989ae75a1bc32b8f7059cfd9f5abbbee70c32e2ed6", size = 239043, upload-time = "2026-09-16T00:14:20.366Z" }, + { url = "https://files.pythonhosted.org/packages/89/2d/f9c47691aa024c8299a3afacd78d22a01ab57eb627b481b6089708e71017/propcache-0.5.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:dd2ac8f5b643454c2cc6b6118b13da16e88f4a6434fc3ba61aca384029f04f36", size = 208218, upload-time = "2026-09-16T00:14:21.801Z" }, + { url = "https://files.pythonhosted.org/packages/74/6b/d510c0c378cabbf9d0ac7b663af6d00f2e9074073d93b20c85f24aa5c071/propcache-0.5.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:4054acf80d40456a0537f2913b349718649d8d6458a14ab7f48d0ce28c30869d", size = 240301, upload-time = "2026-09-16T00:14:23.121Z" }, + { url = "https://files.pythonhosted.org/packages/3d/80/c80f6adaaa1e51f0db2dce8c9b3714d94ec45e358a21f9a1910b10b40a80/propcache-0.5.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:40e94adb1e7d39ff28a8bd8d8b8fbd1df6b9f40976dbe379134f1ce058e532dd", size = 230785, upload-time = "2026-09-16T00:14:24.458Z" }, + { url = "https://files.pythonhosted.org/packages/d9/e2/c32a7df3f39caa7f11b2eb37ea5b6960a6946f2bc7c4b8ff97bbdf6d6b6e/propcache-0.5.4-cp311-cp311-win32.whl", hash = "sha256:9f86f7259efe2c951f43e57d471c9b41daa5bfc7db9f67189059cf1ae6d77fd9", size = 42747, upload-time = "2026-09-16T00:14:25.715Z" }, + { url = "https://files.pythonhosted.org/packages/0a/8a/3db6a3543d8101263b4c52978b6276a04ead2caff2c5ab880d934f47bd89/propcache-0.5.4-cp311-cp311-win_amd64.whl", hash = "sha256:e904d4d01f36bd6e197590be1533c44e06058771e0746dd073a8ebb3ef880858", size = 46268, upload-time = "2026-09-16T00:14:26.996Z" }, + { url = "https://files.pythonhosted.org/packages/41/07/5222e2665bbf6e45847492ecbf3b9f3e4975a0ae300e5fd465df7d48ce55/propcache-0.5.4-cp311-cp311-win_arm64.whl", hash = "sha256:d42a9a856a4a6e2f6c10f1318c07e7daa498d6593abe745c71dae4521a26ca39", size = 43547, upload-time = "2026-09-16T00:14:28.143Z" }, + { url = "https://files.pythonhosted.org/packages/f5/cd/785c64ed382f3f04201870267b02783f63b4678c2acfddc177a3ebcc2727/propcache-0.5.4-py3-none-any.whl", hash = "sha256:62c60aec739ed00124573cce1178138fd690c7676352d67a37328c1cf51d7468", size = 16338, upload-time = "2026-09-16T00:17:13.106Z" }, +] + +[[package]] +name = "protobuf" +version = "6.33.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/66/70/e908e9c5e52ef7c3a6c7902c9dfbb34c7e29c25d2f81ade3856445fd5c94/protobuf-6.33.6.tar.gz", hash = "sha256:a6768d25248312c297558af96a9f9c929e8c4cee0659cb07e780731095f38135", size = 444531, upload-time = "2026-03-18T19:05:00.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/9f/2f509339e89cfa6f6a4c4ff50438db9ca488dec341f7e454adad60150b00/protobuf-6.33.6-cp310-abi3-win32.whl", hash = "sha256:7d29d9b65f8afef196f8334e80d6bc1d5d4adedb449971fefd3723824e6e77d3", size = 425739, upload-time = "2026-03-18T19:04:48.373Z" }, + { url = "https://files.pythonhosted.org/packages/76/5d/683efcd4798e0030c1bab27374fd13a89f7c2515fb1f3123efdfaa5eab57/protobuf-6.33.6-cp310-abi3-win_amd64.whl", hash = "sha256:0cd27b587afca21b7cfa59a74dcbd48a50f0a6400cfb59391340ad729d91d326", size = 437089, upload-time = "2026-03-18T19:04:50.381Z" }, + { url = "https://files.pythonhosted.org/packages/5c/01/a3c3ed5cd186f39e7880f8303cc51385a198a81469d53d0fdecf1f64d929/protobuf-6.33.6-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:9720e6961b251bde64edfdab7d500725a2af5280f3f4c87e57c0208376aa8c3a", size = 427737, upload-time = "2026-03-18T19:04:51.866Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/b3c01fdec7d2f627b3a6884243ba328c1217ed2d978def5c12dc50d328a3/protobuf-6.33.6-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:e2afbae9b8e1825e3529f88d514754e094278bb95eadc0e199751cdd9a2e82a2", size = 324610, upload-time = "2026-03-18T19:04:53.096Z" }, + { url = "https://files.pythonhosted.org/packages/9b/ca/25afc144934014700c52e05103c2421997482d561f3101ff352e1292fb81/protobuf-6.33.6-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:c96c37eec15086b79762ed265d59ab204dabc53056e3443e702d2681f4b39ce3", size = 339381, upload-time = "2026-03-18T19:04:54.616Z" }, + { url = "https://files.pythonhosted.org/packages/16/92/d1e32e3e0d894fe00b15ce28ad4944ab692713f2e7f0a99787405e43533a/protobuf-6.33.6-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:e9db7e292e0ab79dd108d7f1a94fe31601ce1ee3f7b79e0692043423020b0593", size = 323436, upload-time = "2026-03-18T19:04:55.768Z" }, + { url = "https://files.pythonhosted.org/packages/c4/72/02445137af02769918a93807b2b7890047c32bfb9f90371cbc12688819eb/protobuf-6.33.6-py3-none-any.whl", hash = "sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901", size = 170656, upload-time = "2026-03-18T19:04:59.826Z" }, +] + +[[package]] +name = "psutil" +version = "7.1.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e1/88/bdd0a41e5857d5d703287598cbf08dad90aed56774ea52ae071bae9071b6/psutil-7.1.3.tar.gz", hash = "sha256:6c86281738d77335af7aec228328e944b30930899ea760ecf33a4dba66be5e74", size = 489059, upload-time = "2025-11-02T12:25:54.619Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/94/46b9154a800253e7ecff5aaacdf8ebf43db99de4a2dfa18575b02548654e/psutil-7.1.3-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2bdbcd0e58ca14996a42adf3621a6244f1bb2e2e528886959c72cf1e326677ab", size = 238359, upload-time = "2025-11-02T12:26:25.284Z" }, + { url = "https://files.pythonhosted.org/packages/68/3a/9f93cff5c025029a36d9a92fef47220ab4692ee7f2be0fba9f92813d0cb8/psutil-7.1.3-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:bc31fa00f1fbc3c3802141eede66f3a2d51d89716a194bf2cd6fc68310a19880", size = 239171, upload-time = "2025-11-02T12:26:27.23Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b1/5f49af514f76431ba4eea935b8ad3725cdeb397e9245ab919dbc1d1dc20f/psutil-7.1.3-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3bb428f9f05c1225a558f53e30ccbad9930b11c3fc206836242de1091d3e7dd3", size = 263261, upload-time = "2025-11-02T12:26:29.48Z" }, + { url = "https://files.pythonhosted.org/packages/e0/95/992c8816a74016eb095e73585d747e0a8ea21a061ed3689474fabb29a395/psutil-7.1.3-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56d974e02ca2c8eb4812c3f76c30e28836fffc311d55d979f1465c1feeb2b68b", size = 264635, upload-time = "2025-11-02T12:26:31.74Z" }, + { url = "https://files.pythonhosted.org/packages/55/4c/c3ed1a622b6ae2fd3c945a366e64eb35247a31e4db16cf5095e269e8eb3c/psutil-7.1.3-cp37-abi3-win_amd64.whl", hash = "sha256:f39c2c19fe824b47484b96f9692932248a54c43799a84282cfe58d05a6449efd", size = 247633, upload-time = "2025-11-02T12:26:33.887Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ad/33b2ccec09bf96c2b2ef3f9a6f66baac8253d7565d8839e024a6b905d45d/psutil-7.1.3-cp37-abi3-win_arm64.whl", hash = "sha256:bd0d69cee829226a761e92f28140bec9a5ee9d5b4fb4b0cc589068dbfff559b1", size = 244608, upload-time = "2025-11-02T12:26:36.136Z" }, +] + +[[package]] +name = "pyarrow" +version = "17.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/27/4e/ea6d43f324169f8aec0e57569443a38bab4b398d09769ca64f7b4d467de3/pyarrow-17.0.0.tar.gz", hash = "sha256:4beca9521ed2c0921c1023e68d097d0299b62c362639ea315572a58f3f50fd28", size = 1112479, upload-time = "2024-07-17T10:41:25.092Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/46/ce89f87c2936f5bb9d879473b9663ce7a4b1f4359acc2f0eb39865eaa1af/pyarrow-17.0.0-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:1c8856e2ef09eb87ecf937104aacfa0708f22dfeb039c363ec99735190ffb977", size = 29028748, upload-time = "2024-07-16T10:30:02.609Z" }, + { url = "https://files.pythonhosted.org/packages/8d/8e/ce2e9b2146de422f6638333c01903140e9ada244a2a477918a368306c64c/pyarrow-17.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2e19f569567efcbbd42084e87f948778eb371d308e137a0f97afe19bb860ccb3", size = 27190965, upload-time = "2024-07-16T10:30:10.718Z" }, + { url = "https://files.pythonhosted.org/packages/3b/c8/5675719570eb1acd809481c6d64e2136ffb340bc387f4ca62dce79516cea/pyarrow-17.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b244dc8e08a23b3e352899a006a26ae7b4d0da7bb636872fa8f5884e70acf15", size = 39269081, upload-time = "2024-07-16T10:30:18.878Z" }, + { url = "https://files.pythonhosted.org/packages/5e/78/3931194f16ab681ebb87ad252e7b8d2c8b23dad49706cadc865dff4a1dd3/pyarrow-17.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0b72e87fe3e1db343995562f7fff8aee354b55ee83d13afba65400c178ab2597", size = 39864921, upload-time = "2024-07-16T10:30:27.008Z" }, + { url = "https://files.pythonhosted.org/packages/d8/81/69b6606093363f55a2a574c018901c40952d4e902e670656d18213c71ad7/pyarrow-17.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:dc5c31c37409dfbc5d014047817cb4ccd8c1ea25d19576acf1a001fe07f5b420", size = 38740798, upload-time = "2024-07-16T10:30:34.814Z" }, + { url = "https://files.pythonhosted.org/packages/4c/21/9ca93b84b92ef927814cb7ba37f0774a484c849d58f0b692b16af8eebcfb/pyarrow-17.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:e3343cb1e88bc2ea605986d4b94948716edc7a8d14afd4e2c097232f729758b4", size = 39871877, upload-time = "2024-07-16T10:30:42.672Z" }, + { url = "https://files.pythonhosted.org/packages/30/d1/63a7c248432c71c7d3ee803e706590a0b81ce1a8d2b2ae49677774b813bb/pyarrow-17.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:a27532c38f3de9eb3e90ecab63dfda948a8ca859a66e3a47f5f42d1e403c4d03", size = 25151089, upload-time = "2024-07-16T10:30:49.279Z" }, +] + +[[package]] +name = "pyarrow" +version = "20.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/a2/ee/a7810cb9f3d6e9238e61d312076a9859bf3668fd21c69744de9532383912/pyarrow-20.0.0.tar.gz", hash = "sha256:febc4a913592573c8d5805091a6c2b5064c8bd6e002131f01061797d91c783c1", size = 1125187, upload-time = "2025-04-27T12:34:23.264Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/a2/b7930824181ceadd0c63c1042d01fa4ef63eee233934826a7a2a9af6e463/pyarrow-20.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:24ca380585444cb2a31324c546a9a56abbe87e26069189e14bdba19c86c049f0", size = 30856035, upload-time = "2025-04-27T12:28:40.78Z" }, + { url = "https://files.pythonhosted.org/packages/9b/18/c765770227d7f5bdfa8a69f64b49194352325c66a5c3bb5e332dfd5867d9/pyarrow-20.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:95b330059ddfdc591a3225f2d272123be26c8fa76e8c9ee1a77aad507361cfdb", size = 32309552, upload-time = "2025-04-27T12:28:47.051Z" }, + { url = "https://files.pythonhosted.org/packages/44/fb/dfb2dfdd3e488bb14f822d7335653092dde150cffc2da97de6e7500681f9/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5f0fb1041267e9968c6d0d2ce3ff92e3928b243e2b6d11eeb84d9ac547308232", size = 41334704, upload-time = "2025-04-27T12:28:55.064Z" }, + { url = "https://files.pythonhosted.org/packages/58/0d/08a95878d38808051a953e887332d4a76bc06c6ee04351918ee1155407eb/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b8ff87cc837601532cc8242d2f7e09b4e02404de1b797aee747dd4ba4bd6313f", size = 42399836, upload-time = "2025-04-27T12:29:02.13Z" }, + { url = "https://files.pythonhosted.org/packages/f3/cd/efa271234dfe38f0271561086eedcad7bc0f2ddd1efba423916ff0883684/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:7a3a5dcf54286e6141d5114522cf31dd67a9e7c9133d150799f30ee302a7a1ab", size = 40711789, upload-time = "2025-04-27T12:29:09.951Z" }, + { url = "https://files.pythonhosted.org/packages/46/1f/7f02009bc7fc8955c391defee5348f510e589a020e4b40ca05edcb847854/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:a6ad3e7758ecf559900261a4df985662df54fb7fdb55e8e3b3aa99b23d526b62", size = 42301124, upload-time = "2025-04-27T12:29:17.187Z" }, + { url = "https://files.pythonhosted.org/packages/4f/92/692c562be4504c262089e86757a9048739fe1acb4024f92d39615e7bab3f/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6bb830757103a6cb300a04610e08d9636f0cd223d32f388418ea893a3e655f1c", size = 42916060, upload-time = "2025-04-27T12:29:24.253Z" }, + { url = "https://files.pythonhosted.org/packages/a4/ec/9f5c7e7c828d8e0a3c7ef50ee62eca38a7de2fa6eb1b8fa43685c9414fef/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96e37f0766ecb4514a899d9a3554fadda770fb57ddf42b63d80f14bc20aa7db3", size = 44547640, upload-time = "2025-04-27T12:29:32.782Z" }, + { url = "https://files.pythonhosted.org/packages/54/96/46613131b4727f10fd2ffa6d0d6f02efcc09a0e7374eff3b5771548aa95b/pyarrow-20.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:3346babb516f4b6fd790da99b98bed9708e3f02e734c84971faccb20736848dc", size = 25781491, upload-time = "2025-04-27T12:29:38.464Z" }, +] + +[[package]] +name = "pydantic" +version = "2.14.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/fc/1203d011145c98ddce3cd2f505bb54375ef8d43223053df6bfcf3c746f46/pydantic-2.14.3.tar.gz", hash = "sha256:1054f237f4d4733e5a30e1e2333bd33a2004ab9ab1510bd053a9a31bb48e232d", size = 925636, upload-time = "2026-11-05T09:17:04.686Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/b8/b864503789ef5c58597d2a7b4adbee62c26440ab1e682581fc6838df8947/pydantic-2.14.3-py3-none-any.whl", hash = "sha256:3f7b347782ab7e4cf4c798496ae3a82787d9f21ec12676a9c564355eeef8daa8", size = 494071, upload-time = "2026-11-05T09:17:02.426Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.50.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9c/0f/34f9ce4ba701dd0b815033ef94d99b56f66200e578ee6052aa3ac26f064e/pydantic_core-2.50.4.tar.gz", hash = "sha256:aead3b74b68396bf0feab5d57e050b730ded7df55853c1e048a87e00aaf033c6", size = 522249, upload-time = "2026-11-05T09:15:26.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/00/85e80811834d7cbd9bc228f9b5cdf8ec0edd69b55351ad720aac8c412d8c/pydantic_core-2.50.4-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:3e547ceec1da7382f01f9e13963023e53367a71802c88778b21b9645a077cbdf", size = 2170584, upload-time = "2026-11-05T09:11:41.139Z" }, + { url = "https://files.pythonhosted.org/packages/a3/f1/438de1fb99d717dcc6521922478dc16ef7b757302d4fc1f7faba3aaeac09/pydantic_core-2.50.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c813ada7a651193acda85b6bc1cf12abd4b37cd25c7c6a75d7183512cc374969", size = 2128471, upload-time = "2026-11-05T09:11:42.65Z" }, + { url = "https://files.pythonhosted.org/packages/b7/74/f21ab568c6d3f315988b40e53f809c95b63fafc5403332963aa6dfc2c054/pydantic_core-2.50.4-cp311-cp311-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:57fa0a9490785139f1a4e4f43891830d55dfe4408845c0c9cb5eff4aeaf75f69", size = 2281509, upload-time = "2026-11-05T09:11:44.359Z" }, + { url = "https://files.pythonhosted.org/packages/a1/42/24ed3ea8e2fb6463c9ba5b8b1f089e69040905c7fd81dcfa6f52fcc692d5/pydantic_core-2.50.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:30d4dc35bc0eea52202a90b3820445ee0072c820241bfa710a623a078c9b267b", size = 2128064, upload-time = "2026-11-05T09:11:46.01Z" }, + { url = "https://files.pythonhosted.org/packages/d6/d1/44f541b2c18a46df6f18281a557acefeb5bbf0733a0b80b0a5e835e10ee4/pydantic_core-2.50.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:789f88dea57841cdebef392b5d6e90444d767117e9ff2e0d9172df5c9de6690c", size = 2214472, upload-time = "2026-11-05T09:11:47.503Z" }, + { url = "https://files.pythonhosted.org/packages/bd/1b/e9a9ad8733e8051abca9e4acce37ba3ddd13930fd3b8730f4c7816fa979a/pydantic_core-2.50.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:d690121e80ab16e623415351ab24713534d4e500b3cadff216409cb6826063d4", size = 2401153, upload-time = "2026-11-05T09:11:49.403Z" }, + { url = "https://files.pythonhosted.org/packages/79/84/d88e8e6aa42d4d677666d6625db9177ad6851be9e7564a25aeb0b0cbcaf2/pydantic_core-2.50.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b42f64825f5d750228f08318a9bf4d723b7ecb4c472aedcb3013c3ec2dc1f949", size = 2453307, upload-time = "2026-11-05T09:11:51.118Z" }, + { url = "https://files.pythonhosted.org/packages/56/51/cbb7a1bc0196ff94d3478d265eed7449f811759988eb760d41f4edd0893b/pydantic_core-2.50.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0574866e05f6adeecc520d87e87dd06210c0a51706341f6ef8421572f5a64444", size = 2253434, upload-time = "2026-11-05T09:11:52.997Z" }, + { url = "https://files.pythonhosted.org/packages/9e/04/206b4881d631033ae88f005da6e11bd610c850e1850217342c03053d253b/pydantic_core-2.50.4-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:dcf2c7eaaa4cafe8e49b017e5bb49e76e084ab6f0cd712ee4019c812b5cf68b8", size = 2279365, upload-time = "2026-11-05T09:11:54.822Z" }, + { url = "https://files.pythonhosted.org/packages/a1/7c/d815b5a3f83069b283d3b6a2e61de6e14baac3b20c6cd3418e9e629551cf/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:3b8ee2589a082739c522c1fe4be227412fcf108b903abb6672ae2f5570558882", size = 2319407, upload-time = "2026-11-05T09:11:56.46Z" }, + { url = "https://files.pythonhosted.org/packages/ee/00/c9a483276d1052d5142e1e01eccac97d939f83a3a3fd94c4766495a9b807/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:aec3c2d741a8e3ee993de7f95f37afb51e31b169c95dbd29da4cf6688f340914", size = 2489900, upload-time = "2026-11-05T09:11:58.102Z" }, + { url = "https://files.pythonhosted.org/packages/2d/b5/8cd8ee29a1d63ad47f95593384df92476cef6896c644f280db0748b8e76b/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8923fcd49f875e8a0448d7223d1fdf1a9973ae2d1f20d4158753ceb8909facd2", size = 2497732, upload-time = "2026-11-05T09:11:59.928Z" }, + { url = "https://files.pythonhosted.org/packages/60/31/050a48c0c373df16442ac07f3fa167414bb0e22f54a3e886f6d6cb7ad1d4/pydantic_core-2.50.4-cp311-cp311-win32.whl", hash = "sha256:fc04affef30be98c1f36f0c422a4061ef618fdc1dde79f5ad5458dd496fecffa", size = 2132347, upload-time = "2026-11-05T09:12:01.928Z" }, + { url = "https://files.pythonhosted.org/packages/c6/06/cebeeb7a8e87b42a3d8bc189d0d400e47df5d1736cb326764bae8a74c433/pydantic_core-2.50.4-cp311-cp311-win_amd64.whl", hash = "sha256:15bece43a02ad543c621c8305e67dedb5f27d378c5ba741e5a2c36523f8ef37f", size = 2255970, upload-time = "2026-11-05T09:12:03.888Z" }, + { url = "https://files.pythonhosted.org/packages/46/db/5b4bf14347da658c994483043fbabffedcab98929c41c261ec168c3c1f87/pydantic_core-2.50.4-cp311-cp311-win_arm64.whl", hash = "sha256:e498900bfbf7ddddd862f810440c09e9b81674739e8a11d619b40906dccd4a9a", size = 2196799, upload-time = "2026-11-05T09:12:05.389Z" }, + { url = "https://files.pythonhosted.org/packages/d8/18/3ca5b3b8ce7a540305e6856d013e9c6b9c0fef93258fef6038db0beb233a/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:39f489ce31272073e6e146f6781690f9c1ee8c126836e6403361ef91154d89fe", size = 2166960, upload-time = "2026-11-05T09:15:06.902Z" }, + { url = "https://files.pythonhosted.org/packages/a3/60/65d725001bffcde0170f6d37ae8bccce715e5311122eb6127f698115957e/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:5b26e5f1793b96cdc60242bf38da86ff24a27a708aa396214cac9b534bf571c7", size = 2085636, upload-time = "2026-11-05T09:15:08.395Z" }, + { url = "https://files.pythonhosted.org/packages/ac/12/934cf1d44a3fee3c47231d4690dddee19264150c3aa59a3ddf66fa43454d/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:7210398a1607ad607dc73196e575b3148b00a333cbb602ddbe1b60ba54554f43", size = 2284621, upload-time = "2026-11-05T09:15:09.82Z" }, + { url = "https://files.pythonhosted.org/packages/c4/91/52248eee98d76f8d9239166d24928f805292df16729109f4f189cdb59be4/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2f42584e5785385f681163a42506cab0d51295e17599a648396c52a7046c1372", size = 2277673, upload-time = "2026-11-05T09:15:11.236Z" }, + { url = "https://files.pythonhosted.org/packages/9f/89/900a7970ef19843aa79522a95b461e9c365b7fedd7ee80ef28a84dae9a41/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:2039e323acee9abfec1fb5f661776e8965fe5928f3b7f8431900a774cba5c317", size = 2297354, upload-time = "2026-11-05T09:15:12.798Z" }, + { url = "https://files.pythonhosted.org/packages/de/ec/053d829437f70070cdd7116a0257cc0da651103328ff1e9e82954c45efd6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:71ade6d2e445839350d589ff99bbddfde16f3f32db28da5c894a09f99c8b2a03", size = 2469913, upload-time = "2026-11-05T09:15:14.319Z" }, + { url = "https://files.pythonhosted.org/packages/80/af/207c821cb0813e16d630660e0073491e3ab07370efaa6fa0b8b10fffb7b6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:d7d406709ae924cf0b08b8282ca2f0e1c90526911d93bc040557cbc83b74c55f", size = 2503746, upload-time = "2026-11-05T09:15:15.736Z" }, + { url = "https://files.pythonhosted.org/packages/e7/ca/8a053f24e22d8150349cabaecb2f35c89dcf07fbaadb5e48295184dd0e5b/pydantic_core-2.50.4-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:7472c39480ccc11dda69a196d1b7c7a6b48eb6594b77f05d945599d3e47f731c", size = 2333540, upload-time = "2026-11-05T09:15:17.883Z" }, + { url = "https://files.pythonhosted.org/packages/ac/9d/41b374c62cdb87f84081e2ef2963a115eacc6284a26dbc96bb83568e83ec/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_10_12_x86_64.whl", hash = "sha256:b67d38e8bb0ade7e6e84575e4bb153fab35b122458077273aeb08fdf12be9d2c", size = 2166962, upload-time = "2026-11-05T09:15:20.276Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/51ef440ee346d4388a2c4a3ac4b271fcc7b1d3ff68be8da2ed2be4d488b0/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:4eda7e3fdef382b7d4492745988a5baaf6953923a337f8b9dde5f76fa8afde20", size = 2085634, upload-time = "2026-11-05T09:15:21.953Z" }, + { url = "https://files.pythonhosted.org/packages/4b/5f/c9ed62b96beb9050db221d29e81856b6e28f277db601f8b0c3a08f8cf913/pydantic_core-2.50.4-pp311-pypy311_pp80-manylinux_2_28_x86_64.whl", hash = "sha256:474f7e598c7902165662a5d5160d3fce31037890a2975a9871ebf7c05862300b", size = 2277804, upload-time = "2026-11-05T09:15:23.836Z" }, + { url = "https://files.pythonhosted.org/packages/63/bd/b912a5e251ef10ed7be5e543a2bfbeebb0c79bf6302bee786f8dc3bf4341/pydantic_core-2.50.4-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:3e0b395648c6cb871bceb2906907f255dc876ec425f2d5b024e129985cea8519", size = 2333539, upload-time = "2026-11-05T09:15:25.354Z" }, +] + +[[package]] +name = "pyparsing" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/11/b213bebff182584360cb8d17c72c1677fec5c5c228de439e63bcf8ab1c8f/pyparsing-3.3.3.tar.gz", hash = "sha256:928ae7e20211f3b6f3915a72f06a0cfd29ab9d24279dd6346b6b1a7146397d36", size = 1050487, upload-time = "2026-09-20T20:59:05.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" }, +] + +[[package]] +name = "python-dateutil" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, +] + +[[package]] +name = "pytorch-lightning" +version = "2.6.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "fsspec", extra = ["http"] }, + { name = "lightning-utilities" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "torch" }, + { name = "torchmetrics" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/97/e4/5025cb42311b4f8cc6d1b12cd81399ca433159f8e3831ab229c5a6c5177e/pytorch_lightning-2.6.6.tar.gz", hash = "sha256:52c52b20522dd3d3feb3bb3aae2dbe3f291e8e836d4111a74cfd72e9df018834", size = 662507, upload-time = "2026-09-10T09:41:16.684Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/4f/cf/ba8e4cc1b982ff6dc6f9fdef0e4074605438b82640f6270888a10e7e42c3/pytorch_lightning-2.6.6-py3-none-any.whl", hash = "sha256:71f95c7b22f25c4f91cc659e1734bcdc6c69c8b66543f2ed2d78dbe29ce2f167", size = 853045, upload-time = "2026-09-10T09:41:14.923Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/16/a95b6757765b7b031c9374925bb718d55e0a9ba8a1b6a12d25962ea44347/pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", size = 185826, upload-time = "2025-09-25T21:31:58.655Z" }, + { url = "https://files.pythonhosted.org/packages/16/19/13de8e4377ed53079ee996e1ab0a9c33ec2faf808a4647b7b4c0d46dd239/pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", size = 175577, upload-time = "2025-09-25T21:32:00.088Z" }, + { url = "https://files.pythonhosted.org/packages/0c/62/d2eb46264d4b157dae1275b573017abec435397aa59cbcdab6fc978a8af4/pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", size = 775556, upload-time = "2025-09-25T21:32:01.31Z" }, + { url = "https://files.pythonhosted.org/packages/10/cb/16c3f2cf3266edd25aaa00d6c4350381c8b012ed6f5276675b9eba8d9ff4/pyyaml-6.0.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00", size = 882114, upload-time = "2025-09-25T21:32:03.376Z" }, + { url = "https://files.pythonhosted.org/packages/71/60/917329f640924b18ff085ab889a11c763e0b573da888e8404ff486657602/pyyaml-6.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d", size = 806638, upload-time = "2025-09-25T21:32:04.553Z" }, + { url = "https://files.pythonhosted.org/packages/dd/6f/529b0f316a9fd167281a6c3826b5583e6192dba792dd55e3203d3f8e655a/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a", size = 767463, upload-time = "2025-09-25T21:32:06.152Z" }, + { url = "https://files.pythonhosted.org/packages/f2/6a/b627b4e0c1dd03718543519ffb2f1deea4a1e6d42fbab8021936a4d22589/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4", size = 794986, upload-time = "2025-09-25T21:32:07.367Z" }, + { url = "https://files.pythonhosted.org/packages/45/91/47a6e1c42d9ee337c4839208f30d9f09caa9f720ec7582917b264defc875/pyyaml-6.0.3-cp311-cp311-win32.whl", hash = "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b", size = 142543, upload-time = "2025-09-25T21:32:08.95Z" }, + { url = "https://files.pythonhosted.org/packages/da/e3/ea007450a105ae919a72393cb06f122f288ef60bba2dc64b26e2646fa315/pyyaml-6.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf", size = 158763, upload-time = "2025-09-25T21:32:09.96Z" }, +] + +[[package]] +name = "regex" +version = "2026.11.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/61/27/a5afeb952577b84ee5fe48b8b9ce47ae662dbb69cc5b76c28eff98f83b1e/regex-2026.11.9.tar.gz", hash = "sha256:316a70fbd70e999c9664681cb0eb5b4982b2cc0f623c7c86a8a112e1bd4c6277", size = 419513, upload-time = "2026-11-09T00:42:09.786Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/cd/83393cd04d1cdafb07dc6d3e4f6f40455c7d54edcfb7513a51c632a2fa32/regex-2026.11.9-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bc0414bae708e91fa635af848ea1fdc13e442f30497077da562014f88ac67436", size = 496166, upload-time = "2026-11-09T00:39:39.152Z" }, + { url = "https://files.pythonhosted.org/packages/13/90/65cd23cc77094ea6953a7f4f9808539611b71881b7d91729243fcaa43109/regex-2026.11.9-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:26f5137412492f043d13903b8ee3bbc464a73c67ec9432e187f5a5eef25c398f", size = 295747, upload-time = "2026-11-09T00:39:40.41Z" }, + { url = "https://files.pythonhosted.org/packages/3d/61/6523251b377f38be938342fd52da4aead1a1d1b79ce137d4412e5b1eb79e/regex-2026.11.9-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:cf8ba77a8d23fac7912cd9890a49d8f006106147bb80312c9954558b24ec7f95", size = 292719, upload-time = "2026-11-09T00:39:41.711Z" }, + { url = "https://files.pythonhosted.org/packages/97/5c/59cceda8ed285cb277f90f22b220c89576a38ebd1f2d7f0af198af98a5c7/regex-2026.11.9-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c876a5e3992b5f14709c7260188929174247485ed3f940bd94d4beb70abbfed3", size = 799904, upload-time = "2026-11-09T00:39:43.023Z" }, + { url = "https://files.pythonhosted.org/packages/9b/d0/498c4f67179885a4baf3b4500ea371d671180c20e136844065c239fe95d4/regex-2026.11.9-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:49eecd9b855cc9e683fed1b258d4e22dcb8e7b3c82f09c5778ce154359607f09", size = 874027, upload-time = "2026-11-09T00:39:44.36Z" }, + { url = "https://files.pythonhosted.org/packages/33/b9/61d474ad8aa93022edb00f13fcaac44678a5ef858801c804ad7d201d048b/regex-2026.11.9-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2405a0e564a5a1226427b21ee02a70c64f33a10015a18e480039c8ddb46b4f00", size = 915647, upload-time = "2026-11-09T00:39:45.587Z" }, + { url = "https://files.pythonhosted.org/packages/82/14/ec0c0f9e600f308280b901b46dd6e0095b56017fc2216b2abe6182009655/regex-2026.11.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0447593c5f4e2b88446da7466c83fc913ddf191600bbb7aebc6c8856595ccfb1", size = 805976, upload-time = "2026-11-09T00:39:47.654Z" }, + { url = "https://files.pythonhosted.org/packages/5e/de/bf7d2789051771e637d36aab03adea41b1e5729fe0c2a3d1df5e85a422bb/regex-2026.11.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:727989b08b98af7592eb86af12ca4227c017579094d5893a76fdd20b319cd8cd", size = 807143, upload-time = "2026-11-09T00:39:48.999Z" }, + { url = "https://files.pythonhosted.org/packages/0d/14/1a62ebd94dc36f74e2bb7f37bb7d7faf3bfc013cc90c1b1463d157e20136/regex-2026.11.9-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b886e1b7be6c392ea99d1c04de9b7adb4774038a1041514dfc6d0c5fb1bee6c5", size = 780582, upload-time = "2026-11-09T00:39:50.189Z" }, + { url = "https://files.pythonhosted.org/packages/3e/9b/42ce68062387ad6cbc4e2c5dc36d7f25d7a4d7621b5a67b8cd1a913ff2b4/regex-2026.11.9-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f1ec6903dc8054129ccc9404a5aaf19e4fab9af98b03604c69db903da3c045a4", size = 788733, upload-time = "2026-11-09T00:39:51.267Z" }, + { url = "https://files.pythonhosted.org/packages/ff/17/8e5268e78894c2a979a1599f9261eb0ede9952028d0a2689fbd80f2998b5/regex-2026.11.9-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:5c31a4e92c02f5c9e85c37a3851b9f83a36d2afdaaa88368f0d29ac56d8c81b8", size = 863625, upload-time = "2026-11-09T00:39:52.437Z" }, + { url = "https://files.pythonhosted.org/packages/97/0a/82e544ef361afc84e85a47907210bd9d1ef5c887b11ae3e091317c699327/regex-2026.11.9-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3dbccc60fa24fa1bab1cffe580c9bcd6467a885b6260d5e419f6d13db8c3596f", size = 766599, upload-time = "2026-11-09T00:39:54.03Z" }, + { url = "https://files.pythonhosted.org/packages/bf/4b/6484189c5f81e668059464780802b4bd6023415655c9410e8668a0a52a29/regex-2026.11.9-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:b5ce8fd914c9eaedfefa444ed329fc5a80c723136bda90e9e69159c536854c52", size = 855980, upload-time = "2026-11-09T00:39:55.184Z" }, + { url = "https://files.pythonhosted.org/packages/59/f8/954254f0c28b8113b304f0a9fec86274ad043b997161bb019ece9a00e5b8/regex-2026.11.9-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ff675c20d54564cb2b6c480c2e4b362dcc3ce74887ee2d2e63037658a0f01ab5", size = 793610, upload-time = "2026-11-09T00:39:56.351Z" }, + { url = "https://files.pythonhosted.org/packages/d9/2e/c30c186c8e0d55f4fa6cc882fb3f7eb3731ad70ffc5f99d40e99f261fadc/regex-2026.11.9-cp311-cp311-win32.whl", hash = "sha256:dd679c8172c94291ccee40e17b03b6e34c553ad855a57dc52e811c3bb83403f1", size = 269436, upload-time = "2026-11-09T00:39:57.808Z" }, + { url = "https://files.pythonhosted.org/packages/b5/6a/c23207465db6bb7a98211e82e5f79dc5473abea56464960f1c705bda888a/regex-2026.11.9-cp311-cp311-win_amd64.whl", hash = "sha256:b75ea29155c988eb375325a9fd9270a550ea3427acf275d350538c5f83571abc", size = 281159, upload-time = "2026-11-09T00:39:58.824Z" }, + { url = "https://files.pythonhosted.org/packages/df/7e/fe3c59e5adec098cddf9d65ed5f6543c070a344527a20d20e6731d4e57da/regex-2026.11.9-cp311-cp311-win_arm64.whl", hash = "sha256:b9c9746f25607eabe931c42f25535c9461589e25a80879a361f9c02f7abb6dce", size = 279986, upload-time = "2026-11-09T00:39:59.892Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "rouge" +version = "1.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/db/e4/3420a1ab1e82a280fb6107f7ae99e88eb12383c978fe573c0c64d0327d6b/rouge-1.0.1.tar.gz", hash = "sha256:12b48346ca47d6bcf3c45061f315452b9ccec0620ee895ec85b7efc3d54aae34", size = 14292, upload-time = "2021-07-20T08:45:56.53Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/7c/650ae86f92460e9e8ef969cc5008b24798dcf56a9a8947d04c78f550b3f5/rouge-1.0.1-py3-none-any.whl", hash = "sha256:28d118536e8c774dc47d1d15ec266479b4dd0914c4672ce117d4002789bdc644", size = 13725, upload-time = "2021-07-20T08:45:54.605Z" }, +] + +[[package]] +name = "safetensors" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/a0/f718cda65b05407d228f97602cf60dca269c979867aa5beb25410de26cd3/safetensors-0.8.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0", size = 473568, upload-time = "2026-06-09T07:52:18.829Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b1/fa7c600e7dceae12e9606c7578cbc9ff1e1ed55844883ee5c92205e86226/safetensors-0.8.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25", size = 484562, upload-time = "2026-06-09T07:52:17.518Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" }, + { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" }, + { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" }, + { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" }, + { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" }, + { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" }, + { url = "https://files.pythonhosted.org/packages/0d/49/1e15de264dcc3b77943d2d0c56a95809956883b1c2d6d585c792523f180b/safetensors-0.8.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca", size = 559930, upload-time = "2026-06-09T07:52:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" }, + { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" }, + { url = "https://files.pythonhosted.org/packages/29/4b/1c19c509d56e01f4fbb3d0a2e597450f6cc04d1d56cf52defb0a62dfd715/safetensors-0.8.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d", size = 765683, upload-time = "2026-06-09T07:52:22.594Z" }, + { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" }, + { url = "https://files.pythonhosted.org/packages/8e/3f/73ccf82579412b4a71c4ca673f10b5f1f888d7cf5af7fe24f27d30307be4/safetensors-0.8.0-cp310-abi3-win32.whl", hash = "sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d", size = 342401, upload-time = "2026-06-09T07:52:28.895Z" }, + { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" }, + { url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" }, +] + +[[package]] +name = "scikit-learn" +version = "1.7.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "joblib" }, + { name = "numpy" }, + { name = "scipy" }, + { name = "threadpoolctl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/c2/a7855e41c9d285dfe86dc50b250978105dce513d6e459ea66a6aeb0e1e0c/scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda", size = 7193136, upload-time = "2025-09-09T08:21:29.075Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/83/564e141eef908a5863a54da8ca342a137f45a0bfb71d1d79704c9894c9d1/scikit_learn-1.7.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c7509693451651cd7361d30ce4e86a1347493554f172b1c72a39300fa2aea79e", size = 9331967, upload-time = "2025-09-09T08:20:32.421Z" }, + { url = "https://files.pythonhosted.org/packages/18/d6/ba863a4171ac9d7314c4d3fc251f015704a2caeee41ced89f321c049ed83/scikit_learn-1.7.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:0486c8f827c2e7b64837c731c8feff72c0bd2b998067a8a9cbc10643c31f0fe1", size = 8648645, upload-time = "2025-09-09T08:20:34.436Z" }, + { url = "https://files.pythonhosted.org/packages/ef/0e/97dbca66347b8cf0ea8b529e6bb9367e337ba2e8be0ef5c1a545232abfde/scikit_learn-1.7.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:89877e19a80c7b11a2891a27c21c4894fb18e2c2e077815bcade10d34287b20d", size = 9715424, upload-time = "2025-09-09T08:20:36.776Z" }, + { url = "https://files.pythonhosted.org/packages/f7/32/1f3b22e3207e1d2c883a7e09abb956362e7d1bd2f14458c7de258a26ac15/scikit_learn-1.7.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8da8bf89d4d79aaec192d2bda62f9b56ae4e5b4ef93b6a56b5de4977e375c1f1", size = 9509234, upload-time = "2025-09-09T08:20:38.957Z" }, + { url = "https://files.pythonhosted.org/packages/9f/71/34ddbd21f1da67c7a768146968b4d0220ee6831e4bcbad3e03dd3eae88b6/scikit_learn-1.7.2-cp311-cp311-win_amd64.whl", hash = "sha256:9b7ed8d58725030568523e937c43e56bc01cadb478fc43c042a9aca1dacb3ba1", size = 8894244, upload-time = "2025-09-09T08:20:41.166Z" }, +] + +[[package]] +name = "scipy" +version = "1.17.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/75/b4ce781849931fef6fd529afa6b63711d5a733065722d0c3e2724af9e40a/scipy-1.17.1-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1f95b894f13729334fb990162e911c9e5dc1ab390c58aa6cbecb389c5b5e28ec", size = 31613675, upload-time = "2026-02-23T00:16:00.13Z" }, + { url = "https://files.pythonhosted.org/packages/f7/58/bccc2861b305abdd1b8663d6130c0b3d7cc22e8d86663edbc8401bfd40d4/scipy-1.17.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:e18f12c6b0bc5a592ed23d3f7b891f68fd7f8241d69b7883769eb5d5dfb52696", size = 28162057, upload-time = "2026-02-23T00:16:09.456Z" }, + { url = "https://files.pythonhosted.org/packages/6d/ee/18146b7757ed4976276b9c9819108adbc73c5aad636e5353e20746b73069/scipy-1.17.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:a3472cfbca0a54177d0faa68f697d8ba4c80bbdc19908c3465556d9f7efce9ee", size = 20334032, upload-time = "2026-02-23T00:16:17.358Z" }, + { url = "https://files.pythonhosted.org/packages/ec/e6/cef1cf3557f0c54954198554a10016b6a03b2ec9e22a4e1df734936bd99c/scipy-1.17.1-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:766e0dc5a616d026a3a1cffa379af959671729083882f50307e18175797b3dfd", size = 22709533, upload-time = "2026-02-23T00:16:25.791Z" }, + { url = "https://files.pythonhosted.org/packages/4d/60/8804678875fc59362b0fb759ab3ecce1f09c10a735680318ac30da8cd76b/scipy-1.17.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:744b2bf3640d907b79f3fd7874efe432d1cf171ee721243e350f55234b4cec4c", size = 33062057, upload-time = "2026-02-23T00:16:36.931Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/af933f0f6e0767995b4e2d705a0665e454d1c19402aa7e895de3951ebb04/scipy-1.17.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43af8d1f3bea642559019edfe64e9b11192a8978efbd1539d7bc2aaa23d92de4", size = 35349300, upload-time = "2026-02-23T00:16:49.108Z" }, + { url = "https://files.pythonhosted.org/packages/b4/3d/7ccbbdcbb54c8fdc20d3b6930137c782a163fa626f0aef920349873421ba/scipy-1.17.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:cd96a1898c0a47be4520327e01f874acfd61fb48a9420f8aa9f6483412ffa444", size = 35127333, upload-time = "2026-02-23T00:17:01.293Z" }, + { url = "https://files.pythonhosted.org/packages/e8/19/f926cb11c42b15ba08e3a71e376d816ac08614f769b4f47e06c3580c836a/scipy-1.17.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4eb6c25dd62ee8d5edf68a8e1c171dd71c292fdae95d8aeb3dd7d7de4c364082", size = 37741314, upload-time = "2026-02-23T00:17:12.576Z" }, + { url = "https://files.pythonhosted.org/packages/95/da/0d1df507cf574b3f224ccc3d45244c9a1d732c81dcb26b1e8a766ae271a8/scipy-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:d30e57c72013c2a4fe441c2fcb8e77b14e152ad48b5464858e07e2ad9fbfceff", size = 36607512, upload-time = "2026-02-23T00:17:23.424Z" }, + { url = "https://files.pythonhosted.org/packages/68/7f/bdd79ceaad24b671543ffe0ef61ed8e659440eb683b66f033454dcee90eb/scipy-1.17.1-cp311-cp311-win_arm64.whl", hash = "sha256:9ecb4efb1cd6e8c4afea0daa91a87fbddbce1b99d2895d151596716c0b2e859d", size = 24599248, upload-time = "2026-02-23T00:17:34.561Z" }, +] + +[[package]] +name = "sentencepiece" +version = "0.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/15/15/2e7a025fc62d764b151ae6d0f2a92f8081755ebe8d4a64099accc6f77ba6/sentencepiece-0.2.1.tar.gz", hash = "sha256:8138cec27c2f2282f4a34d9a016e3374cd40e5c6e9cb335063db66a0a3b71fad", size = 3228515, upload-time = "2025-08-12T07:00:51.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d8/15/46afbab00733d81788b64be430ca1b93011bb9388527958e26cc31832de5/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6356d0986b8b8dc351b943150fcd81a1c6e6e4d439772e8584c64230e58ca987", size = 1942560, upload-time = "2025-08-12T06:59:25.82Z" }, + { url = "https://files.pythonhosted.org/packages/fa/79/7c01b8ef98a0567e9d84a4e7a910f8e7074fcbf398a5cd76f93f4b9316f9/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8f8ba89a3acb3dc1ae90f65ec1894b0b9596fdb98ab003ff38e058f898b39bc7", size = 1325385, upload-time = "2025-08-12T06:59:27.722Z" }, + { url = "https://files.pythonhosted.org/packages/bb/88/2b41e07bd24f33dcf2f18ec3b74247aa4af3526bad8907b8727ea3caba03/sentencepiece-0.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:02593eca45440ef39247cee8c47322a34bdcc1d8ae83ad28ba5a899a2cf8d79a", size = 1253319, upload-time = "2025-08-12T06:59:29.306Z" }, + { url = "https://files.pythonhosted.org/packages/a0/54/38a1af0c6210a3c6f95aa46d23d6640636d020fba7135cd0d9a84ada05a7/sentencepiece-0.2.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a0d15781a171d188b661ae4bde1d998c303f6bd8621498c50c671bd45a4798e", size = 1316162, upload-time = "2025-08-12T06:59:30.914Z" }, + { url = "https://files.pythonhosted.org/packages/ef/66/fb191403ade791ad2c3c1e72fe8413e63781b08cfa3aa4c9dfc536d6e795/sentencepiece-0.2.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4f5a3e0d9f445ed9d66c0fec47d4b23d12cfc858b407a03c194c1b26c2ac2a63", size = 1387785, upload-time = "2025-08-12T06:59:32.491Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/3bd9b08e70067b2124518b308db6a84a4f8901cc8a4317e2e4288cdd9b4d/sentencepiece-0.2.1-cp311-cp311-win32.whl", hash = "sha256:6d297a1748d429ba8534eebe5535448d78b8acc32d00a29b49acf28102eeb094", size = 999555, upload-time = "2025-08-12T06:59:34.475Z" }, + { url = "https://files.pythonhosted.org/packages/32/b8/f709977f5fda195ae1ea24f24e7c581163b6f142b1005bc3d0bbfe4d7082/sentencepiece-0.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:82d9ead6591015f009cb1be1cb1c015d5e6f04046dbb8c9588b931e869a29728", size = 1054617, upload-time = "2025-08-12T06:59:36.461Z" }, + { url = "https://files.pythonhosted.org/packages/7a/40/a1fc23be23067da0f703709797b464e8a30a1c78cc8a687120cd58d4d509/sentencepiece-0.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:39f8651bd10974eafb9834ce30d9bcf5b73e1fc798a7f7d2528f9820ca86e119", size = 1033877, upload-time = "2025-08-12T06:59:38.391Z" }, +] + +[[package]] +name = "sentry-sdk" +version = "2.74.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8e/7f/1b16ab4aee53cc5db976bac12e6df5d562aae3880965200cef812e7121d9/sentry_sdk-2.74.0.tar.gz", hash = "sha256:dd91d75aacaef636006b579ac3ddb2fdbc9dce35f00f4b353b6b1b110c6b256a", size = 1081514, upload-time = "2026-11-05T14:50:27.444Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/55/b1/736d4b4b308694b0071844a533522ac06669ad61751687b94edfbf863f17/sentry_sdk-2.74.0-py3-none-any.whl", hash = "sha256:40b205af015649df3ec9986e057ce24ce85956bee3fb75efa72c93aa7036bdff", size = 549800, upload-time = "2026-11-05T14:50:25.767Z" }, +] + +[[package]] +name = "setuptools" +version = "80.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/5d/3bf57dcd21979b887f014ea83c24ae194cfcd12b9e0fda66b957c69d1fca/setuptools-80.9.0.tar.gz", hash = "sha256:f36b47402ecde768dbfafc46e8e4207b4360c654f1f3bb84475f0a28628fb19c", size = 1319958, upload-time = "2025-05-27T00:56:51.443Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922", size = 1201486, upload-time = "2025-05-27T00:56:49.664Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "smmap" +version = "5.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/ea/49c993d6dfdd7338c9b1000a0f36817ed7ec84577ae2e52f890d1a4ff909/smmap-5.0.3.tar.gz", hash = "sha256:4d9debb8b99007ae47165abc08670bd74cb74b5227dda7f643eccc4e9eb5642c", size = 22506, upload-time = "2026-03-09T03:43:26.1Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/d4/59e74daffcb57a07668852eeeb6035af9f32cbfd7a1d2511f17d2fe6a738/smmap-5.0.3-py3-none-any.whl", hash = "sha256:c106e05d5a61449cf6ba9a1e650227ecfb141590d2a98412103ff35d89fc7b2f", size = 24390, upload-time = "2026-03-09T03:43:24.361Z" }, +] + +[[package]] +name = "sympy" +version = "1.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mpmath" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, +] + +[[package]] +name = "tensorboard" +version = "2.20.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "absl-py" }, + { name = "grpcio" }, + { name = "markdown" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "protobuf" }, + { name = "setuptools" }, + { name = "tensorboard-data-server" }, + { name = "werkzeug" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/9c/d9/a5db55f88f258ac669a92858b70a714bbbd5acd993820b41ec4a96a4d77f/tensorboard-2.20.0-py3-none-any.whl", hash = "sha256:9dc9f978cb84c0723acf9a345d96c184f0293d18f166bb8d59ee098e6cfaaba6", size = 5525680, upload-time = "2025-07-17T19:20:49.638Z" }, +] + +[[package]] +name = "tensorboard-data-server" +version = "0.7.2" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7a/13/e503968fefabd4c6b2650af21e110aa8466fe21432cd7c43a84577a89438/tensorboard_data_server-0.7.2-py3-none-any.whl", hash = "sha256:7e0610d205889588983836ec05dc098e80f97b7e7bbff7e994ebb78f578d0ddb", size = 2356, upload-time = "2023-10-23T21:23:32.16Z" }, + { url = "https://files.pythonhosted.org/packages/b7/85/dabeaf902892922777492e1d253bb7e1264cadce3cea932f7ff599e53fea/tensorboard_data_server-0.7.2-py3-none-macosx_10_9_x86_64.whl", hash = "sha256:9fe5d24221b29625dbc7328b0436ca7fc1c23de4acf4d272f1180856e32f9f60", size = 4823598, upload-time = "2023-10-23T21:23:33.714Z" }, + { url = "https://files.pythonhosted.org/packages/73/c6/825dab04195756cf8ff2e12698f22513b3db2f64925bdd41671bfb33aaa5/tensorboard_data_server-0.7.2-py3-none-manylinux_2_31_x86_64.whl", hash = "sha256:ef687163c24185ae9754ed5650eb5bc4d84ff257aabdc33f0cc6f74d8ba54530", size = 6590363, upload-time = "2023-10-23T21:23:35.583Z" }, +] + +[[package]] +name = "tensorboardx" +version = "2.6.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "packaging" }, + { name = "protobuf" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2b/c5/d4cc6e293fb837aaf9f76dd7745476aeba8ef7ef5146c3b3f9ee375fe7a5/tensorboardx-2.6.4.tar.gz", hash = "sha256:b163ccb7798b31100b9f5fa4d6bc22dad362d7065c2f24b51e50731adde86828", size = 4769801, upload-time = "2025-06-10T22:37:07.419Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e0/1d/b5d63f1a6b824282b57f7b581810d20b7a28ca951f2d5b59f1eb0782c12b/tensorboardx-2.6.4-py3-none-any.whl", hash = "sha256:5970cf3a1f0a6a6e8b180ccf46f3fe832b8a25a70b86e5a237048a7c0beb18e2", size = 87201, upload-time = "2025-06-10T22:37:05.44Z" }, +] + +[[package]] +name = "termcolor" +version = "3.2.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/87/56/ab275c2b56a5e2342568838f0d5e3e66a32354adcc159b495e374cda43f5/termcolor-3.2.0.tar.gz", hash = "sha256:610e6456feec42c4bcd28934a8c87a06c3fa28b01561d46aa09a9881b8622c58", size = 14423, upload-time = "2025-10-25T19:11:42.586Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/d5/141f53d7c1eb2a80e6d3e9a390228c3222c27705cbe7f048d3623053f3ca/termcolor-3.2.0-py3-none-any.whl", hash = "sha256:a10343879eba4da819353c55cb8049b0933890c2ebf9ad5d3ecd2bb32ea96ea6", size = 7698, upload-time = "2025-10-25T19:11:41.536Z" }, +] + +[[package]] +name = "threadpoolctl" +version = "3.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/56/97/b4748951a683e369513691c8eea33d100298d556308dcb0ab66b132a67f0/threadpoolctl-3.8.0.tar.gz", hash = "sha256:01080674ad7ac6182429c918a79de92da789bb448acc02fc0b620b1abd6b6137", size = 39424, upload-time = "2026-11-05T11:08:51.112Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/1b/831f2de4840a25db1dd7b1afea433ccafe6bb10aca07e13264f2079462d0/threadpoolctl-3.8.0-py3-none-any.whl", hash = "sha256:f1b49c82704d50f13ffae019c727b0fa4f6791a58f48f06a09c45face1be66da", size = 32091, upload-time = "2026-11-05T11:08:49.773Z" }, +] + +[[package]] +name = "tokenizers" +version = "0.19.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "huggingface-hub", marker = "extra == 'group-25-official-loren-experiment-native'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/48/04/2071c150f374aab6d5e92aaec38d0f3c368d227dd9e0469a1f0966ac68d1/tokenizers-0.19.1.tar.gz", hash = "sha256:ee59e6680ed0fdbe6b724cf38bd70400a0c1dd623b07ac729087270caeac88e3", size = 321039, upload-time = "2024-04-17T21:40:41.849Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/d6/6e1d728d765eb4102767f071bf7f6439ab10d7f4a975c9217db65715207a/tokenizers-0.19.1-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:5c88d1481f1882c2e53e6bb06491e474e420d9ac7bdff172610c4f9ad3898059", size = 2533448, upload-time = "2024-04-17T21:36:38.61Z" }, + { url = "https://files.pythonhosted.org/packages/90/79/d17a0f491d10817cd30f1121a07aa09c8e97a81114b116e473baf1577f09/tokenizers-0.19.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ddf672ed719b4ed82b51499100f5417d7d9f6fb05a65e232249268f35de5ed14", size = 2440254, upload-time = "2024-04-17T21:36:40.398Z" }, + { url = "https://files.pythonhosted.org/packages/c7/28/2d11c3ff94f9d42eceb2ea549a06e3f166fe391c5a025e5d96fac898a3ac/tokenizers-0.19.1-cp311-cp311-manylinux_2_12_i686.manylinux2010_i686.whl", hash = "sha256:dadc509cc8a9fe460bd274c0e16ac4184d0958117cf026e0ea8b32b438171594", size = 3684971, upload-time = "2024-04-17T21:36:43.115Z" }, + { url = "https://files.pythonhosted.org/packages/36/c6/537f22b57e6003904d35d07962dbde2f2e9bdd791d0241da976a4c7f8194/tokenizers-0.19.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:dfedf31824ca4915b511b03441784ff640378191918264268e6923da48104acc", size = 3568894, upload-time = "2024-04-17T21:36:45.011Z" }, + { url = "https://files.pythonhosted.org/packages/af/ef/3c1deed14ec59b2c8e7e2fa27b2a53f7d101181277a43b89ab17d891ef2e/tokenizers-0.19.1-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:ac11016d0a04aa6487b1513a3a36e7bee7eec0e5d30057c9c0408067345c48d2", size = 3426873, upload-time = "2024-04-17T21:36:47.001Z" }, + { url = "https://files.pythonhosted.org/packages/06/db/c0320c4798ac6bd12d2ef895bec9d10d216a3b4d6fff10e9d68883ea7edc/tokenizers-0.19.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:76951121890fea8330d3a0df9a954b3f2a37e3ec20e5b0530e9a0044ca2e11fe", size = 3965050, upload-time = "2024-04-17T21:36:49.202Z" }, + { url = "https://files.pythonhosted.org/packages/4c/8a/a166888d6cb14db55f5eb7ce0b1d4777d145aa27cbf4f945712cf6c29935/tokenizers-0.19.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b342d2ce8fc8d00f376af068e3274e2e8649562e3bc6ae4a67784ded6b99428d", size = 4047855, upload-time = "2024-04-17T21:36:52.864Z" }, + { url = "https://files.pythonhosted.org/packages/a7/03/fb50fc03f86016b227a967c8d474f90230c885c0d18f78acdfda7a96ce56/tokenizers-0.19.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d16ff18907f4909dca9b076b9c2d899114dd6abceeb074eca0c93e2353f943aa", size = 3608228, upload-time = "2024-04-17T21:36:55.7Z" }, + { url = "https://files.pythonhosted.org/packages/5b/cd/0385e1026e1e03732fd398e964792a3a8433918b166748c82507e014d748/tokenizers-0.19.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:706a37cc5332f85f26efbe2bdc9ef8a9b372b77e4645331a405073e4b3a8c1c6", size = 9633115, upload-time = "2024-04-17T21:36:58.299Z" }, + { url = "https://files.pythonhosted.org/packages/25/50/8f8ad0bbdaf09d04b15e6502d1fa1c653754ed7e016e4ae009726aa1a4e4/tokenizers-0.19.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:16baac68651701364b0289979ecec728546133e8e8fe38f66fe48ad07996b88b", size = 9949062, upload-time = "2024-04-17T21:37:01.947Z" }, + { url = "https://files.pythonhosted.org/packages/db/11/31be66710f1d14526f3588a441efadeb184e1e68458067007b20ead03c59/tokenizers-0.19.1-cp311-none-win32.whl", hash = "sha256:9ed240c56b4403e22b9584ee37d87b8bfa14865134e3e1c3fb4b2c42fafd3256", size = 2041039, upload-time = "2024-04-17T21:37:05.607Z" }, + { url = "https://files.pythonhosted.org/packages/65/8e/6d7d72b28f22c422cff8beae10ac3c2e4376b9be721ef8167b7eecd1da62/tokenizers-0.19.1-cp311-none-win_amd64.whl", hash = "sha256:ad57d59341710b94a7d9dbea13f5c1e7d76fd8d9bcd944a7a6ab0b0da6e0cc66", size = 2220386, upload-time = "2024-04-17T21:37:08.295Z" }, +] + +[[package]] +name = "tokenizers" +version = "0.22.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform == 'win32' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform == 'emscripten' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform == 'linux' and extra != 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform != 'linux' and extra != 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", +] +dependencies = [ + { name = "huggingface-hub", marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/97/5dbfabf04c7e348e655e907ed27913e03db0923abb5dfdd120d7b25630e1/tokenizers-0.22.2-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:544dd704ae7238755d790de45ba8da072e9af3eea688f698b137915ae959281c", size = 3100275, upload-time = "2026-01-05T10:41:02.158Z" }, + { url = "https://files.pythonhosted.org/packages/2e/47/174dca0502ef88b28f1c9e06b73ce33500eedfac7a7692108aec220464e7/tokenizers-0.22.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:1e418a55456beedca4621dbab65a318981467a2b188e982a23e117f115ce5001", size = 2981472, upload-time = "2026-01-05T10:41:00.276Z" }, + { url = "https://files.pythonhosted.org/packages/d6/84/7990e799f1309a8b87af6b948f31edaa12a3ed22d11b352eaf4f4b2e5753/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2249487018adec45d6e3554c71d46eb39fa8ea67156c640f7513eb26f318cec7", size = 3290736, upload-time = "2026-01-05T10:40:32.165Z" }, + { url = "https://files.pythonhosted.org/packages/78/59/09d0d9ba94dcd5f4f1368d4858d24546b4bdc0231c2354aa31d6199f0399/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:25b85325d0815e86e0bac263506dd114578953b7b53d7de09a6485e4a160a7dd", size = 3168835, upload-time = "2026-01-05T10:40:38.847Z" }, + { url = "https://files.pythonhosted.org/packages/47/50/b3ebb4243e7160bda8d34b731e54dd8ab8b133e50775872e7a434e524c28/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bfb88f22a209ff7b40a576d5324bf8286b519d7358663db21d6246fb17eea2d5", size = 3521673, upload-time = "2026-01-05T10:40:56.614Z" }, + { url = "https://files.pythonhosted.org/packages/e0/fa/89f4cb9e08df770b57adb96f8cbb7e22695a4cb6c2bd5f0c4f0ebcf33b66/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1c774b1276f71e1ef716e5486f21e76333464f47bece56bbd554485982a9e03e", size = 3724818, upload-time = "2026-01-05T10:40:44.507Z" }, + { url = "https://files.pythonhosted.org/packages/64/04/ca2363f0bfbe3b3d36e95bf67e56a4c88c8e3362b658e616d1ac185d47f2/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:df6c4265b289083bf710dff49bc51ef252f9d5be33a45ee2bed151114a56207b", size = 3379195, upload-time = "2026-01-05T10:40:51.139Z" }, + { url = "https://files.pythonhosted.org/packages/2e/76/932be4b50ef6ccedf9d3c6639b056a967a86258c6d9200643f01269211ca/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:369cc9fc8cc10cb24143873a0d95438bb8ee257bb80c71989e3ee290e8d72c67", size = 3274982, upload-time = "2026-01-05T10:40:58.331Z" }, + { url = "https://files.pythonhosted.org/packages/1d/28/5f9f5a4cc211b69e89420980e483831bcc29dade307955cc9dc858a40f01/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:29c30b83d8dcd061078b05ae0cb94d3c710555fbb44861139f9f83dcca3dc3e4", size = 9478245, upload-time = "2026-01-05T10:41:04.053Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fb/66e2da4704d6aadebf8cb39f1d6d1957df667ab24cff2326b77cda0dcb85/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:37ae80a28c1d3265bb1f22464c856bd23c02a05bb211e56d0c5301a435be6c1a", size = 9560069, upload-time = "2026-01-05T10:45:10.673Z" }, + { url = "https://files.pythonhosted.org/packages/16/04/fed398b05caa87ce9b1a1bb5166645e38196081b225059a6edaff6440fac/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:791135ee325f2336f498590eb2f11dc5c295232f288e75c99a36c5dbce63088a", size = 9899263, upload-time = "2026-01-05T10:45:12.559Z" }, + { url = "https://files.pythonhosted.org/packages/05/a1/d62dfe7376beaaf1394917e0f8e93ee5f67fea8fcf4107501db35996586b/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38337540fbbddff8e999d59970f3c6f35a82de10053206a7562f1ea02d046fa5", size = 10033429, upload-time = "2026-01-05T10:45:14.333Z" }, + { url = "https://files.pythonhosted.org/packages/fd/18/a545c4ea42af3df6effd7d13d250ba77a0a86fb20393143bbb9a92e434d4/tokenizers-0.22.2-cp39-abi3-win32.whl", hash = "sha256:a6bf3f88c554a2b653af81f3204491c818ae2ac6fbc09e76ef4773351292bc92", size = 2502363, upload-time = "2026-01-05T10:45:20.593Z" }, + { url = "https://files.pythonhosted.org/packages/65/71/0670843133a43d43070abeb1949abfdef12a86d490bea9cd9e18e37c5ff7/tokenizers-0.22.2-cp39-abi3-win_amd64.whl", hash = "sha256:c9ea31edff2968b44a88f97d784c2f16dc0729b8b143ed004699ebca91f05c48", size = 2747786, upload-time = "2026-01-05T10:45:18.411Z" }, + { url = "https://files.pythonhosted.org/packages/72/f4/0de46cfa12cdcbcd464cc59fde36912af405696f687e53a091fb432f694c/tokenizers-0.22.2-cp39-abi3-win_arm64.whl", hash = "sha256:9ce725d22864a1e965217204946f830c37876eee3b2ba6fc6255e8e903d5fcbc", size = 2612133, upload-time = "2026-01-05T10:45:17.232Z" }, +] + +[[package]] +name = "torch" +version = "2.13.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-bindings", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "nvidia-nvshmem-cu13", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "triton", marker = "sys_platform == 'linux' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, + { name = "typing-extensions" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/fe/cba54dc58523434919b66f13a667e36e436deddd77ca519e96553617d4ec/torch-2.13.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:e76f9bcecc52b8ff711239a2f7547d5353df95878ab232f0773c1d95928b92f8", size = 111187938, upload-time = "2026-07-08T16:05:17.065Z" }, + { url = "https://files.pythonhosted.org/packages/c2/59/1e3160e18e12aa3038390efab3ce02b36a9d4d6a527ecdd8520dca2e68d8/torch-2.13.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:092790c696a760c729fd5722835f50b9d81fd7c8f141571f3f3cf4081a8f664c", size = 427199369, upload-time = "2026-07-08T16:04:51.054Z" }, + { url = "https://files.pythonhosted.org/packages/01/79/1f2d34ad7034ee1c7ffc1cf8bf0f8213af2a81df6ecdb3997ecec107c09d/torch-2.13.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:60fcdcb2f3876e21146cb4524ef06397d727ca9ad5f020818547e25075fe3cb7", size = 526574961, upload-time = "2026-07-08T16:04:07.075Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fd/0f2ce40f58aefbdb3392f9acce3c8171940943ae2d661f70558bfa73befb/torch-2.13.0-cp311-cp311-win_amd64.whl", hash = "sha256:a0d8b11f16a48d60e2015d8213aa0390744cbebb98e58b62b3514dddc656e330", size = 122015870, upload-time = "2026-07-08T16:05:27.59Z" }, +] + +[[package]] +name = "torchmetrics" +version = "1.8.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "lightning-utilities" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "torch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/85/2e/48a887a59ecc4a10ce9e8b35b3e3c5cef29d902c4eac143378526e7485cb/torchmetrics-1.8.2.tar.gz", hash = "sha256:cf64a901036bf107f17a524009eea7781c9c5315d130713aeca5747a686fe7a5", size = 580679, upload-time = "2025-09-03T14:00:54.077Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/21/aa0f434434c48490f91b65962b1ce863fdcce63febc166ca9fe9d706c2b6/torchmetrics-1.8.2-py3-none-any.whl", hash = "sha256:08382fd96b923e39e904c4d570f3d49e2cc71ccabd2a94e0f895d1f0dac86242", size = 983161, upload-time = "2025-09-03T14:00:51.921Z" }, +] + +[[package]] +name = "tqdm" +version = "4.70.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'group-25-official-loren-experiment-modern' and extra == 'group-25-official-loren-experiment-native')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0d/ea/b2a5bd54b28a324dae8211928b2d730b6547500342c7e6c6dea08bd0a485/tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4", size = 171846, upload-time = "2026-09-11T07:25:16.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" }, +] + +[[package]] +name = "transformers" +version = "4.44.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "filelock", marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "huggingface-hub", marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "numpy", marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "packaging", marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "pyyaml", marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "regex", marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "requests", marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "safetensors", marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "tokenizers", version = "0.19.1", source = { registry = "https://pypi.org/simple" }, marker = "extra == 'group-25-official-loren-experiment-native'" }, + { name = "tqdm", marker = "extra == 'group-25-official-loren-experiment-native'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f8/a3/81de49357a3c6ac4421d48d9662b53293838f217baf3f3bb9eb55f89fab6/transformers-4.44.2.tar.gz", hash = "sha256:36aa17cc92ee154058e426d951684a2dab48751b35b49437896f898931270826", size = 8110312, upload-time = "2024-08-22T16:56:33.522Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/75/35/07c9879163b603f0e464b0f6e6e628a2340cfc7cdc5ca8e7d52d776710d4/transformers-4.44.2-py3-none-any.whl", hash = "sha256:1c02c65e7bfa5e52a634aff3da52138b583fc6f263c1f28d547dc144ba3d412d", size = 9465369, upload-time = "2024-08-22T16:56:29.207Z" }, +] + +[[package]] +name = "transformers" +version = "4.57.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform == 'win32' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform == 'emscripten' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32' and extra == 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform == 'linux' and extra != 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", + "sys_platform != 'linux' and extra != 'group-25-official-loren-experiment-modern' and extra != 'group-25-official-loren-experiment-native'", +] +dependencies = [ + { name = "filelock", marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, + { name = "huggingface-hub", marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, + { name = "numpy", marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, + { name = "packaging", marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, + { name = "pyyaml", marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, + { name = "regex", marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, + { name = "requests", marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, + { name = "safetensors", marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, + { name = "tokenizers", version = "0.22.2", source = { registry = "https://pypi.org/simple" }, marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, + { name = "tqdm", marker = "extra == 'group-25-official-loren-experiment-modern' or extra != 'group-25-official-loren-experiment-native'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/68/a39307bcc4116a30b2106f2e689130a48de8bd8a1e635b5e1030e46fcd9e/transformers-4.57.1.tar.gz", hash = "sha256:f06c837959196c75039809636cd964b959f6604b75b8eeec6fdfc0440b89cc55", size = 10142511, upload-time = "2025-10-14T15:39:26.18Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/d3/c16c3b3cf7655a67db1144da94b021c200ac1303f82428f2beef6c2e72bb/transformers-4.57.1-py3-none-any.whl", hash = "sha256:b10d05da8fa67dc41644dbbf9bc45a44cb86ae33da6f9295f5fbf5b7890bd267", size = 11990925, upload-time = "2025-10-14T15:39:23.085Z" }, +] + +[[package]] +name = "triton" +version = "3.7.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/f9/19d842d06a08559534fa1eaab6ca551b1bcf40f06620bddec1babaa2772d/triton-3.7.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4a0e1cd4c4a76370ed74a8432a53cea28716827d19e40ffc732233e35ceb3f6", size = 184664887, upload-time = "2026-06-17T20:03:42.913Z" }, + { url = "https://files.pythonhosted.org/packages/cd/5e/fce69606f7f240297f163e25539906732b199530d486ce67ae319877e821/triton-3.7.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6744957e9fd610a29680ec2346057d0c86948ed3812468670719f391e94b44a5", size = 197701306, upload-time = "2026-06-17T19:53:13.673Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ff/50/0195198eb1d75bab716bb0a813abea4cc394bfa17a92a189f021a34859af/typing_inspection-0.4.5.tar.gz", hash = "sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7", size = 81194, upload-time = "2026-11-04T14:13:23.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" }, +] + +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + +[[package]] +name = "wandb" +version = "0.23.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "gitpython" }, + { name = "packaging" }, + { name = "platformdirs" }, + { name = "protobuf" }, + { name = "pydantic" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "sentry-sdk" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0a/cc/770ae3aa7ae44f6792f7ecb81c14c0e38b672deb35235719bb1006519487/wandb-0.23.1.tar.gz", hash = "sha256:f6fb1e3717949b29675a69359de0eeb01e67d3360d581947d5b3f98c273567d6", size = 44298053, upload-time = "2025-12-03T02:25:10.79Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/0b/c3d7053dfd93fd259a63c7818d9c4ac2ba0642ff8dc8db98662ea0cf9cc0/wandb-0.23.1-py3-none-macosx_12_0_arm64.whl", hash = "sha256:358e15471d19b7d73fc464e37371c19d44d39e433252ac24df107aff993a286b", size = 21527293, upload-time = "2025-12-03T02:24:48.011Z" }, + { url = "https://files.pythonhosted.org/packages/ee/9f/059420fa0cb6c511dc5c5a50184122b6aca7b178cb2aa210139e354020da/wandb-0.23.1-py3-none-macosx_12_0_x86_64.whl", hash = "sha256:110304407f4b38f163bdd50ed5c5225365e4df3092f13089c30171a75257b575", size = 22745926, upload-time = "2025-12-03T02:24:50.519Z" }, + { url = "https://files.pythonhosted.org/packages/96/b6/fd465827c14c64d056d30b4c9fcf4dac889a6969dba64489a88fc4ffa333/wandb-0.23.1-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:6cc984cf85feb2f8ee0451d76bc9fb7f39da94956bb8183e30d26284cf203b65", size = 21212973, upload-time = "2025-12-03T02:24:52.828Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/9a8bb9a39cc1f09c3060456cc79565110226dc4099a719af5c63432da21d/wandb-0.23.1-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:67431cd3168d79fdb803e503bd669c577872ffd5dadfa86de733b3274b93088e", size = 22887885, upload-time = "2025-12-03T02:24:55.281Z" }, + { url = "https://files.pythonhosted.org/packages/6d/4d/8d9e75add529142e037b05819cb3ab1005679272950128d69d218b7e5b2e/wandb-0.23.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:07be70c0baa97ea25fadc4a9d0097f7371eef6dcacc5ceb525c82491a31e9244", size = 21250967, upload-time = "2025-12-03T02:24:57.603Z" }, + { url = "https://files.pythonhosted.org/packages/97/72/0b35cddc4e4168f03c759b96d9f671ad18aec8bdfdd84adfea7ecb3f5701/wandb-0.23.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:216c95b08e0a2ec6a6008373b056d597573d565e30b43a7a93c35a171485ee26", size = 22988382, upload-time = "2025-12-03T02:25:00.518Z" }, + { url = "https://files.pythonhosted.org/packages/c0/6d/e78093d49d68afb26f5261a70fc7877c34c114af5c2ee0ab3b1af85f5e76/wandb-0.23.1-py3-none-win32.whl", hash = "sha256:fb5cf0f85692f758a5c36ab65fea96a1284126de64e836610f92ddbb26df5ded", size = 22150756, upload-time = "2025-12-03T02:25:02.734Z" }, + { url = "https://files.pythonhosted.org/packages/05/27/4f13454b44c9eceaac3d6e4e4efa2230b6712d613ff9bf7df010eef4fd18/wandb-0.23.1-py3-none-win_amd64.whl", hash = "sha256:21c8c56e436eb707b7d54f705652e030d48e5cfcba24cf953823eb652e30e714", size = 22150760, upload-time = "2025-12-03T02:25:05.106Z" }, + { url = "https://files.pythonhosted.org/packages/30/20/6c091d451e2a07689bfbfaeb7592d488011420e721de170884fedd68c644/wandb-0.23.1-py3-none-win_arm64.whl", hash = "sha256:8aee7f3bb573f2c0acf860f497ca9c684f9b35f2ca51011ba65af3d4592b77c1", size = 20137463, upload-time = "2025-12-03T02:25:08.317Z" }, +] + +[[package]] +name = "werkzeug" +version = "3.1.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a4/34/4dd12fc8bb7d61c91467ec3efe415ffa7d5456f799954b40c5bbaeae470e/werkzeug-3.1.9.tar.gz", hash = "sha256:55ca7c70a75689be937aa27f8ff4b018f06ff4838fc73045560bf0f5a1291060", size = 940188, upload-time = "2026-09-27T18:33:41.637Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a1/38/df03f564f43cec2684823f3cccae1a652ee7face1cbaa76fb223096e64d7/werkzeug-3.1.9-py3-none-any.whl", hash = "sha256:6392e50c78460ba618e5b21f08a71f59c99ce99cdc6cf6e3dd7e6ccca8754fab", size = 228700, upload-time = "2026-09-27T18:33:39.685Z" }, +] + +[[package]] +name = "win32-setctime" +version = "1.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1a/e4/f0f252c65f9bf7c4042b1f707ef338d49f799da582234e1d3e6e2cfca291/win32_setctime-1.2.1.tar.gz", hash = "sha256:077b35471bf1ff1d71e165c919ddc0cecf51b8e1802f5d820d33a96e2f6717dd", size = 4983, upload-time = "2026-10-25T18:21:32.318Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bd/df/5593480bc1e932eeae28e4fa182ab68174edd0d77409ced3b6491d02d1d5/win32_setctime-1.2.1-py3-none-any.whl", hash = "sha256:a9edc685b35414bec69392c866ed82456ad125ac4a6a4b703ec1d8b462d4f477", size = 4215, upload-time = "2026-10-25T18:21:30.939Z" }, +] + +[[package]] +name = "xxhash" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c9/b5/3d11d3830ace56d67ea83136c24385c3b07da5a9bc62b73b0b94ac096da3/xxhash-4.1.0.tar.gz", hash = "sha256:c9b288e4c1f5dae54417bc8a05e6f6daf505783d916b4783f4dd2f2e7d5db486", size = 114122, upload-time = "2026-11-09T13:47:33.276Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/cb/da501f3abc32f8c3a6f0fb24f1988ec6b862897034a6f44bff92e06b6f29/xxhash-4.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cf3e28ee18b17d253d85c0a0b3608b9b54f765df4af207722c1ce851f386a26d", size = 51515, upload-time = "2026-11-09T13:46:45.912Z" }, + { url = "https://files.pythonhosted.org/packages/5c/1d/112856c31d49a814854f19b3ecf8d81196a5b2d0c8cccbbe5a0cfe571e86/xxhash-4.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:796b8e5212ba90ebc8afac5ae3615502acd0d65363730cccd1d629b0fe7e87f6", size = 36825, upload-time = "2026-11-09T13:46:48.399Z" }, + { url = "https://files.pythonhosted.org/packages/40/37/fb258a692f0ecd93ff3af8f77a0122db1e33853f6c6c433cb841f46da13f/xxhash-4.1.0-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:822f6aa36f336f65188ae987b9627e843b6963f749d8a2a187f5b6fd72715088", size = 448119, upload-time = "2026-11-09T13:46:48.427Z" }, + { url = "https://files.pythonhosted.org/packages/2f/be/4e9efad09e3152cd437a6ad46148a9fe992f9bdfc1117808e71bc02178c4/xxhash-4.1.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f948b71013e0a0922176563dd4538967e2d7717b845bd61e0407f2e410962050", size = 274457, upload-time = "2026-11-09T13:46:46.078Z" }, + { url = "https://files.pythonhosted.org/packages/3a/11/177b6b4a781ae0a38e2d335b2a6bfe4e70c3e8edace541b1615da408d4ef/xxhash-4.1.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3fbf446e75b80f2a605b4b1637cb5bfdad5c317bc54ecd91ac7cb9e28314fe4b", size = 296295, upload-time = "2026-11-09T13:46:48.728Z" }, + { url = "https://files.pythonhosted.org/packages/30/d7/d59d72875eb268e83743ce507de3ce983a611e18c79d4d4169500932a747/xxhash-4.1.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:586ce49f8d73dc214f9da8e87824f332f2b4ddb7d15534736a2f906373b2030d", size = 273599, upload-time = "2026-11-09T13:46:49.98Z" }, + { url = "https://files.pythonhosted.org/packages/10/8a/3c85277e544cae7f6fa1dad71e23485b21d5695d3ac69a10ea46d3257896/xxhash-4.1.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b6b09351f73f6d0a3df59b02b9d2154a66fcc716fae8f0b8b2bdd63c42a1d2f6", size = 506958, upload-time = "2026-11-09T13:46:47.172Z" }, + { url = "https://files.pythonhosted.org/packages/b6/4f/5b195a79fafb6e9ab8e95229cc5346572a6cc40d6d6ed9227183a25315ea/xxhash-4.1.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e713f5db9e1a8aafac59a45cc1ffce11ca507730f5dc12e212ea7b73d9debde", size = 471448, upload-time = "2026-11-09T13:46:47.314Z" }, + { url = "https://files.pythonhosted.org/packages/d8/6d/c34662fae63220b90d6803dab8fdc9240cf6cef06fbdea73fef0750ff438/xxhash-4.1.0-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:eadb2724470fd9507cb8f864c969d761dac7d549223ff15ff998c1c3c8e134d5", size = 337233, upload-time = "2026-11-09T13:46:49.72Z" }, + { url = "https://files.pythonhosted.org/packages/86/f7/7def1a3b835ef30b8f1a192405dd99db448922aeda8f45eb0359f00613c0/xxhash-4.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0119cf9ae630c5365596dd9dccf29932f364e8ef0f9162e1d7ef9df3e15ccb8e", size = 270274, upload-time = "2026-11-09T13:46:50.189Z" }, + { url = "https://files.pythonhosted.org/packages/bf/fb/677fef1a69b67c62eb12f71b7f49f801db1191df2f336d2930608f61c9f4/xxhash-4.1.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:3f580ff0d8dec8b495c6c6b281a89be3913158b01937281006993168b4375f84", size = 297452, upload-time = "2026-11-09T13:46:47.438Z" }, + { url = "https://files.pythonhosted.org/packages/95/15/5017ecacab16636c244e2cbd014cc56e17528caa736abcea4e151102e514/xxhash-4.1.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6179c5e008d2f1ca3a2e9c7935c021f84c5dc7516dfe5c9ee3edc0e9f26d20f0", size = 442167, upload-time = "2026-11-09T13:46:50.278Z" }, + { url = "https://files.pythonhosted.org/packages/45/0d/29c13f74ac43011aaafff9d9b23effefdf9243fcce764fed17087b1bd12c/xxhash-4.1.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:bdeaa333f8fbc237c5e62e0fb70e694dbfde62d15e242be23ba491ecd706e520", size = 271153, upload-time = "2026-11-09T13:46:51.737Z" }, + { url = "https://files.pythonhosted.org/packages/ef/89/d01eedb87d3ef1f7ec81080a160acd7ba42f29a43706b36d7fb4a8192706/xxhash-4.1.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:7c6bcd4eeeb5411a176b1a63dc505de99cd6182e88b02722d4407f96cf082e62", size = 327241, upload-time = "2026-11-09T13:46:48.482Z" }, + { url = "https://files.pythonhosted.org/packages/69/6a/82eb13aff0e06861cf2ff7a5b4e91092a3e7f7da5442c8be19e4c876d1a4/xxhash-4.1.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9f200a2bc05bade88e7c50c28d2a6637468ff0bacbcf1720928ae55b905bb1af", size = 474740, upload-time = "2026-11-09T13:46:48.76Z" }, + { url = "https://files.pythonhosted.org/packages/64/eb/0859f45d7b690f44704f3d8dc9a6a00eea931bcb0f3c5f5da7799a8740bb/xxhash-4.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e8b54cf9df8802572be9b8af0e3c1bc9eae80f653cd16f97d340a0098c48bb9c", size = 453590, upload-time = "2026-11-09T13:46:51.495Z" }, + { url = "https://files.pythonhosted.org/packages/18/99/e74773a5bc7b8decc874f0c74fb13e2058259101c6f54f87ecf07709e030/xxhash-4.1.0-cp311-cp311-win32.whl", hash = "sha256:b0042c684cf5739352d47afa77d387300805773a756f3677c1113481015934d6", size = 45112, upload-time = "2026-11-09T13:46:51.691Z" }, + { url = "https://files.pythonhosted.org/packages/5d/5f/299d6c8733add97f1b3e25f102dc473cd25b7ca147e6a828ec560c9740f2/xxhash-4.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:306a5538aa1152a3c411ebcce31a824721159495f391290ddcfa5b3f07c051a5", size = 48163, upload-time = "2026-11-09T13:46:48.804Z" }, + { url = "https://files.pythonhosted.org/packages/49/ee/e6d087e0fb37800c84ad842a4f6989ae3bc24964b63440fef1c89ec7f0e9/xxhash-4.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:bf3ebcbed4efff1ec177385e4b906c8ba75881d975ea59f49aa6edc2d37752aa", size = 33410, upload-time = "2026-11-09T13:46:51.735Z" }, + { url = "https://files.pythonhosted.org/packages/c0/41/89fa8c4f2d1190f8a9efca46f5779bdb4481356aec35119529e1ba91d35c/xxhash-4.1.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:d7a55bb01f866f948a4439e325e3e92645d97ca22c43777d2a71e7e51b63a986", size = 47341, upload-time = "2026-11-09T13:49:04.925Z" }, + { url = "https://files.pythonhosted.org/packages/93/5c/aa12a2f255cceb0941fa706d802bd502f64d42a76f17ea68ad62d860499b/xxhash-4.1.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:50e76857c8c47d8feb48ff1de711eaccfc5d28d97a5b1f7bd449b20796ecbf2b", size = 33938, upload-time = "2026-11-09T13:47:34.712Z" }, + { url = "https://files.pythonhosted.org/packages/c8/d1/d009e49747f1344c5c6fce52d67dfd53dfd0a0e75c4525abfc1dac44380b/xxhash-4.1.0-pp311-pypy311_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:49471b564ebae5d664daae4ecb2a02b03dc2e86f2065ed49f85e9367e8ca1428", size = 61619, upload-time = "2026-11-09T13:49:08.256Z" }, + { url = "https://files.pythonhosted.org/packages/9f/b7/473abf21c56969387bf90ac1d36bfbef620776bbe43a66ab4b1dc9fe0f1a/xxhash-4.1.0-pp311-pypy311_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2967f41d315ef1f9530af306ab79af7e5e6f3a4fdb3f02228bfc39414c11c273", size = 42795, upload-time = "2026-11-09T13:47:27.548Z" }, + { url = "https://files.pythonhosted.org/packages/e8/91/7981fb798edebeb130f95bd062f71f2512178af37925da889638ad63eb64/xxhash-4.1.0-pp311-pypy311_pp80-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0dcfb880344d6f1ed6feb867a898031b942f9c158f777c9ad678c078d7614b99", size = 47906, upload-time = "2026-11-09T13:47:30.555Z" }, + { url = "https://files.pythonhosted.org/packages/30/01/3876a8938f4dab623b501c77e874d7b3ac211fb1871e3bb236815dc66499/xxhash-4.1.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:100efa355bcc08b60a719926f9ce3c9ebf21cfa61db0a3bf43ebf64686d66ea3", size = 95476, upload-time = "2026-11-09T13:47:35.059Z" }, +] + +[[package]] +name = "yarl" +version = "1.25.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/75/16/e8be8e2fb175bbf41a0680381a319f1199fae256588241a2ac8677eafb49/yarl-1.25.1.tar.gz", hash = "sha256:03dd38de09bc213e9a8b29761eec33ee1d5318dac0e49d8af36e4d27830e23a7", size = 246245, upload-time = "2026-09-15T19:35:02.264Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/b3/2cea721d495ca57f8f414aa4867ee263f486b274e07463158cf52f02ba7f/yarl-1.25.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9d693bf4bf534e9ba3ae2780cfd577f5135629f7b5ac653490859d0b77864865", size = 143794, upload-time = "2026-09-15T19:30:26.946Z" }, + { url = "https://files.pythonhosted.org/packages/55/e6/cd145cff8e5cf60b8b3c41fbecfa2a45028a8dec3fbc52bec03595ff3d3b/yarl-1.25.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ab2054c5531af2a9ba7b69b8ec91e4f884420e83a8c5e579b013084cb57e5e5d", size = 103993, upload-time = "2026-09-15T19:30:28.661Z" }, + { url = "https://files.pythonhosted.org/packages/ce/7c/fbb40fe2d53747c40aa36a9e2bd2178a202f942bda0b670f3306d4aefbce/yarl-1.25.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:564fdc7085d2245ab84f88882fdb1d6ac0723124bff6ded35bfb1c00f812630d", size = 104010, upload-time = "2026-09-15T19:30:31.069Z" }, + { url = "https://files.pythonhosted.org/packages/f0/0b/5a516f70641092283f57cf3670bdb75e7327bcc0dcb5038697e4dfbfd569/yarl-1.25.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:acae6b45d1ace09b6ba3876da43b88366ef368f73b988c7f57e14231753d4420", size = 116444, upload-time = "2026-09-15T19:30:32.894Z" }, + { url = "https://files.pythonhosted.org/packages/b6/8a/d1a627f827b0a404ae0f5647cab0534959081cde13b0756a783469fb3b5e/yarl-1.25.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1fb2a01ba8cd9c5d2c5dc1ec35e0fc951d04b4f037541d4ac090c993ce58b3d7", size = 107565, upload-time = "2026-09-15T19:30:35.188Z" }, + { url = "https://files.pythonhosted.org/packages/aa/cf/c8e0aaec886840a6c4480fe44eaec7cd4319f79a563b79321473be79c56f/yarl-1.25.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e92b6bcc741b86d67606c40d3cb9c7cc8e6c737f81e31f4a94efc204456c92e3", size = 125006, upload-time = "2026-09-15T19:30:37.1Z" }, + { url = "https://files.pythonhosted.org/packages/50/26/0cce366d54a93cdc8342965dc7663385e4db161625cc1e8b18e786753d24/yarl-1.25.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:72c34ac7ad4314c19362d5ce27626dcc8429bd30bbf8c179f4234078851f9492", size = 128717, upload-time = "2026-09-15T19:30:38.904Z" }, + { url = "https://files.pythonhosted.org/packages/95/0c/a71501bbc1a674ff72c4d6c2b75f4d9a5af819f5244c3a7558080a8802c5/yarl-1.25.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d5add7b4ca7afeea91d52e4d4e4db3b1fe9885b71f07054560d8c4296b7441a2", size = 117728, upload-time = "2026-09-15T19:30:40.809Z" }, + { url = "https://files.pythonhosted.org/packages/e7/6f/c3267ca01defeed9ed9c4ff9b17bd54915432c405945233265b707475d1c/yarl-1.25.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:def538065f9e4d4cf1ae164bd59aba00dfa84f03923e0de4c3788f252d6bcd17", size = 116224, upload-time = "2026-09-15T19:30:42.818Z" }, + { url = "https://files.pythonhosted.org/packages/8f/69/fad57ee52d648431718ee0f1f68966a99c1352c3924688ffbdcc9d3fe51a/yarl-1.25.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0a191bfdb30a79b98e5d175d75285f9fcb78bf0e46ba5efda042e1c72071a0de", size = 116299, upload-time = "2026-09-15T19:30:44.966Z" }, + { url = "https://files.pythonhosted.org/packages/2a/d4/6a8c1e29f33338687ca278cba0a8fbf6525a322c2c02a9a500ccbe041152/yarl-1.25.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:71f42c5b9a948c113bbdebfa544598321431d064ff959d32e99b1feb61d68345", size = 108625, upload-time = "2026-09-15T19:30:46.874Z" }, + { url = "https://files.pythonhosted.org/packages/e8/d2/3a35ae791c9cb6522c106923ff25c3230d999091e5e65511bca23bbd9914/yarl-1.25.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:72849d892954be4d09e569b8b831ac39ce58417fedc767d4308a0fe542018a40", size = 124515, upload-time = "2026-09-15T19:30:49.082Z" }, + { url = "https://files.pythonhosted.org/packages/be/fd/2b022109a6b4af0f7dc371cf7500af380b0d4f034010243e1b0ce218dc93/yarl-1.25.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:efb01a106f971cb3752856bca2318bbdf7f01bd8823779c461586cbe5ffd5258", size = 115711, upload-time = "2026-09-15T19:30:51.208Z" }, + { url = "https://files.pythonhosted.org/packages/18/59/f7586271136c3ddb0126bbfe661844699369b76b555fe38c4efe86870b2e/yarl-1.25.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:a1daf47cd95a7c3a63456336bc5aaa8c86dd3a47d07ed3d0e76132ae4666a5a1", size = 122751, upload-time = "2026-09-15T19:30:53.535Z" }, + { url = "https://files.pythonhosted.org/packages/a0/0b/07f7a2d881f7e16c385b47fc1753382600847cad305dcc7fa0c25828acf8/yarl-1.25.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9489e6abf47ba37f332075a91444c7cfedb03e6ce99fbb2f116bfe1ce810da3b", size = 117983, upload-time = "2026-09-15T19:30:55.277Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9d/8cdceec66a9b940700cb45931741403f045b162afd79bcb93c41cadd0972/yarl-1.25.1-cp311-cp311-win_amd64.whl", hash = "sha256:d7306dee25b8a0e737363f347362b875094b4dc4e367311470656ae420fdbf8e", size = 102894, upload-time = "2026-09-15T19:30:57.606Z" }, + { url = "https://files.pythonhosted.org/packages/17/f1/7ec357db1d3ad2863542d71e8fe64a126bbec17b134cd7d30951196809a5/yarl-1.25.1-cp311-cp311-win_arm64.whl", hash = "sha256:abb1384477f5901d436b5d2e5465954de46ea6098f59163d243660b5c4461d35", size = 98609, upload-time = "2026-09-15T19:30:59.705Z" }, + { url = "https://files.pythonhosted.org/packages/54/22/318c7980066769c6bcd9221ed2248294f5698811da099013098c670565ed/yarl-1.25.1-py3-none-any.whl", hash = "sha256:681c758b0490f9e96b78e5fa8e8dc6e648e9185bb6eaebe73183c33ea0c445f3", size = 63617, upload-time = "2026-09-15T19:34:59.616Z" }, +] diff --git a/baselines/lozo/.python-version b/baselines/lozo/.python-version new file mode 100644 index 0000000..ed7d51a --- /dev/null +++ b/baselines/lozo/.python-version @@ -0,0 +1 @@ +3.11.15 diff --git a/baselines/lozo/README.md b/baselines/lozo/README.md new file mode 100644 index 0000000..3e51984 --- /dev/null +++ b/baselines/lozo/README.md @@ -0,0 +1,45 @@ +# LOZO: Enhancing Zeroth-order fine-tuning for language models with low-rank structures + +This is the implementation for the paper [Enhancing Zeroth-order fine-tuning for language models with low-rank structures](https://arxiv.org/pdf/2410.07698). + + +In this paper, we design a low-rank gradient estimator for the zeroth-order (ZO) method and propose a novel low-rank ZO-SGD (LOZO) algorithm for fine-tuning large language models (LLMs). Additionally, we introduce an approach to combine our LOZO algorithm with the momentum technique, resulting in the low-rank ZO-SGD with momentum (LOZO-M) algorithm, which incurs almost no additional memory overhead compared to the LOZO algorithm. + +Compared to existing ZO methods for LLM fine-tuning, such as [MeZO](https://github.com/princeton-nlp/MeZO), the LOZO and LOZO-M algorithms achieve superior performance across a range of tasks and model scales, along with faster convergence rates. + +

+ Fig + + Left: GPU memory usage comparison between LOZO and MeZO with their respective variants. Right: Performance of MeZO, MeZO-LoRA, FT, FT-LoRA, LOZO, and LOZO-M on RoBERTa-large across three tasks (SNLI, MNLI, and RTE). + +

+ +

+ Fig + + Left: Loss curves of OPT-13B on SQuAD dataset. Middle: Loss curves of OPT-30B on SST-2 dataset. Right: Loss curves of OPT-66B on WIC dataset. LOZO consistently yields faster convergence speed comapred to the baseline. + +

+ + +## Reproduce our paper results + +For reproducing RoBERTa-large experiments, please refer to the [medium_models](https://github.com/optsuite/LOZO/tree/main/medium_models) folder. For autoregressive LM (OPT) experiments, please refer to the [large_models](https://github.com/optsuite/LOZO/tree/main/large_models) folder. + + +## Bugs or questions? + +If you have any questions related to the code or the paper, feel free to email Yiming Chen (`abcdcym@gmail.com`) or Yuan Zhang (`zy1002@stu.pku.edu.cn`). If you encounter any problems when using the code, or want to report a bug, you can open an issue. Please provide specific details about the problem so that we can assist you more effectively and efficiently! + + + +## Citation + +```bibtex +@article{chen2024enhancing, + title={Enhancing Zeroth-order Fine-tuning for Language Models with Low-rank Structures}, + author={Chen, Yiming and Zhang, Yuan and Cao, Liyuan and Yuan, Kun and Wen, Zaiwen}, + journal={arXiv preprint arXiv:2410.07698}, + year={2024} +} +``` diff --git a/baselines/lozo/TROUBLESHOOTING.md b/baselines/lozo/TROUBLESHOOTING.md new file mode 100644 index 0000000..39af5fd --- /dev/null +++ b/baselines/lozo/TROUBLESHOOTING.md @@ -0,0 +1,81 @@ +# LOZO:独立环境、入口与排障 + +官方来源:https://github.com/optsuite/LOZO.git;锁定提交:`5d1ade5bf41846471d33ba526f877829b9a19856`。 +官方文件保留原样;此目录新增 pyproject.toml、uv.lock、native.py、run_compatible.py 和本文。 +原仓库 Git 历史存放在被忽略的 `.upstream-git/`,防止主项目意外把整个目录当成 gitlink。 +查看上游版本:`git --git-dir=.upstream-git --work-tree=. rev-parse HEAD`。 +不要在这个目录执行普通 git commit/push;主项目尚未提交。 + +## 安装与版本 + +在 WSL 中执行(不需要激活根目录环境): + +```bash +cd ~/experiments_codebase +source scripts/env.sh +cd baselines/lozo +uv sync --locked +uv run --locked python native.py --help +``` + +此目录 `.venv` 独立,Python 3.11,torch 2.13.0,原生 Transformers 4.28.1。 +直接依赖精确版本写在 pyproject.toml,全部间接依赖和 wheel 哈希写在 uv.lock。 +`uv sync --locked` 默认 native;`uv sync --locked --no-default-groups --group modern` 切换到 Transformers 4.57.1。 +两组互斥,使用同一个本库 `.venv`,不会激活其他方法的环境。不要使用 `uv pip install -U` 绕开锁。 + +## 官方入口及命令 + +原入口 `large_models/run_lozo.py`。本地资源包装入口 `native.py` 仅设置共享路径、提供本地 Dataset 和启动参数,然后运行原始程序。 +`--asset-model`、`--asset-task`、`--asset-out` 是包装参数,其余参数透传官方入口;以 `--help` 为准。 +MeZO/LOZO/AGZO包装器默认固定 train_set_seed=42,并将result_file显式指向共享输出;否则原版会因num_dev配合空采样seed触发断言,或因相对result目录缺失在训练完成后报错。用户后置同名参数可覆盖这些默认值。 + +```bash +uv run --locked python native.py --asset-model facebook/opt-1.3b --asset-task sst2 --max_steps 2 --num_train 16 --num_dev 4 --num_eval 4 --per_device_train_batch_size 2 --learning_rate 1e-6 --zo_eps 1e-3 --rank_r 1 --step_interval 100 --evaluation_strategy no --save_strategy no --logging_steps 1 +``` + +调参请使用官方参数:学习率 `--learning_rate`,差分半径 `--zo_eps`,batch `--per_device_train_batch_size`。 +参数覆盖:MeZO/LOZO/AGZO 默认 full(不传 LoRA/prefix/head-only 开关);LOREN 包装器显式传 `--full_parameter`。 +全参数覆盖不等于无结构全维搜索;LOZO/AGZO 仍使用结构化扰动。 + +## Qwen3 / DROP 与统一比较入口 + +```bash +uv run --locked --no-default-groups --group modern python run_compatible.py --model Qwen/Qwen3-0.6B --task sst2 --budget 12 --train-samples 16 --dev-samples 4 --eval-samples 4 --batch-size 2 --eval-batch-size 2 --calibration-samples 2 --no-save-checkpoint +# DROP:将 --task 改为 drop,并合理增加 --max-length(短冒烟可以先用128)。 +``` + +兼容层 `../../src/experiments_codebase/official.py` 从本库源码编译官方数值函数;不导入旧 Trainer,也不另写一套公式。 +通用数据协议和计账在 `../../src/experiments_codebase/task.py`、`runner.py`。 +此入口统一 SST2 为两 verbalizer 的交叉熵、DROP 为答案 token 的 teacher-forced CE;它与部分官方任务目标不同,日志会标记 task adapter。 +预算为总 main forward,而非更新步数;检测和基提取前向不免费。评估前向另列。 +不支持从兼容检查点续训;可用 `--action evaluate --checkpoint ...` 或 `--action generate --checkpoint ... --prompt ...` 推理。 + +## 核心位置 + +- 核心算法:`large_models/LOZOtrainer.py: lowrank_zo_step / lowrank_zo_update`。 +- 模型/数据:`large_models/run_lozo.py: Framework; large_models/tasks.py / templates.py`。 +- 官方超参数原型:入口中的参数 dataclass/parser 与原始 shell 脚本;与本站兼容入口参数不是同一命名空间。 + +## 系统组件与常见问题 + +原版 lowrank_zo_update 在刷新 V 的步骤没有重放对应随机数消耗,历史审计发现其更新方向与扰动方向可不一致。原生入口保留原样;兼容入口只有显式传 --lozo-rng-fix 才启用修正,必须将它作为独立算法变体报告。原生 4.28.1 同样不支持 Qwen3。 + +WSL 必须能看到 NVIDIA 驱动:先运行 `nvidia-smi`。RTX 5070 Ti 是 Blackwell;原论文旧版 torch/CUDA wheel 不支持其架构。 +本机选用支持当前显卡的 torch 2.13.0,不声称完全复刻论文年代的二进制环境。 +CUDA runtime 随 wheel 安装,普通运行无需 nvcc;自编译第三方扩展才需要 CUDA toolkit、gcc/g++、make、Python headers。 +Fedora 常见系统依赖:`git curl ca-certificates libgomp libstdc++`;缺库先用 `ldd` 核查,不要盲目替换驱动。 +uv 会下载 Python 3.11,不依赖系统 Python 3.14;保持 `.python-version`。 +如果 WSL 解析到 198.18.* 且直连超时,可在未跟踪的根 `.env` 配置你现有代理,再 `source ../../scripts/env.sh`;不要把代理/token 写入源码。 +本次用临时 HTTP(S)_PROXY 沿用主机代理;未修改系统网络配置。 +`huggingface-hub` 不能随意升到2.x:Transformers 4.x 需要 <1.0。已锁0.36.0。 +新版setuptools移除了pkg_resources,旧Trainer/accelerate仍导入它;锁80.9.0同时满足torch要求的>=77.0.3。LOREN官方requirements漏列loguru,本环境已补0.7.3。 +旧 datasets/pyarrow/numpy 有 ABI 约束,三者必须遵守 uv.lock;不能拿现代 `.venv` 的 site-packages 混入原生环境。 +共享DROP不能用datasets5.x的List元数据序列化后直接给2.x/3.x读;请在根锁定环境datasets3.6执行prepare_assets,工具可从原始parquet重建不兼容资产。 +E盘必须真实挂载。Assets默认位于 `/mnt/e/Experiments/Assets`,包装器在写入前检查 mountpoint。 +模型和数据只从本地共享目录读取;资产缺失先在根环境运行 `scripts/prepare_assets.py --download-missing`。 +Qwen的词表较大,长序列或大 batch 会增显存;先减batch/长度,不要把OOM归因于优化算法。 + +## 验证状态 + +以根目录 `reports/validation_report.json` 和 `reports/validation.log` 为准,区分安装、导入、短步训练、模型任务矩阵。 +`--help` 通过不代表训练通过,短步通过也不代表论文精度复现。未完成项目会明确记录。 diff --git a/baselines/lozo/assets/combined_loss_vs_epochs.png b/baselines/lozo/assets/combined_loss_vs_epochs.png new file mode 100644 index 0000000..63747a0 Binary files /dev/null and b/baselines/lozo/assets/combined_loss_vs_epochs.png differ diff --git a/baselines/lozo/assets/memory_and_k16.png b/baselines/lozo/assets/memory_and_k16.png new file mode 100644 index 0000000..a96a69b Binary files /dev/null and b/baselines/lozo/assets/memory_and_k16.png differ diff --git a/baselines/lozo/large_models/LOZOtrainer.py b/baselines/lozo/large_models/LOZOtrainer.py new file mode 100644 index 0000000..6f351c6 --- /dev/null +++ b/baselines/lozo/large_models/LOZOtrainer.py @@ -0,0 +1,914 @@ +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. +""" + +import contextlib +import functools +import glob +import inspect +import math +import os +import random +import re +import shutil +import sys +import time +import warnings +from collections.abc import Mapping +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union +import copy +from metrics import f1 +import numpy as np + +from tqdm.auto import tqdm +from transformers import Trainer +from sklearn.linear_model import LinearRegression, LogisticRegression, LogisticRegressionCV + +# Integrations must be imported before ML frameworks: +from transformers.integrations import ( # isort: split + default_hp_search_backend, + get_reporting_integration_callbacks, + hp_params, + is_fairscale_available, + is_optuna_available, + is_ray_tune_available, + is_sigopt_available, + is_wandb_available, + run_hp_search_optuna, + run_hp_search_ray, + run_hp_search_sigopt, + run_hp_search_wandb, +) + +import numpy as np +import torch +import torch.distributed as dist +from packaging import version +from torch import nn +from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler +from torch.utils.data.distributed import DistributedSampler + +from huggingface_hub import Repository + +from transformers import __version__ +from transformers.configuration_utils import PretrainedConfig +from transformers.data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator +from transformers.debug_utils import DebugOption, DebugUnderflowOverflow +from transformers.deepspeed import deepspeed_init, is_deepspeed_zero3_enabled +from transformers.dependency_versions_check import dep_version_check +from transformers.modelcard import TrainingSummary +from transformers.modeling_utils import PreTrainedModel, load_sharded_checkpoint, unwrap_model +from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_MAPPING_NAMES +from transformers.optimization import Adafactor, get_scheduler +from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_10, is_torch_less_than_1_11 +from transformers.tokenization_utils_base import PreTrainedTokenizerBase +from transformers.trainer_callback import ( + CallbackHandler, + DefaultFlowCallback, + PrinterCallback, + ProgressCallback, + TrainerCallback, + TrainerControl, + TrainerState, +) +from transformers.trainer_pt_utils import ( + DistributedLengthGroupedSampler, + DistributedSamplerWithLoop, + DistributedTensorGatherer, + IterableDatasetShard, + LabelSmoother, + LengthGroupedSampler, + SequentialDistributedSampler, + ShardSampler, + distributed_broadcast_scalars, + distributed_concat, + find_batch_size, + get_module_class_from_name, + get_parameter_names, + nested_concat, + nested_detach, + nested_numpify, + nested_truncate, + nested_xla_mesh_reduce, + reissue_pt_warnings, +) +from transformers.trainer_utils import ( + PREFIX_CHECKPOINT_DIR, + BestRun, + EvalLoopOutput, + EvalPrediction, + FSDPOption, + HPSearchBackend, + HubStrategy, + IntervalStrategy, + PredictionOutput, + RemoveColumnsCollator, + ShardedDDPOption, + TrainerMemoryTracker, + TrainOutput, + default_compute_objective, + default_hp_space, + denumpify_detensorize, + enable_full_determinism, + find_executable_batch_size, + get_last_checkpoint, + has_length, + number_of_arguments, + seed_worker, + set_seed, + speed_metrics, +) +from transformers.training_args import OptimizerNames, ParallelMode, TrainingArguments +from transformers.utils import ( + CONFIG_NAME, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, + find_labels, + get_full_repo_name, + is_apex_available, + is_datasets_available, + is_in_notebook, + is_ipex_available, + is_sagemaker_dp_enabled, + is_sagemaker_mp_enabled, + is_torch_tensorrt_fx_available, + is_torch_tpu_available, + is_torchdynamo_available, + logging, +) +from transformers.utils.generic import ContextManagers + + +_is_native_cpu_amp_available = is_torch_greater_or_equal_than_1_10 + +DEFAULT_CALLBACKS = [DefaultFlowCallback] +DEFAULT_PROGRESS_CALLBACK = ProgressCallback + +if is_in_notebook(): + from .utils import NotebookProgressCallback + + DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback + +if is_apex_available(): + from apex import amp + +if is_datasets_available(): + import datasets + +if is_torch_tpu_available(check_device=False): + import torch_xla.core.xla_model as xm + import torch_xla.debug.metrics as met + import torch_xla.distributed.parallel_loader as pl + +if is_fairscale_available(): + dep_version_check("fairscale") + import fairscale + from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP + from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP + from fairscale.nn.wrap import auto_wrap + from fairscale.optim import OSS + from fairscale.optim.grad_scaler import ShardedGradScaler + + +if is_sagemaker_mp_enabled(): + import smdistributed.modelparallel.torch as smp + from smdistributed.modelparallel import __version__ as SMP_VERSION + + IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse("1.10") + + from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat +else: + IS_SAGEMAKER_MP_POST_1_10 = False + + +if TYPE_CHECKING: + import optuna + +logger = logging.get_logger(__name__) + + +# Name of the files used for checkpointing +TRAINING_ARGS_NAME = "training_args.bin" +TRAINER_STATE_NAME = "trainer_state.json" +OPTIMIZER_NAME = "optimizer.pt" +SCHEDULER_NAME = "scheduler.pt" +SCALER_NAME = "scaler.pt" + + +class LowRankTrainer(Trainer): + + from transformers.trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state + + def _inner_training_loop( + self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None + ): + """ + We overload the original training loop to add linear probing and MeZO. Search key word "MeZO added" + for those updates. + """ + self._train_batch_size = batch_size + # Data loader and number of training steps + train_dataloader = self.get_train_dataloader() + + # MeZO added: Linear probing + if self.args.linear_probing: + + def _get_token_prediction_layer(model): + if model.config.model_type == "opt": + return model.lm_head + else: + raise NotImplementedError(model.config.model_type) + + def _extract_features(model, *args, **kwargs): + """some magic for getting features pre last layer""" + features = {} + def __hook(model_, input_, output_): + features["features"] = input_[0].detach() + + _get_token_prediction_layer(model).register_forward_hook(__hook) + model.forward(*args, **kwargs) + return features["features"] + + logger.info("Linear probing") + logger.info("Starting to get features for training dataset") + targets = [] + features = [] + with torch.inference_mode(): + for step, inputs in enumerate(tqdm(train_dataloader)): + for k, v in inputs.items(): + if isinstance(v, torch.Tensor): + inputs[k] = v.to(self.model.device) + + feature = _extract_features(self.model, **inputs) + target = inputs["labels"] + + # Shift the target (bc it's autoregressive LM) and add the corresponding part + assert not self.args.train_as_classification and self.args.only_train_option + feature, target = feature[:, :-1], target[:, 1:] + for _i, _len in enumerate(inputs["option_len"]): + features.append(feature[_i, -_len:]) + targets.append(target[_i, -_len:]) + + logger.info("Finished getting features for training dataset") + + features = torch.cat(features, dim=0).cpu().numpy() + targets = torch.cat(targets, dim=0).cpu().numpy() + # Whether to use bias + if self.model.config.model_type in ["opt", "gpt2"]: + use_bias = False + else: + raise NotImplementedError + # Set early stopping + tol = 0.01 if self.args.lp_early_stopping else 1e-4 # 1e-4 is scipy default + max_iter = 1000 if self.args.lp_early_stopping else 5000 + + logger.info("Fitting logistic regression...") + reg = LogisticRegressionCV(max_iter=max_iter, fit_intercept=use_bias, multi_class="multinomial", random_state=0, tol=tol, n_jobs=-1).fit(features, targets) + logger.info("Done") + + logger.info("Assigning weights to model") + decoder = _get_token_prediction_layer(self.model) + coef_torch = torch.tensor(reg.coef_, device=decoder.weight.device, dtype=decoder.weight.dtype) + if use_bias: + bias_torch = torch.tensor(reg.intercept_, device=decoder.weight.device, dtype=decoder.weight.dtype) + if coef_torch.shape[0] == 1: # The regressor only detects two classes + assert len(reg.classes_) == 2 + coef_torch = torch.cat([-coef_torch / 2, coef_torch / 2], dim=0) + if use_bias: + bias_torch = torch.cat([-bias_torch / 2, bias_torch / 2], dim=0) + + for _i, token_id in enumerate(reg.classes_): + decoder.weight.data[token_id] = coef_torch[_i] + if use_bias: + decoder.bias.data[token_id] = bias_torch[_i] + + return None + + # Setting up training control variables: + # number of training epochs: num_train_epochs + # number of training steps per epoch: num_update_steps_per_epoch + # total number of training steps to execute: max_steps + total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size + + len_dataloader = None + if has_length(train_dataloader): + len_dataloader = len(train_dataloader) + num_update_steps_per_epoch = len_dataloader // args.gradient_accumulation_steps + num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) + num_examples = self.num_examples(train_dataloader) + if args.max_steps > 0: + max_steps = args.max_steps + num_train_epochs = args.max_steps // num_update_steps_per_epoch + int( + args.max_steps % num_update_steps_per_epoch > 0 + ) + # May be slightly incorrect if the last batch in the training dataloader has a smaller size but it's + # the best we can do. + num_train_samples = args.max_steps * total_train_batch_size + else: + max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch) + num_train_epochs = math.ceil(args.num_train_epochs) + num_train_samples = self.num_examples(train_dataloader) * args.num_train_epochs + elif args.max_steps > 0: # Rely on max_steps when dataloader does not have a working size + max_steps = args.max_steps + # Setting a very large number of epochs so we go as many times as necessary over the iterator. + num_train_epochs = sys.maxsize + num_update_steps_per_epoch = max_steps + num_examples = total_train_batch_size * args.max_steps + num_train_samples = args.max_steps * total_train_batch_size + else: + raise ValueError( + "args.max_steps must be set to a positive value if dataloader does not have a length, was" + f" {args.max_steps}" + ) + + if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug: + if self.args.n_gpu > 1: + # nn.DataParallel(model) replicates the model, creating new variables and module + # references registered here no longer work on other gpus, breaking the module + raise ValueError( + "Currently --debug underflow_overflow is not supported under DP. Please use DDP" + " (torch.distributed.launch)." + ) + else: + debug_overflow = DebugUnderflowOverflow(self.model) # noqa + + delay_optimizer_creation = ( + self.sharded_ddp is not None + and self.sharded_ddp != ShardedDDPOption.SIMPLE + or is_sagemaker_mp_enabled() + or self.fsdp is not None + ) + if args.deepspeed: + deepspeed_engine, optimizer, lr_scheduler = deepspeed_init( + self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint + ) + self.model = deepspeed_engine.module + self.model_wrapped = deepspeed_engine + self.deepspeed = deepspeed_engine + self.optimizer = optimizer + self.lr_scheduler = lr_scheduler + elif not delay_optimizer_creation: + self.create_optimizer_and_scheduler(num_training_steps=max_steps) + # pass + self.state = TrainerState() + self.state.is_hyper_param_search = trial is not None + + # Activate gradient checkpointing if needed + if args.gradient_checkpointing: + self.model.gradient_checkpointing_enable() + + model = self._wrap_model(self.model_wrapped) + + if is_sagemaker_mp_enabled() and resume_from_checkpoint is not None: + self._load_from_checkpoint(resume_from_checkpoint, model) + + # for the rest of this function `model` is the outside model, whether it was wrapped or not + if model is not self.model: + self.model_wrapped = model + + if delay_optimizer_creation: + self.create_optimizer_and_scheduler(num_training_steps=max_steps) + + # Check if saved optimizer or scheduler states exist + self._load_optimizer_and_scheduler(resume_from_checkpoint) + + # important: at this point: + # self.model is the Transformers Model + # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc. + + # Train! + logger.info("***** Running training *****") + logger.info(f" Num examples = {num_examples}") + logger.info(f" Num Epochs = {num_train_epochs}") + logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") + logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}") + logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") + logger.info(f" Total optimization steps = {max_steps}") + logger.info( + f" Number of trainable parameters = {sum(p.numel() for p in model.parameters() if p.requires_grad)}" + ) + + self.state.epoch = 0 + start_time = time.time() + epochs_trained = 0 + steps_trained_in_current_epoch = 0 + steps_trained_progress_bar = None + + # Check if continuing training from a checkpoint + if resume_from_checkpoint is not None and os.path.isfile( + os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME) + ): + self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)) + epochs_trained = self.state.global_step // num_update_steps_per_epoch + if not args.ignore_data_skip: + steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch) + steps_trained_in_current_epoch *= args.gradient_accumulation_steps + else: + steps_trained_in_current_epoch = 0 + + logger.info(" Continuing training from checkpoint, will skip to saved global_step") + logger.info(f" Continuing training from epoch {epochs_trained}") + logger.info(f" Continuing training from global step {self.state.global_step}") + if not args.ignore_data_skip: + logger.info( + f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} " + "batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` " + "flag to your launch command, but you will resume the training on data already seen by your model." + ) + if self.is_local_process_zero() and not args.disable_tqdm: + steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch) + steps_trained_progress_bar.set_description("Skipping the first batches") + + # Update the references + self.callback_handler.model = self.model + self.callback_handler.optimizer = self.optimizer + self.callback_handler.lr_scheduler = self.lr_scheduler + self.callback_handler.train_dataloader = train_dataloader + if self.hp_name is not None and self._trial is not None: + # use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial + # parameter to Train when using DDP. + self.state.trial_name = self.hp_name(self._trial) + if trial is not None: + assignments = trial.assignments if self.hp_search_backend == HPSearchBackend.SIGOPT else trial + self.state.trial_params = hp_params(assignments) + else: + self.state.trial_params = None + # This should be the same if the state has been saved but in case the training arguments changed, it's safer + # to set this after the load. + self.state.max_steps = max_steps + self.state.num_train_epochs = num_train_epochs + self.state.is_local_process_zero = self.is_local_process_zero() + self.state.is_world_process_zero = self.is_world_process_zero() + + # tr_loss is a tensor to avoid synchronization of TPUs through .item() + tr_loss = torch.tensor(0.0).to(args.device) + # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses + self._total_loss_scalar = 0.0 + self._globalstep_last_logged = self.state.global_step + model.zero_grad() + + self.control = self.callback_handler.on_train_begin(args, self.state, self.control) + + # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. + if not args.ignore_data_skip: + for epoch in range(epochs_trained): + is_random_sampler = hasattr(train_dataloader, "sampler") and isinstance( + train_dataloader.sampler, RandomSampler + ) + if is_torch_less_than_1_11 or not is_random_sampler: + # We just need to begin an iteration to create the randomization of the sampler. + # That was before PyTorch 1.11 however... + for _ in train_dataloader: + break + else: + # Otherwise we need to call the whooooole sampler cause there is some random operation added + # AT THE VERY END! + _ = list(train_dataloader.sampler) + + for epoch in range(epochs_trained, num_train_epochs): + if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): + train_dataloader.sampler.set_epoch(epoch) + elif hasattr(train_dataloader, "dataset") and isinstance(train_dataloader.dataset, IterableDatasetShard): + train_dataloader.dataset.set_epoch(epoch) + + if is_torch_tpu_available(): + parallel_loader = pl.ParallelLoader(train_dataloader, [args.device]).per_device_loader(args.device) + epoch_iterator = parallel_loader + else: + epoch_iterator = train_dataloader + + # Reset the past mems state at the beginning of each epoch if necessary. + if args.past_index >= 0: + self._past = None + + steps_in_epoch = ( + len(epoch_iterator) + if len_dataloader is not None + else args.max_steps * args.gradient_accumulation_steps + ) + self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control) + + if epoch == epochs_trained and resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0: + self._load_rng_state(resume_from_checkpoint) + + step = -1 + for step, inputs in enumerate(epoch_iterator): + + # Skip past any already trained steps if resuming training + if steps_trained_in_current_epoch > 0: + steps_trained_in_current_epoch -= 1 + if steps_trained_progress_bar is not None: + steps_trained_progress_bar.update(1) + if steps_trained_in_current_epoch == 0: + self._load_rng_state(resume_from_checkpoint) + continue + elif steps_trained_progress_bar is not None: + steps_trained_progress_bar.close() + steps_trained_progress_bar = None + + if step % args.gradient_accumulation_steps == 0: + self.control = self.callback_handler.on_step_begin(args, self.state, self.control) + + # MeZO added: estimate gradient + if args.trainer == "LOZO": + tr_loss_step = self.lowrank_zo_step(model, inputs) + else: + if ( + ((step + 1) % args.gradient_accumulation_steps != 0) + and args.local_rank != -1 + and args._no_sync_in_gradient_accumulation + ): + # Avoid unnecessary DDP synchronization since there will be no backward pass on this example. + with model.no_sync(): + tr_loss_step = self.training_step(model, inputs) + else: + tr_loss_step = self.training_step(model, inputs) + + if ( + args.logging_nan_inf_filter + and not is_torch_tpu_available() + and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step)) + ): + # if loss is nan or inf simply add the average of previous logged losses + tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged) + else: + tr_loss += tr_loss_step + + self.current_flos += float(self.floating_point_ops(inputs)) + + # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps + if self.deepspeed: + self.deepspeed.step() + + if (step + 1) % args.gradient_accumulation_steps == 0 or ( + # last step in epoch but step is always smaller than gradient_accumulation_steps + steps_in_epoch <= args.gradient_accumulation_steps + and (step + 1) == steps_in_epoch + ): + # MeZO added: update model with the estimated gradient + if args.trainer == "LOZO": + self.lowrank_zo_update() + else: + # Gradient clipping + if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed: + # deepspeed does its own clipping + + if self.do_grad_scaling: + # Reduce gradients first for XLA + if is_torch_tpu_available(): + gradients = xm._fetch_gradients(self.optimizer) + xm.all_reduce("sum", gradients, scale=1.0 / xm.xrt_world_size()) + # AMP: gradients need unscaling + self.scaler.unscale_(self.optimizer) + + if is_sagemaker_mp_enabled() and args.fp16: + self.optimizer.clip_master_grads(args.max_grad_norm) + elif hasattr(self.optimizer, "clip_grad_norm"): + # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping + self.optimizer.clip_grad_norm(args.max_grad_norm) + elif hasattr(model, "clip_grad_norm_"): + # Some models (like FullyShardedDDP) have a specific way to do gradient clipping + model.clip_grad_norm_(args.max_grad_norm) + else: + # Revert to normal clipping otherwise, handling Apex or full precision + nn.utils.clip_grad_norm_( + amp.master_params(self.optimizer) if self.use_apex else model.parameters(), + args.max_grad_norm, + ) + + # Optimizer step + optimizer_was_run = True + if self.deepspeed: + pass # called outside the loop + elif is_torch_tpu_available(): + if self.do_grad_scaling: + self.scaler.step(self.optimizer) + self.scaler.update() + else: + xm.optimizer_step(self.optimizer) + elif self.do_grad_scaling: + scale_before = self.scaler.get_scale() + self.scaler.step(self.optimizer) + self.scaler.update() + scale_after = self.scaler.get_scale() + optimizer_was_run = scale_before <= scale_after + else: + self.optimizer.step() + + if optimizer_was_run and not self.deepspeed: + self.lr_scheduler.step() + model.zero_grad() + + self.state.global_step += 1 + self.state.epoch = epoch + (step + 1) / steps_in_epoch + self.control = self.callback_handler.on_step_end(args, self.state, self.control) + + self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval) + else: + self.control = self.callback_handler.on_substep_end(args, self.state, self.control) + + if self.control.should_epoch_stop or self.control.should_training_stop: + break + if step < 0: + logger.warning( + "There seems to be not a single sample in your epoch_iterator, stopping training at step" + f" {self.state.global_step}! This is expected if you're using an IterableDataset and set" + f" num_steps ({max_steps}) higher than the number of available samples." + ) + self.control.should_training_stop = True + + self.control = self.callback_handler.on_epoch_end(args, self.state, self.control) + self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval) + + if DebugOption.TPU_METRICS_DEBUG in self.args.debug: + if is_torch_tpu_available(): + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + else: + logger.warning( + "You enabled PyTorch/XLA debug metrics but you don't have a TPU " + "configured. Check your training configuration if this is unexpected." + ) + if self.control.should_training_stop: + break + + if args.past_index and hasattr(self, "_past"): + # Clean the state at the end of training + delattr(self, "_past") + + logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") + if args.load_best_model_at_end and self.state.best_model_checkpoint is not None: + # Wait for everyone to get here so we are sur the model has been saved by process 0. + if is_torch_tpu_available(): + xm.rendezvous("load_best_model_at_end") + elif args.local_rank != -1: + dist.barrier() + elif is_sagemaker_mp_enabled(): + smp.barrier() + + self._load_best_model() + + # add remaining tr_loss + self._total_loss_scalar += tr_loss.item() + train_loss = self._total_loss_scalar / self.state.global_step + + metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps) + self.store_flos() + metrics["total_flos"] = self.state.total_flos + metrics["train_loss"] = train_loss + + self.is_in_train = False + + self._memory_tracker.stop_and_update_metrics(metrics) + + self.log(metrics) + + run_dir = self._get_output_dir(trial) + checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir) + + # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint. + if self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1: + for checkpoint in checkpoints_sorted: + if checkpoint != self.state.best_model_checkpoint: + logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") + shutil.rmtree(checkpoint) + + self.control = self.callback_handler.on_train_end(args, self.state, self.control) + + return TrainOutput(self.state.global_step, train_loss, metrics) + + + # =========================================== LOZO Functions ============================================================== + + + def lowrank_zo_perturb_parameters(self, random_seed=None, scaling_factor=1): + """ + Perturb the parameters with random vector uv^t. + """ + args = self.args + step = self.step + + torch.manual_seed(random_seed if random_seed is not None else self.zo_random_seed) + + for name, param in self.named_parameters_to_optim: + if param.data.ndim >= 2: + if step % args.step_interval == 0: + v = torch.randn(param.data.size(1), args.rank_r, device=param.data.device, dtype=param.data.dtype) + self.v[name] = v + else: + v = self.v[name] + u = self.random_gaussian_matrix(m=param.data.size(0), n=args.rank_r, device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * (u@v.t()) * self.args.zo_eps + else: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * self.args.zo_eps + + def zo_forward(self, model, inputs): + """ + Get (no gradient) loss from the model. Dropout is turned off too. + """ + model.eval() + if self.args.non_diff: + # Non-differentiable objective (may require autoregressive generation) + return self.zo_forward_nondiff(model, inputs) + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + # Warning: this is copied from the original Huggingface Trainer. Untested. + loss = loss.mean() # mean() to average on multi-gpu parallel training + return loss.detach() + + + def zo_forward_nondiff(self, model, inputs): + """ + Get (no gradient) non-diffiable loss from the model. + """ + model.eval() + assert self.args.task_name == "SQuAD", "Non differentiable objective only supports SQuAD for now." + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + args = self.args + outputs = self.model.generate( + inputs["input_ids"], do_sample=args.sampling, temperature=args.temperature, + num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - inputs["input_ids"].size(1)), + num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id], + ) + output_text = [] + for i in range(len(outputs)): + output_text.append(self.tokenizer.decode(outputs[i][inputs["input_ids"].size(1):], skip_special_tokens=True).strip()) + f1s = [f1(output_text[i], inputs['gold'][i]) for i in range(len(output_text))] + + return -torch.tensor(np.mean(f1s), dtype=torch.float32) + + + def lowrank_zo_step(self, model, inputs): + """ + Estimate gradient by Lowrank-zo. Return the loss from f(theta + uv^t) + """ + args = self.args + if hasattr(self, 'step'): + self.step += 1 + else: + self.step = 0 + self.v = {} + + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + + # Sample the random seed for sampling + self.zo_random_seed = np.random.randint(1000000000) + + # First function evaluation + self.lowrank_zo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + # Second function evaluation + self.lowrank_zo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + + # No gradient accumulation support + assert self.args.gradient_accumulation_steps == 1 + + # Reset model back to its parameters at start of step + self.lowrank_zo_perturb_parameters(scaling_factor=1) + return loss1 + + + def lowrank_zo_update(self): + args = self.args + + # Reset the random seed for sampling + torch.manual_seed(self.zo_random_seed) + + for name, param in self.named_parameters_to_optim: + if param.data.ndim >= 2: + v = self.v[name] + u = self.random_gaussian_matrix(m=param.data.size(0), n=args.rank_r, device=param.data.device, dtype=param.data.dtype) + + if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * (u@v.t()) + args.weight_decay * param.data) + else: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * (u@v.t())) + else: + # Resample z for bias + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * z + args.weight_decay * param.data) + else: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * z) + + self.lr_scheduler.step() + + def random_gaussian_matrix(self, m, n, device, dtype, random_seed=None): + if random_seed is not None: + torch.manual_seed(random_seed) + + random_matrix = torch.randn(m, n, device=device, dtype=dtype) + return random_matrix + + ############## Misc overload functions ############## + + + def _set_signature_columns_if_needed(self): + """ + We overload this function for non-differentiable objective training to pass "gold" -- the gold text for the task + """ + if self._signature_columns is None: + # Inspect model forward signature to keep only the arguments it accepts. + signature = inspect.signature(self.model.forward) + self._signature_columns = list(signature.parameters.keys()) + # Labels may be named label or label_ids, the default data collator handles that. + self._signature_columns += list(set(["label", "label_ids"] + self.label_names)) + self._signature_columns += ["gold"] + + + def save_model(self, output_dir: Optional[str] = None, _internal_call: bool = False): + """ + We overload this function to fix an FSDP saving bug (before fix, it will likely cause OOM) + """ + + if output_dir is None: + output_dir = self.args.output_dir + + if is_torch_tpu_available(): + self._save_tpu(output_dir) + elif is_sagemaker_mp_enabled(): + # Calling the state_dict needs to be done on the wrapped model and on all processes. + os.makedirs(output_dir, exist_ok=True) + state_dict = self.model_wrapped.state_dict() + if self.args.should_save: + self._save(output_dir, state_dict=state_dict) + if IS_SAGEMAKER_MP_POST_1_10: + # 'user_content.pt' indicates model state_dict saved with smp >= 1.10 + Path(os.path.join(output_dir, "user_content.pt")).touch() + elif ( + ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp + or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp + or self.fsdp is not None + ): + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, StateDictType, FullStateDictConfig + full_state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) + + # Fix the FSDP loading bug + with FSDP.state_dict_type(self.model, StateDictType.FULL_STATE_DICT, full_state_dict_config): + state_dict = self.model.state_dict() + # state_dict = self.model.state_dict() + + if self.args.should_save: + self._save(output_dir, state_dict=state_dict) + elif self.deepspeed: + # this takes care of everything as long as we aren't under zero3 + if self.args.should_save: + self._save(output_dir) + + if is_deepspeed_zero3_enabled(): + # It's too complicated to try to override different places where the weights dump gets + # saved, so since under zero3 the file is bogus, simply delete it. The user should + # either user deepspeed checkpoint to resume or to recover full weights use + # zero_to_fp32.py stored in the checkpoint. + if self.args.should_save: + file = os.path.join(output_dir, WEIGHTS_NAME) + if os.path.isfile(file): + # logger.info(f"deepspeed zero3: removing {file}, see zero_to_fp32.py to recover weights") + os.remove(file) + + # now save the real model if stage3_gather_16bit_weights_on_model_save=True + # if false it will not be saved. + # This must be called on all ranks + if not self.deepspeed.save_16bit_model(output_dir, WEIGHTS_NAME): + logger.warning( + "deepspeed.save_16bit_model didn't save the model, since" + " stage3_gather_16bit_weights_on_model_save=false. Saving the full checkpoint instead, use" + " zero_to_fp32.py to recover weights" + ) + self.deepspeed.save_checkpoint(output_dir) + + elif self.args.should_save: + self._save(output_dir) + + # Push to the Hub when `save_model` is called by the user. + if self.args.push_to_hub and not _internal_call: + self.push_to_hub(commit_message="Model save") diff --git a/baselines/lozo/large_models/README.md b/baselines/lozo/large_models/README.md new file mode 100644 index 0000000..8dcd9d9 --- /dev/null +++ b/baselines/lozo/large_models/README.md @@ -0,0 +1,58 @@ +# LOZO on Large Autoregressive Language Models + +This part of the code is for LOZO experiments on large autoregressive language models, based on [MeZO](https://github.com/princeton-nlp/MeZO). To avoid interfering with the existing code and to improve clarity, we add three new files: `run_lozo.py`, `lozo.sh`, and `LOZOtrainer.py`. These files support the replication of our experiments. + +## Installation + +Please install the latest versions of PyTorch (`pytorch` following [https://pytorch.org](https://pytorch.org)), Transformers (`transformers`), and Accelerate (`accelerate`). This code is tested on `torch==2.1.0.dev20230514+cu118`, `transformers==4.28.1`, and `accelerate==0.17.1` with Python 3.9.7, but should work with older/later versions of these packages too. + +## Usage + +Use `run_lozo.py` for all functions (zero-shot/ICL/fine-tuning/LOZO): +```bash +python run_lozo.py {ARGUMENTS} +``` + +Please read `run_lozo.py` for a complete list of arguments. We introduce some of the most important ones below. +* `--num_train`: Number of training examples. For ICL, this is the number of demonstrations. +* `--num_dev`: Number of validation examples. +* `--num_test`: Number of testing examples. +* `--model_name`: HuggingFace model name or path. +* `--task_name`: Task name. +* `--trainer`: can be `none` (zero-shot/ICL), `regular` (fine-tuning), or `LOZO` (LOZO). +* `--train_as_classification`: turn this on for classification tasks (Cross Entropy over likelihood of each class' label words). Otherwise it is LM-style teacher forcing. +* `--zo_eps`: LOZO hyperparameter epsilon. +* `--rank_r`: the rank of matrices $U$ and $V$. +* `step_interval`: the update interval of $V$ e.g.the value of $\nu$. + +We also support all [HuggingFace trainer arguments](https://github.com/huggingface/transformers/blob/main/src/transformers/training_args.py) for easily setting fine-tuning hyperparameters. + + +```bash +# Zero-shot +MODEL=facebook/opt-13b TASK=SST2 bash icl.sh --num_train 0 + +# In-context learning +MODEL=facebook/opt-13b TASK=SST2 bash icl.sh + +# Full-parameter fine-tuning +MODEL=facebook/opt-1.3b TASK=SST2 MODE=ft LR=1e-5 bash finetune.sh + +# Full-parameter fine-tuning using fully-sharded data parallel or FSDP (multi-GPU) +MODEL=facebook/opt-13b TASK=SST2 MODE=ft LR=1e-5 NUM_GPU=4 bash finetune_fsdp.sh + +# MeZO (full-parameter) +MODEL=facebook/opt-13b TASK=SST2 MODE=ft LR=1e-7 EPS=1e-3 bash mezo.sh + +# LOZO (full-parameter) +MODEL=facebook/opt-13b TASK=SST2 MODE=ft LR=1e-7 EPS=1e-3 RANK=2 STEP_INTERVAL=50 bash lozo.sh +``` + +Note that `icl.sh` and `mezo.sh` automatically support multi-GPU usage. For fine-tuning, use `finetune_fsdp.sh` for multi-GPU training and specific `NUM_GPU`. Evaluation results (json format) and checkpoints (HuggingFace format) will be saved in `result` folder. + +Our recommended hyperparameter search range for OPT-13b (should also work for other sizes/models) are as follows, + +| LOZO methods | LR | EPS | rank | $\nu$ | +| ------------- | ------------ | --- | ---- | ----- | +| Full parameter | 1e-6/1e-7 | 1e-3 | 1/2 | 50/100| + diff --git a/baselines/lozo/large_models/finetune.sh b/baselines/lozo/large_models/finetune.sh new file mode 100644 index 0000000..233ec7a --- /dev/null +++ b/baselines/lozo/large_models/finetune.sh @@ -0,0 +1,73 @@ +MODEL=${MODEL:-facebook/opt-1.3b} +MODEL_NAME=(${MODEL//\// }) +MODEL_NAME="${MODEL_NAME[-1]}" + +EPOCH=${EPOCH:-5} +BS=${BS:-8} +LR=${LR:-1e-5} +SEED=${SEED:-0} +TRAIN=${TRAIN:-1000} +DEV=${DEV:-500} +EVAL=${EVAL:-1000} + +MODE=${MODE:-ft} +EXTRA_ARGS="" +if [ "$MODE" == "prefix" ]; then + EXTRA_ARGS="--prefix_tuning --num_prefix 5 --no_reparam --prefix_init_by_real_act" +elif [ "$MODE" == "lora" ]; then + EXTRA_ARGS="--lora" +fi +TAG=$MODE-$EPOCH-$BS-$LR-$SEED + +TASK_ARGS="" +case $TASK in + # For Copa, ReCoRD, SQuAD, DROP, we set --train_as_classification False; for others, set this flag to True + CB) # It has <1000 training examples. Only use 100 for dev + DEV=100 + ;; + Copa) # It has <1000 training examples. Only use 100 for dev + DEV=100 + TASK_ARGS="--train_as_classification False" + ;; + MultiRC) # Can only fit real bsz = 2 on 80G A100 + GA=$(expr $BS / 2) + BS=2 + echo "Gradient accumulation: $GA" + TASK_ARGS="--gradient_accumulation_steps $GA" + ;; + ReCoRD) # Can only fit real bsz = 2 on 80G A100 + GA=$(expr $BS / 2) + BS=2 + echo "Gradient accumulation: $GA" + TASK_ARGS="--gradient_accumulation_steps $GA --train_as_classification False" + ;; + DROP) # Can only fit real bsz = 1 on 80G A100 + GA=$(expr $BS / 1) + BS=1 + echo "Gradient accumulation: $GA" + TASK_ARGS="--gradient_accumulation_steps $GA --train_as_classification False" + ;; + SQuAD) + TASK_ARGS="--train_as_classification False" + ;; +esac + +echo $TAG +echo "EPOCH: $EPOCH" +echo "BS: $BS" +echo "LR: $LR" +echo "SEED: $SEED" +echo "MODE: $MODE" +echo "Extra args: $EXTRA_ARGS $TASK_ARGS" + +python run.py \ + --model_name $MODEL \ + --task_name $TASK \ + --output_dir result/$TASK-${MODEL_NAME}-$TAG --tag $TAG --train_set_seed $SEED --num_train $TRAIN --num_dev $DEV --num_eval $EVAL --logging_steps 10 \ + --trainer regular --fp16 \ + --learning_rate $LR --num_train_epochs $EPOCH --per_device_train_batch_size $BS \ + --load_best_model_at_end --evaluation_strategy epoch --save_strategy epoch --save_total_limit 1 \ + --train_as_classification \ + $EXTRA_ARGS \ + $TASK_ARGS \ + "$@" diff --git a/baselines/lozo/large_models/finetune_fsdp.sh b/baselines/lozo/large_models/finetune_fsdp.sh new file mode 100644 index 0000000..2d8a10c --- /dev/null +++ b/baselines/lozo/large_models/finetune_fsdp.sh @@ -0,0 +1,63 @@ +MODEL=${MODEL:-facebook/opt-1.3b} +MODEL_NAME=(${MODEL//\// }) +MODEL_NAME="${MODEL_NAME[-1]}" + +EPOCH=${EPOCH:-5} +BS=${BS:-8} +LR=${LR:-1e-5} +SEED=${SEED:-0} +TRAIN=${TRAIN:-1000} +DEV=${DEV:-500} +EVAL=${EVAL:-1000} + +MODE=${MODE:-ft} +EXTRA_ARGS="" +if [ "$MODE" == "prefix" ]; then + EXTRA_ARGS="--prefix_tuning --num_prefix 5 --no_reparam --prefix_init_by_real_act" +elif [ "$MODE" == "lora" ]; then + EXTRA_ARGS="--lora" +fi +TAG=fsdp-$MODE-$EPOCH-$BS-$LR-$SEED + +TASK_ARGS="" +case $TASK in + # For Copa, ReCoRD, SQuAD, DROP, we set --train_as_classification False; for others, set this flag to True + CB) # It has <1000 training examples. Only use 100 for dev + DEV=100 + ;; + Copa) # It has <1000 training examples. Only use 100 for dev + DEV=100 + TASK_ARGS="--train_as_classification False" + ;; + ReCoRD) + TASK_ARGS="--train_as_classification False" + ;; + DROP) + TASK_ARGS="--train_as_classification False" + ;; + SQuAD) + TASK_ARGS="--train_as_classification False" + ;; +esac + +echo $TAG +echo "EPOCH: $EPOCH" +echo "BS (gradient accumulation): $BS" +echo "LR: $LR" +echo "SEED: $SEED" +echo "MODE: $MODE" +echo "Extra args: $EXTRA_ARGS $TASK_ARGS" + +OMP_NUM_THREADS=10 torchrun --nproc_per_node=$NUM_GPU --master_port=$(( RANDOM + 1000 )) run.py \ + --model_name $MODEL \ + --task_name $TASK \ + --output_dir result/$TASK-${MODEL_NAME}-$TAG --tag $TAG --train_set_seed $SEED --num_train $TRAIN --num_dev $DEV --num_eval $EVAL --logging_steps 10 \ + --trainer regular --fp16 --no_auto_device \ + --learning_rate $LR --num_train_epochs $EPOCH --per_device_train_batch_size 1 --gradient_accumulation_steps $BS \ + --load_best_model_at_end --evaluation_strategy epoch --save_strategy epoch --save_total_limit 1 \ + --train_as_classification \ + --fsdp "full_shard auto_wrap" \ + --fsdp_transformer_layer_cls_to_wrap 'OPTDecoderLayer' \ + $EXTRA_ARGS \ + $TASK_ARGS \ + "$@" diff --git a/baselines/lozo/large_models/ht_opt.py b/baselines/lozo/large_models/ht_opt.py new file mode 100644 index 0000000..3079a49 --- /dev/null +++ b/baselines/lozo/large_models/ht_opt.py @@ -0,0 +1,1268 @@ +# For head-tuning, we use torch.no_grad() for all the forward functions except the lm head +# The following code is mostly copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/opt/modeling_opt.py +# Search "MeZO added" to find we we added + +# coding=utf-8 +# Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" PyTorch OPT model.""" +import random +from typing import List, Optional, Tuple, Union + +import torch +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +from transformers.activations import ACT2FN +from transformers.modeling_outputs import ( + BaseModelOutputWithPast, + CausalLMOutputWithPast, + QuestionAnsweringModelOutput, + SequenceClassifierOutputWithPast, +) +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import ( + add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, + logging, + replace_return_docstrings, +) +from transformers.models.opt.configuration_opt import OPTConfig + + +logger = logging.get_logger(__name__) + +_CHECKPOINT_FOR_DOC = "facebook/opt-350m" +_CONFIG_FOR_DOC = "OPTConfig" + +# Base model docstring +_EXPECTED_OUTPUT_SHAPE = [1, 8, 1024] + +# SequenceClassification docstring +_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ArthurZ/opt-350m-dummy-sc" +_SEQ_CLASS_EXPECTED_LOSS = 1.71 +_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_0'" + +OPT_PRETRAINED_MODEL_ARCHIVE_LIST = [ + "facebook/opt-125m", + "facebook/opt-350m", + "facebook/opt-1.3b", + "facebook/opt-2.7b", + "facebook/opt-6.7b", + "facebook/opt-13b", + "facebook/opt-30b", + # See all OPT models at https://huggingface.co/models?filter=opt +] + + +# Copied from transformers.models.bart.modeling_bart._make_causal_mask +def _make_causal_mask( + input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 +): + """ + Make causal mask used for bi-directional self-attention. + """ + bsz, tgt_len = input_ids_shape + mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device) + mask_cond = torch.arange(mask.size(-1), device=device) + mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) + mask = mask.to(dtype) + + if past_key_values_length > 0: + mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) + return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) + + +def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + bsz, src_len = mask.size() + tgt_len = tgt_len if tgt_len is not None else src_len + + expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) + + inverted_mask = 1.0 - expanded_mask + + return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) + + +class OPTLearnedPositionalEmbedding(nn.Embedding): + """ + This module learns positional embeddings up to a fixed maximum size. + """ + + def __init__(self, num_embeddings: int, embedding_dim: int): + # OPT is set up so that if padding_idx is specified then offset the embedding ids by 2 + # and adjust num_embeddings appropriately. Other models don't have this hack + self.offset = 2 + super().__init__(num_embeddings + self.offset, embedding_dim) + + def forward(self, attention_mask: torch.LongTensor, past_key_values_length: int = 0): + """`input_ids_shape` is expected to be [bsz x seqlen].""" + attention_mask = attention_mask.long() + + # create positions depending on attention_mask + positions = (torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask).long() - 1 + + # cut positions if `past_key_values_length` is > 0 + positions = positions[:, past_key_values_length:] + + return super().forward(positions + self.offset) + + +class OPTAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__( + self, + embed_dim: int, + num_heads: int, + dropout: float = 0.0, + is_decoder: bool = False, + bias: bool = True, + ): + super().__init__() + self.embed_dim = embed_dim + self.num_heads = num_heads + self.dropout = dropout + self.head_dim = embed_dim // num_heads + + if (self.head_dim * num_heads) != self.embed_dim: + raise ValueError( + f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" + f" and `num_heads`: {num_heads})." + ) + self.scaling = self.head_dim**-0.5 + self.is_decoder = is_decoder + + self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def forward( + self, + hidden_states: torch.Tensor, + key_value_states: Optional[torch.Tensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + """Input shape: Batch x Time x Channel""" + + # if key_value_states are provided this layer is used as a cross-attention layer + # for the decoder + is_cross_attention = key_value_states is not None + + bsz, tgt_len, _ = hidden_states.size() + + # get query proj + query_states = self.q_proj(hidden_states) * self.scaling + # get key, value proj + if is_cross_attention and past_key_value is not None: + # reuse k,v, cross_attentions + key_states = past_key_value[0] + value_states = past_key_value[1] + elif is_cross_attention: + # cross_attentions + key_states = self._shape(self.k_proj(key_value_states), -1, bsz) + value_states = self._shape(self.v_proj(key_value_states), -1, bsz) + elif past_key_value is not None: + # reuse k, v, self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + else: + # self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + + if self.is_decoder: + # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. + # Further calls to cross_attention layer can then reuse all cross-attention + # key/value_states (first "if" case) + # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of + # all previous decoder key/value_states. Further calls to uni-directional self-attention + # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) + # if encoder bi-directional self-attention `past_key_value` is always `None` + past_key_value = (key_states, value_states) + + proj_shape = (bsz * self.num_heads, -1, self.head_dim) + query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape) + key_states = key_states.view(*proj_shape) + value_states = value_states.view(*proj_shape) + + src_len = key_states.size(1) + attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) + + if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len): + raise ValueError( + f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, tgt_len, src_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" + ) + attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask + attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437 + if attn_weights.dtype == torch.float16: + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16) + else: + attn_weights = nn.functional.softmax(attn_weights, dim=-1) + + if layer_head_mask is not None: + if layer_head_mask.size() != (self.num_heads,): + raise ValueError( + f"Head mask for a single layer should be of size {(self.num_heads,)}, but is" + f" {layer_head_mask.size()}" + ) + attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + if output_attentions: + # this operation is a bit awkward, but it's required to + # make sure that attn_weights keeps its gradient. + # In order to do so, attn_weights have to be reshaped + # twice and have to be reused in the following + attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len) + else: + attn_weights_reshaped = None + + attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) + + attn_output = torch.bmm(attn_probs, value_states) + + if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) + attn_output = attn_output.transpose(1, 2) + + # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be + # partitioned aross GPUs when using tensor-parallelism. + attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) + + attn_output = self.out_proj(attn_output) + + return attn_output, attn_weights_reshaped, past_key_value + + +class OPTDecoderLayer(nn.Module): + def __init__(self, config: OPTConfig): + super().__init__() + self.embed_dim = config.hidden_size + self.self_attn = OPTAttention( + embed_dim=self.embed_dim, + num_heads=config.num_attention_heads, + dropout=config.attention_dropout, + is_decoder=True, + bias=config.enable_bias, + ) + self.do_layer_norm_before = config.do_layer_norm_before + self.dropout = config.dropout + self.activation_fn = ACT2FN[config.activation_function] + + self.self_attn_layer_norm = nn.LayerNorm( + self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine + ) + self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim, bias=config.enable_bias) + self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim, bias=config.enable_bias) + self.final_layer_norm = nn.LayerNorm(self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size + `(encoder_attention_heads,)`. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + past_key_value=past_key_value, + attention_mask=attention_mask, + layer_head_mask=layer_head_mask, + output_attentions=output_attentions, + ) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + hidden_states = residual + hidden_states + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Fully Connected + hidden_states_shape = hidden_states.shape + hidden_states = hidden_states.reshape(-1, hidden_states.size(-1)) + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + hidden_states = self.fc1(hidden_states) + hidden_states = self.activation_fn(hidden_states) + + hidden_states = self.fc2(hidden_states) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + + hidden_states = (residual + hidden_states).view(hidden_states_shape) + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +OPT_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`OPTConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTPreTrainedModel(PreTrainedModel): + config_class = OPTConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["OPTDecoderLayer"] + _keys_to_ignore_on_load_unexpected = [r"decoder\.version"] + + def _init_weights(self, module): + std = self.config.init_std + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, (OPTDecoder)): + module.gradient_checkpointing = value + + +OPT_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape + `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape + `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +class OPTDecoder(OPTPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`] + + Args: + config: OPTConfig + """ + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.dropout = config.dropout + self.layerdrop = config.layerdrop + self.padding_idx = config.pad_token_id + self.max_target_positions = config.max_position_embeddings + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.word_embed_proj_dim, self.padding_idx) + self.embed_positions = OPTLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size) + + if config.word_embed_proj_dim != config.hidden_size: + self.project_out = nn.Linear(config.hidden_size, config.word_embed_proj_dim, bias=False) + else: + self.project_out = None + + if config.word_embed_proj_dim != config.hidden_size: + self.project_in = nn.Linear(config.word_embed_proj_dim, config.hidden_size, bias=False) + else: + self.project_in = None + + # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility + # with checkpoints that have been fine-tuned before transformers v4.20.1 + # see https://github.com/facebookresearch/metaseq/pull/164 + if config.do_layer_norm_before and not config._remove_final_layer_norm: + self.final_layer_norm = nn.LayerNorm( + config.hidden_size, elementwise_affine=config.layer_norm_elementwise_affine + ) + else: + self.final_layer_norm = None + + self.layers = nn.ModuleList([OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)]) + + self.gradient_checkpointing = False + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask + def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): + # create causal mask + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + combined_attention_mask = None + if input_shape[-1] > 1: + combined_attention_mask = _make_causal_mask( + input_shape, + inputs_embeds.dtype, + device=inputs_embeds.device, + past_key_values_length=past_key_values_length, + ) + + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( + inputs_embeds.device + ) + combined_attention_mask = ( + expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask + ) + + return combined_attention_mask + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + """ + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + batch_size, seq_length = input_shape + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + # required mask seq length can be calculated via length of past + mask_seq_length = past_key_values_length + seq_length + + # embed positions + if attention_mask is None: + attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device) + causal_attention_mask = self._prepare_decoder_attention_mask( + attention_mask, input_shape, inputs_embeds, past_key_values_length + ) + pos_embeds = self.embed_positions(attention_mask, past_key_values_length) + + if self.project_in is not None: + inputs_embeds = self.project_in(inputs_embeds) + + hidden_states = inputs_embeds + pos_embeds + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + # check if head_mask has a correct number of layers specified if desired + for attn_mask, mask_name in zip([head_mask], ["head_mask"]): + if attn_mask is not None: + if attn_mask.size()[0] != (len(self.layers)): + raise ValueError( + f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" + f" {head_mask.size()[0]}." + ) + + for idx, decoder_layer in enumerate(self.layers): + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + causal_attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=causal_attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + if self.final_layer_norm is not None: + hidden_states = self.final_layer_norm(hidden_states) + + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTModel(OPTPreTrainedModel): + def __init__(self, config: OPTConfig): + super().__init__(config) + self.decoder = OPTDecoder(config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.decoder.embed_tokens = value + + def get_decoder(self): + return self.decoder + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=BaseModelOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_EXPECTED_OUTPUT_SHAPE, + ) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn) + decoder_outputs = self.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + if not return_dict: + return decoder_outputs + + return BaseModelOutputWithPast( + last_hidden_state=decoder_outputs.last_hidden_state, + past_key_values=decoder_outputs.past_key_values, + hidden_states=decoder_outputs.hidden_states, + attentions=decoder_outputs.attentions, + ) + + +class OPTForCausalLM(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = OPTModel(config) + + # the lm_head weight is automatically tied to the embed tokens weight + self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model.decoder = decoder + + def get_decoder(self): + return self.model.decoder + + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional + tensors are only required when the model is used as a decoder in a Sequence to Sequence model. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, OPTForCausalLM + + >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m") + >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") + + >>> prompt = "Hey, are you consciours? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + # MeZO added: torch.no_grad + with torch.no_grad(): + outputs = self.model.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + logits = self.lm_head(outputs[0]).contiguous() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + ): + if past_key_values: + input_ids = input_ids[:, -1:] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + model_inputs.update( + { + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) + return reordered_past + + +@add_start_docstrings( + """ + The OPT Model transformer with a sequence classification head on top (linear layer). + + [`OPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + OPT_START_DOCSTRING, +) +class OPTForSequenceClassification(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.num_labels = config.num_labels + self.model = OPTModel(config) + self.score = nn.Linear(config.word_embed_proj_dim, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION, + output_type=SequenceClassifierOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_SEQ_CLASS_EXPECTED_OUTPUT, + expected_loss=_SEQ_CLASS_EXPECTED_LOSS, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size, sequence_length = input_ids.shape[:2] + else: + batch_size, sequence_length = inputs_embeds.shape[:2] + + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device) + else: + sequence_lengths = -1 + logger.warning( + f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " + "unexpected if using padding tokens in conjunction with `inputs_embeds.`" + ) + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + +@add_start_docstrings( + """ + The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD + (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + """, + OPT_START_DOCSTRING, +) +class OPTForQuestionAnswering(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.model = OPTModel(config) + self.qa_outputs = nn.Linear(config.word_embed_proj_dim, 2) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + start_positions: Optional[torch.LongTensor] = None, + end_positions: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, QuestionAnsweringModelOutput]: + r""" + start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, OPTForQuestionAnswering + >>> import torch + + >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT + >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") + + >>> # note: we are loading a OPTForQuestionAnswering from the hub here, + >>> # so the head will be randomly initialized, hence the predictions will be random + >>> model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m") + + >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" + + >>> inputs = tokenizer(question, text, return_tensors="pt") + >>> with torch.no_grad(): + ... outputs = model(**inputs) + + >>> answer_start_index = outputs.start_logits.argmax() + >>> answer_end_index = outputs.end_logits.argmax() + + >>> answer_offset = len(tokenizer(question)[0]) + + >>> predict_answer_tokens = inputs.input_ids[ + ... 0, answer_offset + answer_start_index : answer_offset + answer_end_index + 1 + ... ] + >>> predicted = tokenizer.decode(predict_answer_tokens) + >>> predicted + ' a nice puppet' + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + + logits = self.qa_outputs(hidden_states) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + transformer_outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value diff --git a/baselines/lozo/large_models/icl.sh b/baselines/lozo/large_models/icl.sh new file mode 100644 index 0000000..f34ec71 --- /dev/null +++ b/baselines/lozo/large_models/icl.sh @@ -0,0 +1,3 @@ +MODEL=${MODEL:-facebook/opt-13b} + +python run.py --model_name $MODEL --task_name $TASK --output_dir result/tmp --tag icl --num_train 32 --num_eval 1000 --load_float16 --verbose "$@" diff --git a/baselines/lozo/large_models/lora.py b/baselines/lozo/large_models/lora.py new file mode 100644 index 0000000..a87dd6e --- /dev/null +++ b/baselines/lozo/large_models/lora.py @@ -0,0 +1,147 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import torch +from torch import nn +from torch.nn import functional as F +import math + +def find_module(root_module: nn.Module, key: str): + """ + Find a module with a specific name in a Transformer model + From OpenDelta https://github.com/thunlp/OpenDelta + """ + sub_keys = key.split(".") + parent_module = root_module + for sub_key in sub_keys[:-1]: + parent_module = getattr(parent_module, sub_key) + module = getattr(parent_module, sub_keys[-1]) + return parent_module, sub_keys[-1], module + + +class LoRALinear(nn.Linear): + """ + LoRA implemented in a dense layer + From https://github.com/microsoft/LoRA/blob/main/loralib/layers.py + """ + def __init__( + self, + in_features: int, + out_features: int, + r: int = 0, + lora_alpha: int = 1, + lora_dropout: float = 0., + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + merge_weights: bool = False, # Not sure if this will affect saving/loading models so just set it to be False + **kwargs + ): + nn.Linear.__init__(self, in_features, out_features, **kwargs) + + self.r = r + self.lora_alpha = lora_alpha + # Optional dropout + if lora_dropout > 0.: + self.lora_dropout = nn.Dropout(p=lora_dropout) + else: + self.lora_dropout = lambda x: x + # Mark the weight as unmerged + self.merged = False + self.merge_weights = merge_weights + self.fan_in_fan_out = fan_in_fan_out + # Actual trainable parameters + if r > 0: + self.lora_A = nn.Parameter(self.weight.new_zeros((r, in_features))) + self.lora_B = nn.Parameter(self.weight.new_zeros((out_features, r))) + self.scaling = self.lora_alpha / self.r + # Freezing the pre-trained weight matrix + self.weight.requires_grad = False + self.reset_parameters() + if fan_in_fan_out: + self.weight.data = self.weight.data.transpose(0, 1) + + def reset_parameters(self): + nn.Linear.reset_parameters(self) + if hasattr(self, 'lora_A'): + # initialize A the same way as the default for nn.Linear and B to zero + nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5)) + nn.init.zeros_(self.lora_B) + + def train(self, mode: bool = True): + def T(w): + return w.transpose(0, 1) if self.fan_in_fan_out else w + nn.Linear.train(self, mode) + if mode: + if self.merge_weights and self.merged: + # Make sure that the weights are not merged + if self.r > 0: + self.weight.data -= T(self.lora_B @ self.lora_A) * self.scaling + self.merged = False + else: + if self.merge_weights and not self.merged: + # Merge the weights and mark it + if self.r > 0: + self.weight.data += T(self.lora_B @ self.lora_A) * self.scaling + self.merged = True + + def forward(self, x: torch.Tensor): + def T(w): + return w.transpose(0, 1) if self.fan_in_fan_out else w + if self.r > 0 and not self.merged: + result = F.linear(x, T(self.weight), bias=self.bias) + if self.r > 0: + result += (self.lora_dropout(x) @ self.lora_A.transpose(0, 1) @ self.lora_B.transpose(0, 1)) * self.scaling + return result + else: + return F.linear(x, T(self.weight), bias=self.bias) + + +class LoRA: + + def __init__(self, model, r, alpha, float16): + """ + Input: + r, alpha: LoRA hyperparameters + float16: Whether the model parameters are float16 or not + """ + + self.model = model + self.hidden_dim = model.config.hidden_size + self.float16 = float16 + + if model.config.model_type == "opt": + attention_name = "attn" + elif model.config.model_type == "roberta": + attention_name = "attention" + else: + raise NotImplementedError + + # Insert LoRA + for key, _ in model.named_modules(): + if key[-len(attention_name):] == attention_name: + logger.info(f"Inject lora to: {key}") + _, _, attn = find_module(model, key) + + if model.config.model_type == "opt": + original_q_weight = attn.q_proj.weight.data + original_q_bias = attn.q_proj.bias.data + original_v_weight= attn.v_proj.weight.data + original_v_bias = attn.v_proj.bias.data + attn.q_proj = LoRALinear(model.config.hidden_size, model.config.hidden_size, r=r, lora_alpha=alpha, bias=model.config.enable_bias).to(original_q_weight.device) + attn.v_proj = LoRALinear(model.config.hidden_size, model.config.hidden_size, r=r, lora_alpha=alpha, bias=model.config.enable_bias).to(original_v_weight.device) + if float16: + attn.q_proj.half() + attn.v_proj.half() + attn.q_proj.weight.data = original_q_weight + attn.q_proj.bias.data = original_q_bias + attn.v_proj.weight.data = original_v_weight + attn.v_proj.bias.data = original_v_bias + else: + raise NotImplementedError + + # Freeze non-LoRA parameters + for n, p in model.named_parameters(): + if "lora" not in n: + p.requires_grad = False \ No newline at end of file diff --git a/baselines/lozo/large_models/lozo.sh b/baselines/lozo/large_models/lozo.sh new file mode 100644 index 0000000..d483a8c --- /dev/null +++ b/baselines/lozo/large_models/lozo.sh @@ -0,0 +1,84 @@ +MODEL=${MODEL:-facebook/opt-1.3b} +MODEL_NAME=(${MODEL//\// }) +MODEL_NAME="${MODEL_NAME[-1]}" + +BS=${BS:-16} +EPS=${EPS:-1e-3} +TRAIN=${TRAIN:-1000} +DEV=${DEV:-500} +EVAL=${EVAL:-1000} +STEPS=${STEPS:-20000} +EVAL_STEPS=${EVAL_STEPS:-4000} + +MODE=${MODE:-ft} +EXTRA_ARGS="" +if [ "$MODE" == "prefix" ]; then + EXTRA_ARGS="--prefix_tuning --num_prefix 5 --no_reparam --prefix_init_by_real_act" +elif [ "$MODE" == "lora" ]; then + EXTRA_ARGS="--lora" +fi + +LR=1e-7 +TASK=DROP +SEED=0 +RANK=1 +STEP_INTERVAL=100 +Tainer=LOZO + +case $TASK in + CB) # It has <1000 training examples. Only use 100 for dev + DEV=100 + ;; + Copa) # It has <1000 training examples. Only use 100 for dev + DEV=100 + TASK_ARGS="--train_as_classification False" + ;; + ReCoRD) + TASK_ARGS="--train_as_classification False" + ;; + DROP) + TASK_ARGS="--train_as_classification False" + ;; + SQuAD) + TASK_ARGS="--train_as_classification False" + ;; + *) + TASK_ARGS="" + ;; +esac + +TAG=$Tainer-$MODE-$STEPS-$BS-$LR-$EPS-$SEED-$STEP_INTERVAL-$RANK + + +echo $TAG +echo "Task: $TASK" +echo "BS: $BS" +echo "LR: $LR" +echo "EPS: $EPS" +echo "SEED: $SEED" +echo "TRAIN/EVAL STEPS: $STEPS/$EVAL_STEPS" +echo "MODE: $MODE" +echo "Extra args: $EXTRA_ARGS $TASK_ARGS" +echo "RANK: $RANK" +echo "STEP INTERVAL: $STEP_INTERVAL" + +python run_lozo.py \ + --model_name $MODEL \ + --task_name $TASK \ + --output_dir result/$TASK-${MODEL_NAME}-$TAG --tag $TAG --train_set_seed $SEED --num_train $TRAIN --num_dev $DEV --num_eval $EVAL --logging_steps 10 \ + --max_steps $STEPS \ + --trainer $Tainer --load_float16 \ + --learning_rate $LR --zo_eps $EPS --per_device_train_batch_size $BS --lr_scheduler_type "constant" \ + --load_best_model_at_end --evaluation_strategy steps --save_strategy steps --save_total_limit 1 \ + --eval_steps $EVAL_STEPS --save_steps $EVAL_STEPS \ + --train_as_classification \ + --step_interval $STEP_INTERVAL \ + --rank_r $RANK \ + $EXTRA_ARGS \ + $TASK_ARGS \ + "$@" + + + + + diff --git a/baselines/lozo/large_models/metrics.py b/baselines/lozo/large_models/metrics.py new file mode 100644 index 0000000..0e0a282 --- /dev/null +++ b/baselines/lozo/large_models/metrics.py @@ -0,0 +1,78 @@ +import numpy as np +import collections +import re +import string +from collections import Counter + +def normalize_answer(s): + """Lower text and remove punctuation, articles and extra whitespace.""" + + def remove_articles(text): + return re.sub(r'\b(a|an|the)\b', ' ', text) + + def white_space_fix(text): + return ' '.join(text.split()) + + def remove_punc(text): + exclude = set(string.punctuation) + return ''.join(ch for ch in text if ch not in exclude) + + def lower(text): + return text.lower() + + return white_space_fix(remove_articles(remove_punc(lower(s)))) + + +def calculate_metric(predictions, metric_name): + if metric_name == "accuracy": + if isinstance(predictions[0].correct_candidate, list): + return np.mean([pred.predicted_candidate in pred.correct_candidate for pred in predictions]) + else: + return np.mean([pred.correct_candidate == pred.predicted_candidate for pred in predictions]) + elif metric_name == "em": + # For question answering + return np.mean([any([normalize_answer(ans) == normalize_answer(pred.predicted_candidate) for ans in pred.correct_candidate]) for pred in predictions]) + elif metric_name == "f1": + # For question answering + f1 = [] + for pred in predictions: + all_f1s = [] + if pred.correct_candidate[0] == "CANNOTANSWER" or pred.correct_candidate[0] == "no answer": + f1.append(int(normalize_answer(pred.correct_candidate[0]) == normalize_answer(pred.predicted_candidate))) + else: + for ans in pred.correct_candidate: + prediction_tokens = normalize_answer(pred.predicted_candidate).split() + ground_truth_tokens = normalize_answer(ans).split() + common = Counter(prediction_tokens) & Counter(ground_truth_tokens) + num_same = sum(common.values()) + if num_same == 0: + all_f1s.append(0) + else: + precision = 1.0 * num_same / len(prediction_tokens) + recall = 1.0 * num_same / len(ground_truth_tokens) + all_f1s.append((2 * precision * recall) / (precision + recall)) + f1.append(max(all_f1s)) + + return np.mean(f1) + + +def f1(pred, gold): + """ + This separate F1 function is used as non-differentiable metric for SQuAD + """ + if gold[0] == "CANNOTANSWER" or gold[0] == "no answer": + return int(normalize_answer(gold[0]) == normalize_answer(pred)) + else: + all_f1s = [] + for ans in gold: + prediction_tokens = normalize_answer(pred).split() + ground_truth_tokens = normalize_answer(ans).split() + common = Counter(prediction_tokens) & Counter(ground_truth_tokens) + num_same = sum(common.values()) + if num_same == 0: + all_f1s.append(0) + else: + precision = 1.0 * num_same / len(prediction_tokens) + recall = 1.0 * num_same / len(ground_truth_tokens) + all_f1s.append((2 * precision * recall) / (precision + recall)) + return np.max(all_f1s) \ No newline at end of file diff --git a/baselines/lozo/large_models/mezo.sh b/baselines/lozo/large_models/mezo.sh new file mode 100644 index 0000000..cf2d00b --- /dev/null +++ b/baselines/lozo/large_models/mezo.sh @@ -0,0 +1,66 @@ +MODEL=${MODEL:-facebook/opt-1.3b} +MODEL_NAME=(${MODEL//\// }) +MODEL_NAME="${MODEL_NAME[-1]}" + +BS=${BS:-16} +LR=${LR:-1e-5} +EPS=${EPS:-1e-3} +SEED=${SEED:-0} +TRAIN=${TRAIN:-1000} +DEV=${DEV:-500} +EVAL=${EVAL:-1000} +STEPS=${STEPS:-20000} +EVAL_STEPS=${EVAL_STEPS:-4000} + +MODE=${MODE:-ft} +EXTRA_ARGS="" +if [ "$MODE" == "prefix" ]; then + EXTRA_ARGS="--prefix_tuning --num_prefix 5 --no_reparam --prefix_init_by_real_act" +elif [ "$MODE" == "lora" ]; then + EXTRA_ARGS="--lora" +fi +TAG=mezo-$MODE-$STEPS-$BS-$LR-$EPS-$SEED + +TASK_ARGS="" +case $TASK in + # For Copa, ReCoRD, SQuAD, DROP, we set --train_as_classification False; for others, set this flag to True + CB) # It has <1000 training examples. Only use 100 for dev + DEV=100 + ;; + Copa) # It has <1000 training examples. Only use 100 for dev + DEV=100 + TASK_ARGS="--train_as_classification False" + ;; + ReCoRD) + TASK_ARGS="--train_as_classification False" + ;; + DROP) + TASK_ARGS="--train_as_classification False" + ;; + SQuAD) + TASK_ARGS="--train_as_classification False" + ;; +esac + +echo $TAG +echo "BS: $BS" +echo "LR: $LR" +echo "EPS: $EPS" +echo "SEED: $SEED" +echo "TRAIN/EVAL STEPS: $STEPS/$EVAL_STEPS" +echo "MODE: $MODE" +echo "Extra args: $EXTRA_ARGS $TASK_ARGS" + +python run_mezo.py \ + --model_name $MODEL \ + --task_name $TASK \ + --output_dir result/$TASK-${MODEL_NAME}-$TAG --tag $TAG --train_set_seed $SEED --num_train $TRAIN --num_dev $DEV --num_eval $EVAL --logging_steps 10 \ + --max_steps $STEPS \ + --trainer zo --load_float16 \ + --learning_rate $LR --zo_eps $EPS --per_device_train_batch_size $BS --lr_scheduler_type "constant" \ + --load_best_model_at_end --evaluation_strategy steps --save_strategy steps --save_total_limit 1 \ + --eval_steps $EVAL_STEPS --save_steps $EVAL_STEPS \ + --train_as_classification \ + $EXTRA_ARGS \ + $TASK_ARGS \ + "$@" diff --git a/baselines/lozo/large_models/prefix.py b/baselines/lozo/large_models/prefix.py new file mode 100644 index 0000000..40d10b9 --- /dev/null +++ b/baselines/lozo/large_models/prefix.py @@ -0,0 +1,200 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import torch +from torch import nn + +def find_module(root_module: nn.Module, key: str): + """ + Find a module with a specific name in a Transformer model + From OpenDelta https://github.com/thunlp/OpenDelta + """ + sub_keys = key.split(".") + parent_module = root_module + for sub_key in sub_keys[:-1]: + parent_module = getattr(parent_module, sub_key) + module = getattr(parent_module, sub_keys[-1]) + return parent_module, sub_keys[-1], module + + +def attn_forward_hook(self, *args, **kwargs): + """ + Replace the original attention forward with this to enable prefix + """ + + def _expand_bsz(x, bsz): + x = x.reshape(x.size(0), self.num_heads, -1).transpose(0,1) # (num_prefix, hidden) -> (num_head, num_prefix, hidden/num_head) + x = x.unsqueeze(0).expand(bsz, *x.shape) # -> (bsz, num_head, num_prefix, hidden/num_head) + return x + + if "hidden_states" in kwargs: + hidden_states = kwargs["hidden_states"] + else: + hidden_states = args[0] + bsz = hidden_states.size(0) + + if 'past_key_value' not in kwargs or kwargs['past_key_value'] is None: + if self.reparam: + prefix_keys = self.prefix_mlp_keys(self.prefix_input_embeds) + prefix_values = self.prefix_mlp_values(self.prefix_input_embeds) + else: + prefix_keys, prefix_values = self.prefix_keys, self.prefix_values + kwargs['past_key_value'] = (_expand_bsz(prefix_keys, bsz), _expand_bsz(prefix_values, bsz)) + + if 'attention_mask' in kwargs and kwargs['attention_mask'] is not None: + am = kwargs['attention_mask'] + kwargs['attention_mask'] = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1) + elif len(args) > 1: # attention mask is passed via positional argument + am = args[1] + am = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1) + args = (args[0], am) + args[2:] + + return self.original_forward(*args, **kwargs) + + +def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs): + """ + Replace the original "prepare_inputs_for_generation" with this to pass prefix correctly + """ + original_input_len = input_ids.size(-1) + if past_key_values: + input_ids = input_ids[:, -1:] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + if past_key_values is not None: + # Check if we should add extra to attention mask + if past_key_values[0][0].size(2) != attention_mask.size(1) - 1: + num_prefix = past_key_values[0][0].size(2) - (attention_mask.size(1) - 1) + attention_mask = torch.cat([torch.ones((attention_mask.size(0), num_prefix), dtype=attention_mask.dtype, device=attention_mask.device), attention_mask], dim=-1) + + model_inputs.update( + { + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + +class PrefixTuning: + + def __init__(self, model, num_prefix, reparam=True, embed_dim=512, mid_dim=512, float16=False, init_by_real_act=False): + """ + Inputs: + num_prefix: number of prefix tokens + reparam: use reparameterization trick (not used in MeZO) + embed_dim, mid_dim: hyperparameters for reparameterization trick (not used in MeZO) + float15: whether the model parameters are float15 + init_by_real_act: init prefix tokens by real activations + """ + + self.model = model + self.num_prefix = num_prefix + self.hidden_dim = model.config.hidden_size + self.float16 = float16 + + # Reparameterization + self.reparam = reparam + self.embed_dim = embed_dim + self.mid_dim = mid_dim + + input_embeds = None # For reparameterization + if model.config.model_type == "opt": + attention_name = "attn" + first_layer_name = "layers.0" + layer_name = "layers." + elif model.config.model_type == "roberta": + attention_name = "attention" + first_layer_name = "layer.0" + layer_name = "layer." + elif model.config.model_type == "llama": + attention_name = "self_attn" + first_layer_name = "layers.0" + layer_name = "layers." + else: + raise NotImplementedError + + if init_by_real_act: + # Initialize prefix with real words' activations + assert not reparam + + # Randomly sample input tokens + input_tokens = torch.randint(low=0, high=model.config.vocab_size, size=(1, num_prefix), dtype=torch.long).cuda() + if model.config.model_type in ["opt", "llama"]: + with torch.no_grad(): + # Get the real activations + real_key_values = model(input_ids=input_tokens, use_cache=True).past_key_values + else: + raise NotImplementedError + + # Insert prefix + for key, _ in model.named_modules(): + if key[-len(attention_name):] == attention_name: + layer_id = int(key.split(layer_name)[1].split(".")[0]) + logger.info(f"Inject prefix to: {key}") + _, _, attn = find_module(model, key) + + # Replace the old forward functions + attn.original_forward = attn.forward + attn.forward = attn_forward_hook.__get__(attn, type(attn)) + if not hasattr(attn, "num_heads"): + attn.num_heads = model.config.num_attention_heads + first = first_layer_name in key + self.add_prefix(attn, first=first, input_embeds=input_embeds) + + if first and self.reparam: + input_embeds = attn.prefix_input_embeds + if init_by_real_act: + logger.info(f"Reinitialize with actual activation: {key} (layer {layer_id})") + keys = real_key_values[layer_id][0].squeeze(0).transpose(0, 1).reshape(num_prefix, -1) + values = real_key_values[layer_id][1].squeeze(0).transpose(0, 1).reshape(num_prefix, -1) + attn.prefix_keys.data = keys.to(attn.prefix_keys.data.device) + attn.prefix_values.data = values.to(attn.prefix_values.data.device) + + # Freeze non-prefix parameters + for n, p in model.named_parameters(): + if "prefix" not in n: + p.requires_grad = False + + # Replace the old prepare_inputs_for_generation function + model.prepare_inputs_for_generation = prepare_inputs_for_generation.__get__(model, type(model)) + + + def add_prefix(self, module, first, input_embeds=None): + device = module.k_proj.weight.data.device + module.num_prefix = self.num_prefix + module.reparam = self.reparam + if self.reparam: + if first: + # For the first layer we inject the embeddings + logger.info("For prefix+reparameterization, inject the embeddings in the first layer.") + module.prefix_input_embeds = nn.Parameter(torch.randn(self.num_prefix, self.embed_dim, device=device, dtype=self.model.dtype), requires_grad=True) + else: + assert input_embeds is not None + module.prefix_input_embeds = input_embeds + module.prefix_mlp_keys = nn.Sequential( + nn.Linear(self.embed_dim, self.mid_dim), + nn.Tanh(), + nn.Linear(self.mid_dim, self.hidden_dim) + ).to(device) + module.prefix_mlp_values = nn.Sequential( + nn.Linear(self.embed_dim, self.mid_dim), + nn.Tanh(), + nn.Linear(self.mid_dim, self.hidden_dim) + ).to(device) + if self.float16: + module.prefix_mlp_keys = module.prefix_mlp_keys.half() + module.prefix_mlp_values = module.prefix_mlp_values.half() + else: + module.prefix_keys = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=device, dtype=self.model.dtype), requires_grad=True) + module.prefix_values = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=device, dtype=self.model.dtype), requires_grad=True) diff --git a/baselines/lozo/large_models/run_lozo.py b/baselines/lozo/large_models/run_lozo.py new file mode 100644 index 0000000..e697dee --- /dev/null +++ b/baselines/lozo/large_models/run_lozo.py @@ -0,0 +1,534 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import argparse +import time +import tasks +from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM, Trainer, HfArgumentParser, Trainer, TrainingArguments, DataCollatorWithPadding, DataCollatorForTokenClassification +from typing import Union, Optional +import torch +from torch.nn.parameter import Parameter +import numpy as np +from dataclasses import dataclass, is_dataclass, asdict +from tqdm import tqdm +from tasks import get_task +import json +import torch.nn.functional as F +from torch.utils.data import Dataset +from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP +from metrics import calculate_metric +from utils import * +from LOZOtrainer import LowRankTrainer +import random + +@dataclass +class OurArguments(TrainingArguments): + # dataset and sampling strategy + task_name: str = "SST2" # task name should match the string before Dataset in the Dataset class name. We support the following task_name: SST2, RTE, CB, BoolQ, WSC, WIC, MultiRC, Copa, ReCoRD, SQuAD, DROP + + # Number of examples + num_train: int = 0 # ICL mode: number of demonstrations; training mode: number of training samples + num_dev: int = None # (only enabled with training) number of development samples + num_eval: int = None # number of evaluation samples + num_train_sets: int = None # how many sets of training samples/demos to sample; if None and train_set_seed is None, then we will sample one set for each evaluation sample + train_set_seed: int = None # designated seed to sample training samples/demos + result_file: str = None # file name for saving performance; if None, then use the task name, model name, and config + + # Model loading + model_path: str = None + model_name: str = "facebook/opt-125m" # HuggingFace model name + load_float16: bool = False # load model parameters as float16 + load_bfloat16: bool = False # load model parameters as bfloat16 + load_int8: bool = False # load model parameters as int8 + max_length: int = 2048 # max length the model can take + no_auto_device: bool = False # do not load model by auto device; should turn this on when using FSDP + + # Calibration + sfc: bool = False # whether to use SFC calibration + icl_sfc: bool = False # whether to use SFC calibration for ICL samples + + # Training + trainer: str = "none" + ## options + ## - none: no training -- for zero-shot or in-context learning (ICL) + ## - regular: regular huggingface trainer -- for fine-tuning + ## - zo: zeroth-order (MeZO) training + ## - LOZO: low rank zeroth-order (LOZO) training + only_train_option: bool = True # whether to only train the option part of the input + train_as_classification: bool = False # take the log likelihood of all options and train as classification + + # LOZO + zo_eps: float = 1e-3 # eps in LOZO + step_interval: int = 50 # $\nu$ in LOZO + rank_r: int = 2 # rank r in LOZO + + # Prefix tuning + prefix_tuning: bool = False # whether to use prefix tuning + num_prefix: int = 5 # number of prefixes to use + no_reparam: bool = True # do not use reparameterization trick + prefix_init_by_real_act: bool = True # initialize prefix by real activations of random words + + # LoRA + lora: bool = False # whether to use LoRA + lora_alpha: int = 16 # alpha in LoRA + lora_r: int = 8 # r in LoRA + + # Generation + sampling: bool = False # whether to use sampling + temperature: float = 1.0 # temperature for generation + num_beams: int = 1 # number of beams for generation + top_k: int = None # top-k for generation + top_p: float = 0.95 # top-p for generation + max_new_tokens: int = 50 # max number of new tokens to generate + eos_token: str = "\n" # end of sentence token + + # Saving + save_model: bool = False # whether to save the model + no_eval: bool = False # whether to skip evaluation + tag: str = "" # saving tag + + # Linear probing + linear_probing: bool = False # whether to do linear probing + lp_early_stopping: bool = False # whether to do early stopping in linear probing + head_tuning: bool = False # head tuning: only tune the LM head + + # Untie emb/lm_head weights + untie_emb: bool = False # untie the embeddings and LM head + + # Display + verbose: bool = False # verbose output + + # Non-diff objective + non_diff: bool = False # use non-differentiable objective (only support F1 for SQuAD for now) + + # Auto saving when interrupted + save_on_interrupt: bool = False # save model when interrupted (useful for long training) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser = HfArgumentParser(OurArguments) + args = parser.parse_args_into_dataclasses()[0] + print(args) + return args + + +def set_seed(seed: int): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +class Framework: + + def __init__(self, args, task): + self.args = args + self.task = task + self.model, self.tokenizer = self.load_model() + + + def load_model(self): + """ + Load HuggingFace models + """ + with count_time("Loading model with FP%d" % (16 if self.args.load_float16 else 32)): + free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) + config = AutoConfig.from_pretrained(self.args.model_name if self.args.model_path is None else self.args.model_path) + if self.args.untie_emb: + # Untie embeddings/LM head + logger.warn("Untie embeddings and LM head") + config.tie_word_embeddings = False + if self.args.head_tuning: + # Head tuning + from ht_opt import OPTForCausalLM + model = OPTForCausalLM.from_pretrained( + self.args.model_name if self.args.model_path is None else self.args.model_path, + config=config, + ) + elif self.args.no_auto_device: + # No auto device (use for FSDP) + model = AutoModelForCausalLM.from_pretrained( + self.args.model_name if self.args.model_path is None else self.args.model_path, + config=config, + ) + else: + # Auto device loading + torch_dtype = torch.float32 + if self.args.load_float16: + torch_dtype = torch.float16 + elif self.args.load_bfloat16: + torch_dtype = torch.bfloat16 + model = AutoModelForCausalLM.from_pretrained( + self.args.model_name if self.args.model_path is None else self.args.model_path, + config=config, + device_map='auto', + torch_dtype=torch_dtype, + max_memory={i: f'{free_in_GB-5}GB' for i in range(torch.cuda.device_count())}, + load_in_8bit=self.args.load_int8, + ) + model.eval() + + # Load tokenizer + tokenizer = AutoTokenizer.from_pretrained(self.args.model_name if self.args.model_path is None else self.args.model_path, use_fast=False) + + # HF tokenizer bug fix + if "opt" in self.args.model_name: + tokenizer.bos_token_id = 0 + + if "llama" in self.args.model_name: + # LLaMA padding token + tokenizer.pad_token_id = 0 # technically + + # Prefix tuning/LoRA + if self.args.prefix_tuning: + from prefix import PrefixTuning + PrefixTuning(model, num_prefix=self.args.num_prefix, reparam=not self.args.no_reparam, float16=self.args.load_float16, init_by_real_act=self.args.prefix_init_by_real_act) + if self.args.lora: + from lora import LoRA + LoRA(model, r=self.args.lora_r, alpha=self.args.lora_alpha, float16=self.args.load_float16) + + if self.args.head_tuning: + if model.config.model_type == "opt": + head_name = "lm_head" if self.args.untie_emb else "embed_tokens" + else: + raise NotImplementedError + for n, p in model.named_parameters(): + if head_name not in n: + p.requires_grad = False + else: + logger.info(f"Only tuning {n}") + + return model, tokenizer + + + def forward(self, input_ids, option_len=None, generation=False): + """ + Given input_ids and the length of the option, return the log-likelihood of each token in the option. + For generation tasks, return the generated text. + This function is only for inference + """ + input_ids = torch.tensor([input_ids]).to(self.model.device) + + if generation: + args = self.args + # Autoregressive generation + outputs = self.model.generate( + input_ids, do_sample=args.sampling, temperature=args.temperature, + num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - input_ids.size(1)), + num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id], + ) + # For generation, directly return the text output + output_text = self.tokenizer.decode(outputs[0][input_ids.size(1):], skip_special_tokens=True).strip() + return output_text + else: + with torch.inference_mode(): + self.model.eval() + logits = self.model(input_ids=input_ids).logits + labels = input_ids[0, 1:] + logits = logits[0, :-1] + log_probs = F.log_softmax(logits, dim=-1) + + selected_log_probs = log_probs[torch.arange(len(labels)).to(labels.device), labels] + selected_log_probs = selected_log_probs.cpu().detach() + # Only return the option (candidate) part + return selected_log_probs[-option_len:] + + + def one_step_pred(self, train_samples, eval_sample, verbose=False): + """ + Return the prediction on the eval sample. In ICL, use train_samples as demonstrations + """ + verbose = verbose or self.args.verbose + if verbose: + logger.info("========= Example =========") + logger.info(f"Candidate: {eval_sample.candidates}") + logger.info(f"Correct candidate: {eval_sample.correct_candidate}") + + + # Encode (add prompt and tokenize) the sample; if multiple-choice/classification, encode all candidates (options) + encoded_candidates, option_lens = encode_prompt( + self.task, self.task.get_template(), train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length, + generation=self.task.generation, max_new_tokens=self.args.max_new_tokens + ) + + # Calibration + if self.args.sfc or self.args.icl_sfc: + sfc_encoded_candidates, sfc_option_lens = encode_prompt(self.task, self.task.get_template(), + train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length, + sfc=self.args.sfc, icl_sfc=self.args.icl_sfc, generation=self.task.generation, + max_new_tokens=self.args.max_new_tokens + ) + + outputs = [] + if self.task.generation: + # For generation tasks, return the autoregressively-generated text + output_text = self.forward(encoded_candidates[0], generation=True) + if verbose: + logger.info("=== Prompt ===") + logger.info(self.tokenizer.decode(encoded_candidates[0])) + logger.info(f"Output: {output_text}") + return Prediction(correct_candidate=eval_sample.correct_candidate, predicted_candidate=output_text) + else: + # For classification/multiple-choice, calculate the probabilities of all candidates + for candidate_id, encoded_candidate in enumerate(encoded_candidates): + selected_log_probs = self.forward(encoded_candidate, option_len=option_lens[candidate_id]) + if verbose: + if candidate_id == 0: + logger.info("=== Candidate %d ===" % candidate_id) + logger.info(self.tokenizer.decode(encoded_candidate)) + else: + logger.info("=== Candidate %d (without context)===" % candidate_id) + logger.info(self.tokenizer.decode(encoded_candidate).split(self.task.train_sep)[-1]) + logger.info(f"Log probabilities of the option tokens: {selected_log_probs}") + + if self.args.sfc or self.args.icl_sfc: + sfc_selected_log_probs = self.forward(sfc_encoded_candidates[candidate_id], option_len=sfc_option_lens[candidate_id]) + if verbose: + logger.info("=== Candidate %d (without context) SFC ===" % candidate_id) + logger.info(self.tokenizer.decode(sfc_encoded_candidates[candidate_id]).split(self.task.train_sep)[-1]) + logger.info(f"Log probabilities of the option tokens: {sfc_selected_log_probs}") + + outputs.append({"log_probs": selected_log_probs, "sfc_log_probs": sfc_selected_log_probs if self.args.sfc or self.args.icl_sfc else None}) + + if self.args.sfc or self.args.icl_sfc: + # Calibrated probabilities (surface form competition; https://arxiv.org/pdf/2104.08315.pdf) + # log p(candidate | input) = log p_lm(candidate | input) - log p_lm(candidate | sfc prompt) + scores = [x['log_probs'].sum().item() - x['sfc_log_probs'].sum().item() for x in outputs] + else: + # (Default) length-normalized log probabilities + # log p(candidate | input) = log p_lm(candidate | input) / |candidate #tokens| + scores = [x['log_probs'].mean().item() for x in outputs] + + if verbose: + logger.info(f"Prediction scores: {scores}") + + if isinstance(eval_sample.correct_candidate, list): + # For some datasets there are multiple correct answers + correct_candidate_id = [eval_sample.candidates.index(c) for c in eval_sample.correct_candidate] + else: + correct_candidate_id = eval_sample.candidates.index(eval_sample.correct_candidate) + + return Prediction(correct_candidate=correct_candidate_id, predicted_candidate=int(np.argmax(scores))) + + + def evaluate(self, train_samples, eval_samples, one_train_set_per_eval_sample=False): + """ + Evaluate function. If one_train_set_per_eval_sample is True, then each eval sample has its own training (demonstration) set. + """ + if one_train_set_per_eval_sample: + logger.info(f"There are {len(eval_samples)} validation samples and one train set per eval sample") + else: + logger.info(f"There are {len(train_samples)} training samples and {len(eval_samples)} validation samples") + + # Prediction loop + predictions = [] + for eval_id, eval_sample in enumerate(tqdm(eval_samples)): + predictions.append( + self.one_step_pred(train_samples[eval_id] if one_train_set_per_eval_sample else train_samples, eval_sample, verbose=(eval_id < 3)) + ) + + # Calculate metrics + metric_name = getattr(self.task, "metric_name", "accuracy") + metrics = {metric_name: calculate_metric(predictions, metric_name)} + return metrics + + + def train(self, train_samples, eval_samples): + """ + Training function + """ + # Set tokenizer to left padding (so that all the options are right aligned) + self.tokenizer.padding_side = "left" + + class HFDataset(Dataset): + + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __getitem__(self, idx): + return self.data[idx] + + + def _convert(samples): + """ + Convert samples to HF-compatible dataset + """ + data = [] + for sample in samples: + encoded_candidates, option_lens = encode_prompt( + self.task, self.task.get_template(), [], sample, self.tokenizer, + max_length=self.args.max_length, generation=self.task.generation, generation_with_gold=True, + max_new_tokens=self.args.max_new_tokens + ) + if self.task.generation: + correct_candidate_id = 0 + elif isinstance(sample.correct_candidate, list): + correct_candidate_id = sample.candidates.index(sample.correct_candidate[0]) + else: + correct_candidate_id = sample.candidates.index(sample.correct_candidate) + + if self.args.non_diff: + # For non-differentiable objective, there is no teacher forcing thus the + # current answer part is removed + encoded_candidates[correct_candidate_id] = encoded_candidates[correct_candidate_id][:-option_lens[correct_candidate_id]] + + if self.args.train_as_classification: + # For classification, we provide the label as the correct candidate id + data.append([{"input_ids": encoded_candidates[_i], "labels": correct_candidate_id, "option_len": option_lens[_i], "num_options": len(sample.candidates)} for _i in range(len(encoded_candidates))]) + elif self.args.only_train_option: + # Otherwise, it is just LM-style teacher forcing + if self.args.non_diff: + # For non-differentiable objective, we need to provide the gold answer to calculate F1/acc + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id], "gold": sample.correct_candidate}) + else: + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id]}) + else: + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id]}) + return data + + with count_time("Tokenizing training samples"): + train_dataset = HFDataset(_convert(train_samples)) + eval_dataset = HFDataset(_convert(eval_samples)) + + if self.args.only_train_option and not self.args.non_diff: + # If --only_train_option and not with a non-differentiable objective, we wrap the forward function + self.model.original_forward = self.model.forward + self.model.forward = forward_wrap_with_option_len.__get__(self.model, type(self.model)) + + if self.args.non_diff: + collator = NondiffCollator + else: + collator = DataCollatorForTokenClassification + + if self.args.trainer == "LOZO": + trainer = LowRankTrainer( + model=self.model, + args=self.args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + tokenizer=self.tokenizer, + data_collator=DataCollatorWithPaddingAndNesting(self.tokenizer, pad_to_multiple_of=8) if self.args.train_as_classification else collator(self.tokenizer, pad_to_multiple_of=8), + ) + if self.args.save_on_interrupt: + trainer.add_callback(SIGUSR1Callback()) + + # Resume training from a last checkpoint + last_checkpoint = None + from transformers.trainer_utils import get_last_checkpoint + if os.path.isdir(self.args.output_dir) and not self.args.overwrite_output_dir: + last_checkpoint = get_last_checkpoint(self.args.output_dir) + if last_checkpoint is not None and self.args.resume_from_checkpoint is None: + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + if self.args.resume_from_checkpoint is not None: + last_checkpoint = self.args.resume_from_checkpoint + + trainer.train(resume_from_checkpoint=last_checkpoint) + + # Explicitly save the model + if self.args.save_model: + logger.warn("Save model..") + trainer.save_model() + + # FSDP compatibility + self.model = trainer.model + + # Reset the forward function for evaluation + if self.args.only_train_option and not self.args.non_diff: + if type(self.model) == FSDP: + logger.info("This is an FSDP model now. Be careful when assigning back the original forward function") + self.model._fsdp_wrapped_module.forward = self.model._fsdp_wrapped_module.original_forward + else: + self.model.forward = self.model.original_forward + + +def result_file_tag(args): + """ + Get the result file tag + """ + save_model_name = args.model_name.split("/")[-1] + sfc_tag = "-sfc" if args.sfc else "" + icl_sfc_tag = "-icl_sfc" if args.icl_sfc else "" + sample_eval_tag = "-sampleeval%d" % args.num_eval if args.num_eval is not None else "" + sample_train_tag = "-ntrain%d" % args.num_train if args.num_train > 0 else "" + sample_dev_tag = "-ndev%d" % args.num_dev if args.num_dev is not None else "" + customized_tag = f"-{args.tag}" if len(args.tag) > 0 else "" + return f"{args.task_name}-{save_model_name}" + sfc_tag + icl_sfc_tag + sample_eval_tag + sample_train_tag + sample_dev_tag + customized_tag + + +def main(): + args = parse_args() + + set_seed(args.seed) + task = get_task(args.task_name) + train_sets = task.sample_train_sets(num_train=args.num_train, num_dev=args.num_dev, num_eval=args.num_eval, num_train_sets=args.num_train_sets, seed=args.train_set_seed) + + # Initialize trainer and load model + framework = Framework(args, task) + + if args.train_set_seed is not None or args.num_train_sets is not None: + # Eval samples share one (or multiple) training set(s) + for train_set_id, train_samples in enumerate(train_sets): + train_set_seed = train_set_id if args.train_set_seed is None else args.train_set_seed + + # Sample eval samples + if args.num_eval is not None: + eval_samples = task.sample_subset(data_split="valid", seed=train_set_seed, num=args.num_eval) + else: + eval_samples = task.valid_samples + + if args.trainer != "none": + if args.num_dev is not None: + # Dev samples + dev_samples = train_samples[-args.num_dev:] + train_samples = train_samples[:-args.num_dev] + else: + dev_samples = None + + # Training + framework.train(train_samples, dev_samples if dev_samples is not None else eval_samples) + + if not args.no_eval: + metrics = framework.evaluate([], eval_samples) # No in-context learning if there is training + if dev_samples is not None: + dev_metrics = framework.evaluate([], dev_samples) + for m in dev_metrics: + metrics["dev_" + m] = dev_metrics[m] + else: + assert args.num_dev is None + # Zero-shot / in-context learning + metrics = framework.evaluate(train_samples, eval_samples) + + if not args.no_eval: + logger.info("===== Train set %d =====" % train_set_seed) + logger.info(metrics) + print(metrics) + if args.local_rank <= 0: + write_metrics_to_file(metrics, "result/" + result_file_tag(args) + f"-trainset{train_set_id}.json" if args.result_file is None else args.result_file) + + else: + # For each eval sample, there is a training set. no training is allowed + # This is for in-context learning (ICL) + assert args.trainer == "none" + if args.num_eval is not None: + eval_samples = task.sample_subset(data_split="valid", seed=0, num=args.num_eval) + else: + eval_samples = task.valid_samples + + metrics = framework.evaluate(train_sets, eval_samples, one_train_set_per_eval_sample=True) + logger.info(metrics) + if args.local_rank <= 0: + write_metrics_to_file(metrics, "result/" + result_file_tag(args) + "-onetrainpereval.json" if args.result_file is None else args.result_file) + +if __name__ == "__main__": + + main() diff --git a/baselines/lozo/large_models/run_mezo.py b/baselines/lozo/large_models/run_mezo.py new file mode 100644 index 0000000..b46435a --- /dev/null +++ b/baselines/lozo/large_models/run_mezo.py @@ -0,0 +1,528 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import argparse +import time +import tasks +from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM, Trainer, HfArgumentParser, Trainer, TrainingArguments, DataCollatorWithPadding, DataCollatorForTokenClassification +from typing import Union, Optional +import torch +from torch.nn.parameter import Parameter +import numpy as np +from dataclasses import dataclass, is_dataclass, asdict +from tqdm import tqdm +from tasks import get_task +import json +import torch.nn.functional as F +from torch.utils.data import Dataset +from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP +from metrics import calculate_metric +from utils import * +from trainer import OurTrainer +import random + +@dataclass +class OurArguments(TrainingArguments): + # dataset and sampling strategy + task_name: str = "SST2" # task name should match the string before Dataset in the Dataset class name. We support the following task_name: SST2, RTE, CB, BoolQ, WSC, WIC, MultiRC, Copa, ReCoRD, SQuAD, DROP + + # Number of examples + num_train: int = 0 # ICL mode: number of demonstrations; training mode: number of training samples + num_dev: int = None # (only enabled with training) number of development samples + num_eval: int = None # number of evaluation samples + num_train_sets: int = None # how many sets of training samples/demos to sample; if None and train_set_seed is None, then we will sample one set for each evaluation sample + train_set_seed: int = None # designated seed to sample training samples/demos + result_file: str = None # file name for saving performance; if None, then use the task name, model name, and config + + # Model loading + model_path: str = None + model_name: str = "facebook/opt-125m" # HuggingFace model name + load_float16: bool = False # load model parameters as float16 + load_bfloat16: bool = False # load model parameters as bfloat16 + load_int8: bool = False # load model parameters as int8 + max_length: int = 2048 # max length the model can take + no_auto_device: bool = False # do not load model by auto device; should turn this on when using FSDP + + # Calibration + sfc: bool = False # whether to use SFC calibration + icl_sfc: bool = False # whether to use SFC calibration for ICL samples + + # Training + trainer: str = "none" + ## options + ## - none: no training -- for zero-shot or in-context learning (ICL) + ## - regular: regular huggingface trainer -- for fine-tuning + ## - zo: zeroth-order (MeZO) training + only_train_option: bool = True # whether to only train the option part of the input + train_as_classification: bool = False # take the log likelihood of all options and train as classification + + # MeZO + zo_eps: float = 1e-3 # eps in MeZO + + # Prefix tuning + prefix_tuning: bool = False # whether to use prefix tuning + num_prefix: int = 5 # number of prefixes to use + no_reparam: bool = True # do not use reparameterization trick + prefix_init_by_real_act: bool = True # initialize prefix by real activations of random words + + # LoRA + lora: bool = False # whether to use LoRA + lora_alpha: int = 16 # alpha in LoRA + lora_r: int = 8 # r in LoRA + + # Generation + sampling: bool = False # whether to use sampling + temperature: float = 1.0 # temperature for generation + num_beams: int = 1 # number of beams for generation + top_k: int = None # top-k for generation + top_p: float = 0.95 # top-p for generation + max_new_tokens: int = 50 # max number of new tokens to generate + eos_token: str = "\n" # end of sentence token + + # Saving + save_model: bool = False # whether to save the model + no_eval: bool = False # whether to skip evaluation + tag: str = "" # saving tag + + # Linear probing + linear_probing: bool = False # whether to do linear probing + lp_early_stopping: bool = False # whether to do early stopping in linear probing + head_tuning: bool = False # head tuning: only tune the LM head + + # Untie emb/lm_head weights + untie_emb: bool = False # untie the embeddings and LM head + + # Display + verbose: bool = False # verbose output + + # Non-diff objective + non_diff: bool = False # use non-differentiable objective (only support F1 for SQuAD for now) + + # Auto saving when interrupted + save_on_interrupt: bool = False # save model when interrupted (useful for long training) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser = HfArgumentParser(OurArguments) + args = parser.parse_args_into_dataclasses()[0] + print(args) + return args + + +def set_seed(seed: int): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +class Framework: + + def __init__(self, args, task): + self.args = args + self.task = task + self.model, self.tokenizer = self.load_model() + + + def load_model(self): + """ + Load HuggingFace models + """ + with count_time("Loading model with FP%d" % (16 if self.args.load_float16 else 32)): + free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) + config = AutoConfig.from_pretrained(self.args.model_name if self.args.model_path is None else self.args.model_path) + if self.args.untie_emb: + # Untie embeddings/LM head + logger.warn("Untie embeddings and LM head") + config.tie_word_embeddings = False + if self.args.head_tuning: + # Head tuning + from ht_opt import OPTForCausalLM + model = OPTForCausalLM.from_pretrained( + self.args.model_name if self.args.model_path is None else self.args.model_path, + config=config, + ) + elif self.args.no_auto_device: + # No auto device (use for FSDP) + model = AutoModelForCausalLM.from_pretrained( + self.args.model_name if self.args.model_path is None else self.args.model_path, + config=config, + ) + else: + # Auto device loading + torch_dtype = torch.float32 + if self.args.load_float16: + torch_dtype = torch.float16 + elif self.args.load_bfloat16: + torch_dtype = torch.bfloat16 + model = AutoModelForCausalLM.from_pretrained( + self.args.model_name if self.args.model_path is None else self.args.model_path, + config=config, + device_map='auto', + torch_dtype=torch_dtype, + max_memory={i: f'{free_in_GB-5}GB' for i in range(torch.cuda.device_count())}, + load_in_8bit=self.args.load_int8, + ) + model.eval() + + # Load tokenizer + tokenizer = AutoTokenizer.from_pretrained(self.args.model_name if self.args.model_path is None else self.args.model_path, use_fast=False) + + # HF tokenizer bug fix + if "opt" in self.args.model_name: + tokenizer.bos_token_id = 0 + + if "llama" in self.args.model_name: + # LLaMA padding token + tokenizer.pad_token_id = 0 # technically + + # Prefix tuning/LoRA + if self.args.prefix_tuning: + from prefix import PrefixTuning + PrefixTuning(model, num_prefix=self.args.num_prefix, reparam=not self.args.no_reparam, float16=self.args.load_float16, init_by_real_act=self.args.prefix_init_by_real_act) + if self.args.lora: + from lora import LoRA + LoRA(model, r=self.args.lora_r, alpha=self.args.lora_alpha, float16=self.args.load_float16) + + if self.args.head_tuning: + if model.config.model_type == "opt": + head_name = "lm_head" if self.args.untie_emb else "embed_tokens" + else: + raise NotImplementedError + for n, p in model.named_parameters(): + if head_name not in n: + p.requires_grad = False + else: + logger.info(f"Only tuning {n}") + + return model, tokenizer + + + def forward(self, input_ids, option_len=None, generation=False): + """ + Given input_ids and the length of the option, return the log-likelihood of each token in the option. + For generation tasks, return the generated text. + This function is only for inference + """ + input_ids = torch.tensor([input_ids]).to(self.model.device) + + if generation: + args = self.args + # Autoregressive generation + outputs = self.model.generate( + input_ids, do_sample=args.sampling, temperature=args.temperature, + num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - input_ids.size(1)), + num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id], + ) + # For generation, directly return the text output + output_text = self.tokenizer.decode(outputs[0][input_ids.size(1):], skip_special_tokens=True).strip() + return output_text + else: + with torch.inference_mode(): + self.model.eval() + logits = self.model(input_ids=input_ids).logits + labels = input_ids[0, 1:] + logits = logits[0, :-1] + log_probs = F.log_softmax(logits, dim=-1) + + selected_log_probs = log_probs[torch.arange(len(labels)).to(labels.device), labels] + selected_log_probs = selected_log_probs.cpu().detach() + # Only return the option (candidate) part + return selected_log_probs[-option_len:] + + + def one_step_pred(self, train_samples, eval_sample, verbose=False): + """ + Return the prediction on the eval sample. In ICL, use train_samples as demonstrations + """ + verbose = verbose or self.args.verbose + if verbose: + logger.info("========= Example =========") + logger.info(f"Candidate: {eval_sample.candidates}") + logger.info(f"Correct candidate: {eval_sample.correct_candidate}") + + + # Encode (add prompt and tokenize) the sample; if multiple-choice/classification, encode all candidates (options) + encoded_candidates, option_lens = encode_prompt( + self.task, self.task.get_template(), train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length, + generation=self.task.generation, max_new_tokens=self.args.max_new_tokens + ) + + # Calibration + if self.args.sfc or self.args.icl_sfc: + sfc_encoded_candidates, sfc_option_lens = encode_prompt(self.task, self.task.get_template(), + train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length, + sfc=self.args.sfc, icl_sfc=self.args.icl_sfc, generation=self.task.generation, + max_new_tokens=self.args.max_new_tokens + ) + + outputs = [] + if self.task.generation: + # For generation tasks, return the autoregressively-generated text + output_text = self.forward(encoded_candidates[0], generation=True) + if verbose: + logger.info("=== Prompt ===") + logger.info(self.tokenizer.decode(encoded_candidates[0])) + logger.info(f"Output: {output_text}") + return Prediction(correct_candidate=eval_sample.correct_candidate, predicted_candidate=output_text) + else: + # For classification/multiple-choice, calculate the probabilities of all candidates + for candidate_id, encoded_candidate in enumerate(encoded_candidates): + selected_log_probs = self.forward(encoded_candidate, option_len=option_lens[candidate_id]) + if verbose: + if candidate_id == 0: + logger.info("=== Candidate %d ===" % candidate_id) + logger.info(self.tokenizer.decode(encoded_candidate)) + else: + logger.info("=== Candidate %d (without context)===" % candidate_id) + logger.info(self.tokenizer.decode(encoded_candidate).split(self.task.train_sep)[-1]) + logger.info(f"Log probabilities of the option tokens: {selected_log_probs}") + + if self.args.sfc or self.args.icl_sfc: + sfc_selected_log_probs = self.forward(sfc_encoded_candidates[candidate_id], option_len=sfc_option_lens[candidate_id]) + if verbose: + logger.info("=== Candidate %d (without context) SFC ===" % candidate_id) + logger.info(self.tokenizer.decode(sfc_encoded_candidates[candidate_id]).split(self.task.train_sep)[-1]) + logger.info(f"Log probabilities of the option tokens: {sfc_selected_log_probs}") + + outputs.append({"log_probs": selected_log_probs, "sfc_log_probs": sfc_selected_log_probs if self.args.sfc or self.args.icl_sfc else None}) + + if self.args.sfc or self.args.icl_sfc: + # Calibrated probabilities (surface form competition; https://arxiv.org/pdf/2104.08315.pdf) + # log p(candidate | input) = log p_lm(candidate | input) - log p_lm(candidate | sfc prompt) + scores = [x['log_probs'].sum().item() - x['sfc_log_probs'].sum().item() for x in outputs] + else: + # (Default) length-normalized log probabilities + # log p(candidate | input) = log p_lm(candidate | input) / |candidate #tokens| + scores = [x['log_probs'].mean().item() for x in outputs] + + if verbose: + logger.info(f"Prediction scores: {scores}") + + if isinstance(eval_sample.correct_candidate, list): + # For some datasets there are multiple correct answers + correct_candidate_id = [eval_sample.candidates.index(c) for c in eval_sample.correct_candidate] + else: + correct_candidate_id = eval_sample.candidates.index(eval_sample.correct_candidate) + + return Prediction(correct_candidate=correct_candidate_id, predicted_candidate=int(np.argmax(scores))) + + + def evaluate(self, train_samples, eval_samples, one_train_set_per_eval_sample=False): + """ + Evaluate function. If one_train_set_per_eval_sample is True, then each eval sample has its own training (demonstration) set. + """ + if one_train_set_per_eval_sample: + logger.info(f"There are {len(eval_samples)} validation samples and one train set per eval sample") + else: + logger.info(f"There are {len(train_samples)} training samples and {len(eval_samples)} validation samples") + + # Prediction loop + predictions = [] + for eval_id, eval_sample in enumerate(tqdm(eval_samples)): + predictions.append( + self.one_step_pred(train_samples[eval_id] if one_train_set_per_eval_sample else train_samples, eval_sample, verbose=(eval_id < 3)) + ) + + # Calculate metrics + metric_name = getattr(self.task, "metric_name", "accuracy") + metrics = {metric_name: calculate_metric(predictions, metric_name)} + return metrics + + + def train(self, train_samples, eval_samples): + """ + Training function + """ + # Set tokenizer to left padding (so that all the options are right aligned) + self.tokenizer.padding_side = "left" + + class HFDataset(Dataset): + + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __getitem__(self, idx): + return self.data[idx] + + + def _convert(samples): + """ + Convert samples to HF-compatible dataset + """ + data = [] + for sample in samples: + encoded_candidates, option_lens = encode_prompt( + self.task, self.task.get_template(), [], sample, self.tokenizer, + max_length=self.args.max_length, generation=self.task.generation, generation_with_gold=True, + max_new_tokens=self.args.max_new_tokens + ) + if self.task.generation: + correct_candidate_id = 0 + elif isinstance(sample.correct_candidate, list): + correct_candidate_id = sample.candidates.index(sample.correct_candidate[0]) + else: + correct_candidate_id = sample.candidates.index(sample.correct_candidate) + + if self.args.non_diff: + # For non-differentiable objective, there is no teacher forcing thus the + # current answer part is removed + encoded_candidates[correct_candidate_id] = encoded_candidates[correct_candidate_id][:-option_lens[correct_candidate_id]] + + if self.args.train_as_classification: + # For classification, we provide the label as the correct candidate id + data.append([{"input_ids": encoded_candidates[_i], "labels": correct_candidate_id, "option_len": option_lens[_i], "num_options": len(sample.candidates)} for _i in range(len(encoded_candidates))]) + elif self.args.only_train_option: + # Otherwise, it is just LM-style teacher forcing + if self.args.non_diff: + # For non-differentiable objective, we need to provide the gold answer to calculate F1/acc + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id], "gold": sample.correct_candidate}) + else: + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id]}) + else: + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id]}) + return data + + with count_time("Tokenizing training samples"): + train_dataset = HFDataset(_convert(train_samples)) + eval_dataset = HFDataset(_convert(eval_samples)) + + if self.args.only_train_option and not self.args.non_diff: + # If --only_train_option and not with a non-differentiable objective, we wrap the forward function + self.model.original_forward = self.model.forward + self.model.forward = forward_wrap_with_option_len.__get__(self.model, type(self.model)) + + if self.args.non_diff: + collator = NondiffCollator + else: + collator = DataCollatorForTokenClassification + + trainer = OurTrainer( + model=self.model, + args=self.args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + tokenizer=self.tokenizer, + data_collator=DataCollatorWithPaddingAndNesting(self.tokenizer, pad_to_multiple_of=8) if self.args.train_as_classification else collator(self.tokenizer, pad_to_multiple_of=8), + ) + if self.args.save_on_interrupt: + trainer.add_callback(SIGUSR1Callback()) + + # Resume training from a last checkpoint + last_checkpoint = None + from transformers.trainer_utils import get_last_checkpoint + if os.path.isdir(self.args.output_dir) and not self.args.overwrite_output_dir: + last_checkpoint = get_last_checkpoint(self.args.output_dir) + if last_checkpoint is not None and self.args.resume_from_checkpoint is None: + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + if self.args.resume_from_checkpoint is not None: + last_checkpoint = self.args.resume_from_checkpoint + + trainer.train(resume_from_checkpoint=last_checkpoint) + + # Explicitly save the model + if self.args.save_model: + logger.warn("Save model..") + trainer.save_model() + + # FSDP compatibility + self.model = trainer.model + + # Reset the forward function for evaluation + if self.args.only_train_option and not self.args.non_diff: + if type(self.model) == FSDP: + logger.info("This is an FSDP model now. Be careful when assigning back the original forward function") + self.model._fsdp_wrapped_module.forward = self.model._fsdp_wrapped_module.original_forward + else: + self.model.forward = self.model.original_forward + + +def result_file_tag(args): + """ + Get the result file tag + """ + save_model_name = args.model_name.split("/")[-1] + sfc_tag = "-sfc" if args.sfc else "" + icl_sfc_tag = "-icl_sfc" if args.icl_sfc else "" + sample_eval_tag = "-sampleeval%d" % args.num_eval if args.num_eval is not None else "" + sample_train_tag = "-ntrain%d" % args.num_train if args.num_train > 0 else "" + sample_dev_tag = "-ndev%d" % args.num_dev if args.num_dev is not None else "" + customized_tag = f"-{args.tag}" if len(args.tag) > 0 else "" + return f"{args.task_name}-{save_model_name}" + sfc_tag + icl_sfc_tag + sample_eval_tag + sample_train_tag + sample_dev_tag + customized_tag + + +def main(): + args = parse_args() + + set_seed(args.seed) + task = get_task(args.task_name) + train_sets = task.sample_train_sets(num_train=args.num_train, num_dev=args.num_dev, num_eval=args.num_eval, num_train_sets=args.num_train_sets, seed=args.train_set_seed) + + # Initialize trainer and load model + framework = Framework(args, task) + + if args.train_set_seed is not None or args.num_train_sets is not None: + # Eval samples share one (or multiple) training set(s) + for train_set_id, train_samples in enumerate(train_sets): + train_set_seed = train_set_id if args.train_set_seed is None else args.train_set_seed + + # Sample eval samples + if args.num_eval is not None: + eval_samples = task.sample_subset(data_split="valid", seed=train_set_seed, num=args.num_eval) + else: + eval_samples = task.valid_samples + + if args.trainer != "none": + if args.num_dev is not None: + # Dev samples + dev_samples = train_samples[-args.num_dev:] + train_samples = train_samples[:-args.num_dev] + else: + dev_samples = None + + # Training + framework.train(train_samples, dev_samples if dev_samples is not None else eval_samples) + + if not args.no_eval: + metrics = framework.evaluate([], eval_samples) # No in-context learning if there is training + if dev_samples is not None: + dev_metrics = framework.evaluate([], dev_samples) + for m in dev_metrics: + metrics["dev_" + m] = dev_metrics[m] + else: + assert args.num_dev is None + # Zero-shot / in-context learning + metrics = framework.evaluate(train_samples, eval_samples) + + if not args.no_eval: + logger.info("===== Train set %d =====" % train_set_seed) + logger.info(metrics) + if args.local_rank <= 0: + write_metrics_to_file(metrics, "result/" + result_file_tag(args) + f"-trainset{train_set_id}.json" if args.result_file is None else args.result_file) + + else: + # For each eval sample, there is a training set. no training is allowed + # This is for in-context learning (ICL) + assert args.trainer == "none" + if args.num_eval is not None: + eval_samples = task.sample_subset(data_split="valid", seed=0, num=args.num_eval) + else: + eval_samples = task.valid_samples + + metrics = framework.evaluate(train_sets, eval_samples, one_train_set_per_eval_sample=True) + logger.info(metrics) + if args.local_rank <= 0: + write_metrics_to_file(metrics, "result/" + result_file_tag(args) + "-onetrainpereval.json" if args.result_file is None else args.result_file) + +if __name__ == "__main__": + main() diff --git a/baselines/lozo/large_models/tasks.py b/baselines/lozo/large_models/tasks.py new file mode 100644 index 0000000..4d482c4 --- /dev/null +++ b/baselines/lozo/large_models/tasks.py @@ -0,0 +1,425 @@ +from templates import * +from utils import temp_seed +import json +import os +from datasets import load_dataset +from dataclasses import dataclass +from typing import List, Union +import string +import random +import datasets +import sys +import numpy as np +import logging + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +def get_task(task_name): + aa = task_name.split("__") + if len(aa) == 2: + task_group, subtask = aa + else: + task_group = aa[0] + subtask = None + class_ = getattr(sys.modules[__name__], f"{task_group}Dataset") + instance = class_(subtask) + return instance + + +@dataclass +class Sample: + id: int = None + data: dict = None + correct_candidate: Union[str, List[str]] = None + candidates: List[str] = None + + +class Dataset: + mixed_set = False + train_sep = "\n\n" + generation = False # whether this is a generation task + + def __init__(self, subtask=None, **kwargs) -> None: + self.subtask = subtask + + def get_task_name(self): + return self.subtask + + def load_dataset(): + raise NotImplementedError + + def get_template(self, template_version=0): + templates = {0: Template} + return templates[template_version] + + def build_sample(self, example): + return + + def sample_train_sets(self, num_train=32, num_dev=None, num_eval=None, num_train_sets=None, seed=None): + if seed is not None: + # one train/demo set using the designated seed + seeds = [seed] + elif num_train_sets is not None: + # num_train_sets train/demo sets + seeds = list(range(num_train_sets)) + else: + # one train/demo set per evaluation sample + assert num_dev is None # not supported + len_valid_samples = len(self.samples["valid"]) if num_eval is None else num_eval + with temp_seed(0): + seeds = np.random.randint(0, 10000, len_valid_samples) + + train_samples = [] + for i, set_seed in enumerate(seeds): + if self.mixed_set: + raise NotImplementedError + train_samples.append(self.sample_subset(data_split="valid", seed=set_seed, num=num_train, exclude=i)) + else: + if num_dev is not None: + train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train+num_dev)) # dev set is included at the end of train set + if num_train + num_dev > len(self.samples["train"]): + logger.warn("num_train + num_dev > available training examples") + else: + train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train)) + if num_dev is not None: + logger.info(f"Sample train set {len(train_samples[-1])}/{len(self.samples['train'])}") + logger.info(f"... including dev set {num_dev} samples") + return train_samples + + def sample_subset(self, data_split="train", seed=0, num=100, exclude=None): + with temp_seed(seed): + samples = self.samples[data_split] + lens = len(samples) + index = np.random.permutation(lens).tolist()[:num if exclude is None else num+1] + if exclude is not None and exclude in index: + index.remove(exclude) + else: + index = index[:num] + return [samples[i] for i in index] + + @property + def valid_samples(self): + return self.samples["valid"] + + +class SST2Dataset(Dataset): + train_sep = "\n\n" + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset('glue', 'sst2') + train_d = d["train"] + validation_d = d["validation"] + + train_samples = [self.build_sample(example) for example in train_d] + valid_samples = [self.build_sample(example) for example in validation_d] + + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example): + label = int(example["label"]) + return Sample(id=example["idx"], data=example, correct_candidate=label, candidates=[0, 1]) + + def get_template(self, template_version=0): + return {0: SST2Template}[template_version]() + + +class CopaDataset(Dataset): + train_sep = "\n\n" + mixed_set = False + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + train_examples = load_dataset('super_glue', "copa")["train"] + valid_examples = load_dataset('super_glue', "copa")["validation"] + + train_samples = [self.build_sample(example) for example in train_examples] + valid_samples = [self.build_sample(example) for example in valid_examples] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example): + sample = \ + Sample( + id=example["idx"], + data=example, + candidates=[example["choice1"], example["choice2"]], + correct_candidate=example[f"choice{example['label'] + 1}"], + ) + + return sample + + def get_template(self, template_version=0): + return {0: CopaTemplate}[template_version]() + + +class BoolQDataset(Dataset): + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("boolq") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=["Yes", "No"], + correct_candidate="Yes" if example["answer"] else "No", + ) + + return sample + + def get_template(self, template_version=2): + return {0: BoolQTemplate, 1: BoolQTemplateV2, 2: BoolQTemplateV3}[template_version]() + + +class MultiRCDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "multirc") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: MultiRCTemplate}[template_version]() + + +class CBDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "cb") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1, 2], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: CBTemplate}[template_version]() + + +class WICDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "wic") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: WICTemplate}[template_version]() + + +class WSCDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "wsc.fixed") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: WSCTemplate}[template_version]() + + +class ReCoRDDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "record") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=example['entities'], + correct_candidate=example['answers'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: ReCoRDTemplateGPT3}[template_version]() + + +class RTEDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "rte") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: RTETemplate}[template_version]() + + +class SQuADDataset(Dataset): + metric_name = "f1" + generation = True + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset() + + def load_dataset(self): + dataset = load_dataset("squad") + train_examples = dataset["train"] + valid_examples = dataset["validation"] + + train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)] + valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example, idx): + answers = example['answers']['text'] + assert len(answers) > 0 + return Sample( + id=idx, + data={ + "title": example['title'], + "context": example['context'], + "question": example['question'], + "answers": answers + }, + candidates=None, + correct_candidate=answers + ) + + def get_template(self, template_version=0): + return {0: SQuADv2Template}[template_version]() + + +class DROPDataset(Dataset): + metric_name = "f1" + generation = True + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset() + + def load_dataset(self): + dataset = load_dataset("drop") + train_examples = dataset["train"] + valid_examples = dataset["validation"] + + train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)] + valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example, idx): + answers = example['answers_spans']['spans'] + assert len(answers) > 0 + return Sample( + id=idx, + data={ + "context": example['passage'], + "question": example['question'], + "answers": answers + }, + candidates=None, + correct_candidate=answers + ) + + def get_template(self, template_version=0): + return {0: DROPTemplate}[template_version]() diff --git a/baselines/lozo/large_models/templates.py b/baselines/lozo/large_models/templates.py new file mode 100644 index 0000000..4a07fb2 --- /dev/null +++ b/baselines/lozo/large_models/templates.py @@ -0,0 +1,379 @@ +class Template: + def encode(self, sample): + """ + Return prompted version of the example (without the answer/candidate) + """ + raise NotImplementedError + + def verbalize(self, sample, candidate): + """ + Return the prompted version of the example (with the answer/candidate) + """ + return candidate + + def encode_sfc(self, sample): + """ + Same as encode, but for SFC (calibration) -- this usually means the input is not included + """ + return "" + + def verbalize_sfc(self, sample, candidate): + """ + Same as verbalize, but for SFC (calibration) -- this usually means the input is not included + """ + return candidate + + +class SST2Template(Template): + verbalizer = {0: "terrible", 1: "great"} + def encode(self, sample): + text = sample.data["sentence"].strip() + return f"{text} It was" + + def verbalize(self, sample, candidate): + text = sample.data["sentence"].strip() + return f"{text} It was {self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f" It was" + + def verbalize_sfc(self, sample, candidate): + return f" It was {self.verbalizer[candidate]}" + + +class CopaTemplate(Template): + capitalization: str = "correct" + effect_conj: str = " so " + cause_conj: str = " because " + + def get_conjucture(self, sample): + if sample.data["question"] == "effect": + conjunction = self.effect_conj + elif sample.data["question"] == "cause": + conjunction = self.cause_conj + else: + raise NotImplementedError + return conjunction + + def get_prompt(self, sample): + premise = sample.data["premise"].rstrip() + if premise.endswith("."): # TODO Add other scripts with different punctuation + premise = premise[:-1] + conjunction = self.get_conjucture(sample) + prompt = premise + conjunction + if self.capitalization == "upper": + prompt = prompt.upper() + elif self.capitalization == "lower": + prompt = prompt.lower() + return prompt + + def encode(self, sample): + prompt = self.get_prompt(sample) + return prompt + + def capitalize(self, c): + if self.capitalization == "correct": + words = c.split(" ") + if words[0] != "I": + words[0] = words[0].lower() + return " ".join(words) + elif self.capitalization == "bug": + return c + elif self.capitalization == "upper": + return c.upper() + elif self.capitalization == "lower": + return c.lower() + else: + raise NotImplementedError + + def verbalize(self, sample, candidate): + prompt = self.get_prompt(sample) + return prompt + self.capitalize(candidate) + + def encode_sfc(self, sample): + conjunction = self.get_conjucture(sample) + return conjunction.strip() + + def verbalize_sfc(self, sample, candidate): + conjunction = self.get_conjucture(sample) + sfc_prompt = conjunction.strip() + " " + self.capitalize(candidate) + return sfc_prompt + + +class BoolQTemplate(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question} {candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class BoolQTemplateV2(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\\n\\n" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\\n\\n{candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class BoolQTemplateV3(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\n" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\n{candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class MultiRCTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + paragraph = sample.data["paragraph"] + question = sample.data["question"] + answer = sample.data["answer"] + return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n" + + def verbalize(self, sample, candidate): + paragraph = sample.data["paragraph"] + question = sample.data["question"] + answer = sample.data["answer"] + return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class CBTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "Yes", 1: "No", 2: "Maybe"} + + def encode(self, sample): + premise = sample.data["premise"] + hypothesis = sample.data["hypothesis"] + return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n" + + def verbalize(self, sample, candidate): + premise = sample.data["premise"] + hypothesis = sample.data["hypothesis"] + return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class WICTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + sent1 = sample.data["sentence1"] + sent2 = sample.data["sentence2"] + word = sample.data["word"] + return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n" + + def verbalize(self, sample, candidate): + sent1 = sample.data["sentence1"] + sent2 = sample.data["sentence2"] + word = sample.data["word"] + return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class WSCTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + text = sample.data['text'] + span1 = sample.data['span1_text'] + span2 = sample.data['span2_text'] + return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n" + + def verbalize(self, sample, candidate): + text = sample.data['text'] + span1 = sample.data['span1_text'] + span2 = sample.data['span2_text'] + return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class ReCoRDTemplate(Template): + # From PromptSource 1 but modified + + def encode(self, sample): + passage = sample.data['passage'] + query = sample.data['query'] + return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer:" + + def verbalize(self, sample, candidate): + passage = sample.data['passage'] + query = sample.data['query'] + return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}" + + def encode_sfc(self, sample): + return f"Answer:" + + def verbalize_sfc(self, sample, candidate): + return f"Answer: {candidate}" + + +class ReCoRDTemplateGPT3(Template): + # From PromptSource 1 but modified + + def encode(self, sample): + passage = sample.data['passage'].replace("@highlight\n", "- ") + return f"{passage}\n-" + + def verbalize(self, sample, candidate): + passage = sample.data['passage'].replace("@highlight\n", "- ") + query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate) + return f"{passage}\n- {query}" + + # passage = sample.data['passage'] + # query = sample.data['query'] + # return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}" + + def encode_sfc(self, sample): + return f"-" + + def verbalize_sfc(self, sample, candidate): + query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate) + return f"- {query}" + + +class RTETemplate(Template): + # From PromptSource 1 + verbalizer={0: "Yes", 1: "No"} + + def encode(self, sample): + premise = sample.data['premise'] + hypothesis = sample.data['hypothesis'] + return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n" + + def verbalize(self, sample, candidate): + premise = sample.data['premise'] + hypothesis = sample.data['hypothesis'] + return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class SQuADv2Template(Template): + + def encode(self, sample): + question = sample.data['question'].strip() + title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer:" + + def verbalize(self, sample, candidate): + question = sample.data['question'].strip() + title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer: {answer}\n" + + + def encode_sfc(self, sample): + raise NotImplementedError + + def verbalize_sfc(self, sample, candidate): + raise NotImplementedError + + +class DROPTemplate(Template): + + def encode(self, sample): + question = sample.data['question'].strip() + # title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Passage: {context}\nQuestion: {question}\nAnswer:" + + def verbalize(self, sample, candidate): + question = sample.data['question'].strip() + # title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Passage: {context}\nQuestion: {question}\nAnswer: {answer}\n" + + + def encode_sfc(self, sample): + raise NotImplementedError + + def verbalize_sfc(self, sample, candidate): + raise NotImplementedError diff --git a/baselines/lozo/large_models/trainer.py b/baselines/lozo/large_models/trainer.py new file mode 100644 index 0000000..304ec18 --- /dev/null +++ b/baselines/lozo/large_models/trainer.py @@ -0,0 +1,893 @@ +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. +""" + +import contextlib +import functools +import glob +import inspect +import math +import os +import random +import re +import shutil +import sys +import time +import warnings +from collections.abc import Mapping +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union +import copy +from metrics import f1 +import numpy as np + +from tqdm.auto import tqdm +from transformers import Trainer +from sklearn.linear_model import LinearRegression, LogisticRegression, LogisticRegressionCV + +# Integrations must be imported before ML frameworks: +from transformers.integrations import ( # isort: split + default_hp_search_backend, + get_reporting_integration_callbacks, + hp_params, + is_fairscale_available, + is_optuna_available, + is_ray_tune_available, + is_sigopt_available, + is_wandb_available, + run_hp_search_optuna, + run_hp_search_ray, + run_hp_search_sigopt, + run_hp_search_wandb, +) + +import numpy as np +import torch +import torch.distributed as dist +from packaging import version +from torch import nn +from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler +from torch.utils.data.distributed import DistributedSampler + +from huggingface_hub import Repository + +from transformers import __version__ +from transformers.configuration_utils import PretrainedConfig +from transformers.data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator +from transformers.debug_utils import DebugOption, DebugUnderflowOverflow +from transformers.deepspeed import deepspeed_init, is_deepspeed_zero3_enabled +from transformers.dependency_versions_check import dep_version_check +from transformers.modelcard import TrainingSummary +from transformers.modeling_utils import PreTrainedModel, load_sharded_checkpoint, unwrap_model +from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_MAPPING_NAMES +from transformers.optimization import Adafactor, get_scheduler +from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_10, is_torch_less_than_1_11 +from transformers.tokenization_utils_base import PreTrainedTokenizerBase +from transformers.trainer_callback import ( + CallbackHandler, + DefaultFlowCallback, + PrinterCallback, + ProgressCallback, + TrainerCallback, + TrainerControl, + TrainerState, +) +from transformers.trainer_pt_utils import ( + DistributedLengthGroupedSampler, + DistributedSamplerWithLoop, + DistributedTensorGatherer, + IterableDatasetShard, + LabelSmoother, + LengthGroupedSampler, + SequentialDistributedSampler, + ShardSampler, + distributed_broadcast_scalars, + distributed_concat, + find_batch_size, + get_module_class_from_name, + get_parameter_names, + nested_concat, + nested_detach, + nested_numpify, + nested_truncate, + nested_xla_mesh_reduce, + reissue_pt_warnings, +) +from transformers.trainer_utils import ( + PREFIX_CHECKPOINT_DIR, + BestRun, + EvalLoopOutput, + EvalPrediction, + FSDPOption, + HPSearchBackend, + HubStrategy, + IntervalStrategy, + PredictionOutput, + RemoveColumnsCollator, + ShardedDDPOption, + TrainerMemoryTracker, + TrainOutput, + default_compute_objective, + default_hp_space, + denumpify_detensorize, + enable_full_determinism, + find_executable_batch_size, + get_last_checkpoint, + has_length, + number_of_arguments, + seed_worker, + set_seed, + speed_metrics, +) +from transformers.training_args import OptimizerNames, ParallelMode, TrainingArguments +from transformers.utils import ( + CONFIG_NAME, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, + find_labels, + get_full_repo_name, + is_apex_available, + is_datasets_available, + is_in_notebook, + is_ipex_available, + is_sagemaker_dp_enabled, + is_sagemaker_mp_enabled, + is_torch_tensorrt_fx_available, + is_torch_tpu_available, + is_torchdynamo_available, + logging, +) +from transformers.utils.generic import ContextManagers + + +_is_native_cpu_amp_available = is_torch_greater_or_equal_than_1_10 + +DEFAULT_CALLBACKS = [DefaultFlowCallback] +DEFAULT_PROGRESS_CALLBACK = ProgressCallback + +if is_in_notebook(): + from .utils.notebook import NotebookProgressCallback + + DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback + +if is_apex_available(): + from apex import amp + +if is_datasets_available(): + import datasets + +if is_torch_tpu_available(check_device=False): + import torch_xla.core.xla_model as xm + import torch_xla.debug.metrics as met + import torch_xla.distributed.parallel_loader as pl + +if is_fairscale_available(): + dep_version_check("fairscale") + import fairscale + from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP + from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP + from fairscale.nn.wrap import auto_wrap + from fairscale.optim import OSS + from fairscale.optim.grad_scaler import ShardedGradScaler + + +if is_sagemaker_mp_enabled(): + import smdistributed.modelparallel.torch as smp + from smdistributed.modelparallel import __version__ as SMP_VERSION + + IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse("1.10") + + from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat +else: + IS_SAGEMAKER_MP_POST_1_10 = False + + +if TYPE_CHECKING: + import optuna + +logger = logging.get_logger(__name__) + + +# Name of the files used for checkpointing +TRAINING_ARGS_NAME = "training_args.bin" +TRAINER_STATE_NAME = "trainer_state.json" +OPTIMIZER_NAME = "optimizer.pt" +SCHEDULER_NAME = "scheduler.pt" +SCALER_NAME = "scaler.pt" + + +class OurTrainer(Trainer): + + from transformers.trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state + + def _inner_training_loop( + self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None + ): + """ + We overload the original training loop to add linear probing and MeZO. Search key word "MeZO added" + for those updates. + """ + self._train_batch_size = batch_size + # Data loader and number of training steps + train_dataloader = self.get_train_dataloader() + + # MeZO added: Linear probing + if self.args.linear_probing: + + def _get_token_prediction_layer(model): + if model.config.model_type == "opt": + return model.lm_head + else: + raise NotImplementedError(model.config.model_type) + + def _extract_features(model, *args, **kwargs): + """some magic for getting features pre last layer""" + features = {} + def __hook(model_, input_, output_): + features["features"] = input_[0].detach() + + _get_token_prediction_layer(model).register_forward_hook(__hook) + model.forward(*args, **kwargs) + return features["features"] + + logger.info("Linear probing") + logger.info("Starting to get features for training dataset") + targets = [] + features = [] + with torch.inference_mode(): + for step, inputs in enumerate(tqdm(train_dataloader)): + for k, v in inputs.items(): + if isinstance(v, torch.Tensor): + inputs[k] = v.to(self.model.device) + + feature = _extract_features(self.model, **inputs) + target = inputs["labels"] + + # Shift the target (bc it's autoregressive LM) and add the corresponding part + assert not self.args.train_as_classification and self.args.only_train_option + feature, target = feature[:, :-1], target[:, 1:] + for _i, _len in enumerate(inputs["option_len"]): + features.append(feature[_i, -_len:]) + targets.append(target[_i, -_len:]) + + logger.info("Finished getting features for training dataset") + + features = torch.cat(features, dim=0).cpu().numpy() + targets = torch.cat(targets, dim=0).cpu().numpy() + # Whether to use bias + if self.model.config.model_type in ["opt", "gpt2"]: + use_bias = False + else: + raise NotImplementedError + # Set early stopping + tol = 0.01 if self.args.lp_early_stopping else 1e-4 # 1e-4 is scipy default + max_iter = 1000 if self.args.lp_early_stopping else 5000 + + logger.info("Fitting logistic regression...") + reg = LogisticRegressionCV(max_iter=max_iter, fit_intercept=use_bias, multi_class="multinomial", random_state=0, tol=tol, n_jobs=-1).fit(features, targets) + logger.info("Done") + + logger.info("Assigning weights to model") + decoder = _get_token_prediction_layer(self.model) + coef_torch = torch.tensor(reg.coef_, device=decoder.weight.device, dtype=decoder.weight.dtype) + if use_bias: + bias_torch = torch.tensor(reg.intercept_, device=decoder.weight.device, dtype=decoder.weight.dtype) + if coef_torch.shape[0] == 1: # The regressor only detects two classes + assert len(reg.classes_) == 2 + coef_torch = torch.cat([-coef_torch / 2, coef_torch / 2], dim=0) + if use_bias: + bias_torch = torch.cat([-bias_torch / 2, bias_torch / 2], dim=0) + + for _i, token_id in enumerate(reg.classes_): + decoder.weight.data[token_id] = coef_torch[_i] + if use_bias: + decoder.bias.data[token_id] = bias_torch[_i] + + return None + + # Setting up training control variables: + # number of training epochs: num_train_epochs + # number of training steps per epoch: num_update_steps_per_epoch + # total number of training steps to execute: max_steps + total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size + + len_dataloader = None + if has_length(train_dataloader): + len_dataloader = len(train_dataloader) + num_update_steps_per_epoch = len_dataloader // args.gradient_accumulation_steps + num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) + num_examples = self.num_examples(train_dataloader) + if args.max_steps > 0: + max_steps = args.max_steps + num_train_epochs = args.max_steps // num_update_steps_per_epoch + int( + args.max_steps % num_update_steps_per_epoch > 0 + ) + # May be slightly incorrect if the last batch in the training dataloader has a smaller size but it's + # the best we can do. + num_train_samples = args.max_steps * total_train_batch_size + else: + max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch) + num_train_epochs = math.ceil(args.num_train_epochs) + num_train_samples = self.num_examples(train_dataloader) * args.num_train_epochs + elif args.max_steps > 0: # Rely on max_steps when dataloader does not have a working size + max_steps = args.max_steps + # Setting a very large number of epochs so we go as many times as necessary over the iterator. + num_train_epochs = sys.maxsize + num_update_steps_per_epoch = max_steps + num_examples = total_train_batch_size * args.max_steps + num_train_samples = args.max_steps * total_train_batch_size + else: + raise ValueError( + "args.max_steps must be set to a positive value if dataloader does not have a length, was" + f" {args.max_steps}" + ) + + if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug: + if self.args.n_gpu > 1: + # nn.DataParallel(model) replicates the model, creating new variables and module + # references registered here no longer work on other gpus, breaking the module + raise ValueError( + "Currently --debug underflow_overflow is not supported under DP. Please use DDP" + " (torch.distributed.launch)." + ) + else: + debug_overflow = DebugUnderflowOverflow(self.model) # noqa + + delay_optimizer_creation = ( + self.sharded_ddp is not None + and self.sharded_ddp != ShardedDDPOption.SIMPLE + or is_sagemaker_mp_enabled() + or self.fsdp is not None + ) + if args.deepspeed: + deepspeed_engine, optimizer, lr_scheduler = deepspeed_init( + self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint + ) + self.model = deepspeed_engine.module + self.model_wrapped = deepspeed_engine + self.deepspeed = deepspeed_engine + self.optimizer = optimizer + self.lr_scheduler = lr_scheduler + elif not delay_optimizer_creation: + self.create_optimizer_and_scheduler(num_training_steps=max_steps) + + self.state = TrainerState() + self.state.is_hyper_param_search = trial is not None + + # Activate gradient checkpointing if needed + if args.gradient_checkpointing: + self.model.gradient_checkpointing_enable() + + model = self._wrap_model(self.model_wrapped) + + if is_sagemaker_mp_enabled() and resume_from_checkpoint is not None: + self._load_from_checkpoint(resume_from_checkpoint, model) + + # for the rest of this function `model` is the outside model, whether it was wrapped or not + if model is not self.model: + self.model_wrapped = model + + if delay_optimizer_creation: + self.create_optimizer_and_scheduler(num_training_steps=max_steps) + + # Check if saved optimizer or scheduler states exist + self._load_optimizer_and_scheduler(resume_from_checkpoint) + + # important: at this point: + # self.model is the Transformers Model + # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc. + + # Train! + logger.info("***** Running training *****") + logger.info(f" Num examples = {num_examples}") + logger.info(f" Num Epochs = {num_train_epochs}") + logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") + logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}") + logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") + logger.info(f" Total optimization steps = {max_steps}") + logger.info( + f" Number of trainable parameters = {sum(p.numel() for p in model.parameters() if p.requires_grad)}" + ) + + self.state.epoch = 0 + start_time = time.time() + epochs_trained = 0 + steps_trained_in_current_epoch = 0 + steps_trained_progress_bar = None + + # Check if continuing training from a checkpoint + if resume_from_checkpoint is not None and os.path.isfile( + os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME) + ): + self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)) + epochs_trained = self.state.global_step // num_update_steps_per_epoch + if not args.ignore_data_skip: + steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch) + steps_trained_in_current_epoch *= args.gradient_accumulation_steps + else: + steps_trained_in_current_epoch = 0 + + logger.info(" Continuing training from checkpoint, will skip to saved global_step") + logger.info(f" Continuing training from epoch {epochs_trained}") + logger.info(f" Continuing training from global step {self.state.global_step}") + if not args.ignore_data_skip: + logger.info( + f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} " + "batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` " + "flag to your launch command, but you will resume the training on data already seen by your model." + ) + if self.is_local_process_zero() and not args.disable_tqdm: + steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch) + steps_trained_progress_bar.set_description("Skipping the first batches") + + # Update the references + self.callback_handler.model = self.model + self.callback_handler.optimizer = self.optimizer + self.callback_handler.lr_scheduler = self.lr_scheduler + self.callback_handler.train_dataloader = train_dataloader + if self.hp_name is not None and self._trial is not None: + # use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial + # parameter to Train when using DDP. + self.state.trial_name = self.hp_name(self._trial) + if trial is not None: + assignments = trial.assignments if self.hp_search_backend == HPSearchBackend.SIGOPT else trial + self.state.trial_params = hp_params(assignments) + else: + self.state.trial_params = None + # This should be the same if the state has been saved but in case the training arguments changed, it's safer + # to set this after the load. + self.state.max_steps = max_steps + self.state.num_train_epochs = num_train_epochs + self.state.is_local_process_zero = self.is_local_process_zero() + self.state.is_world_process_zero = self.is_world_process_zero() + + # tr_loss is a tensor to avoid synchronization of TPUs through .item() + tr_loss = torch.tensor(0.0).to(args.device) + # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses + self._total_loss_scalar = 0.0 + self._globalstep_last_logged = self.state.global_step + model.zero_grad() + + self.control = self.callback_handler.on_train_begin(args, self.state, self.control) + + # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. + if not args.ignore_data_skip: + for epoch in range(epochs_trained): + is_random_sampler = hasattr(train_dataloader, "sampler") and isinstance( + train_dataloader.sampler, RandomSampler + ) + if is_torch_less_than_1_11 or not is_random_sampler: + # We just need to begin an iteration to create the randomization of the sampler. + # That was before PyTorch 1.11 however... + for _ in train_dataloader: + break + else: + # Otherwise we need to call the whooooole sampler cause there is some random operation added + # AT THE VERY END! + _ = list(train_dataloader.sampler) + + for epoch in range(epochs_trained, num_train_epochs): + if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): + train_dataloader.sampler.set_epoch(epoch) + elif hasattr(train_dataloader, "dataset") and isinstance(train_dataloader.dataset, IterableDatasetShard): + train_dataloader.dataset.set_epoch(epoch) + + if is_torch_tpu_available(): + parallel_loader = pl.ParallelLoader(train_dataloader, [args.device]).per_device_loader(args.device) + epoch_iterator = parallel_loader + else: + epoch_iterator = train_dataloader + + # Reset the past mems state at the beginning of each epoch if necessary. + if args.past_index >= 0: + self._past = None + + steps_in_epoch = ( + len(epoch_iterator) + if len_dataloader is not None + else args.max_steps * args.gradient_accumulation_steps + ) + self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control) + + if epoch == epochs_trained and resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0: + self._load_rng_state(resume_from_checkpoint) + + step = -1 + for step, inputs in enumerate(epoch_iterator): + + # Skip past any already trained steps if resuming training + if steps_trained_in_current_epoch > 0: + steps_trained_in_current_epoch -= 1 + if steps_trained_progress_bar is not None: + steps_trained_progress_bar.update(1) + if steps_trained_in_current_epoch == 0: + self._load_rng_state(resume_from_checkpoint) + continue + elif steps_trained_progress_bar is not None: + steps_trained_progress_bar.close() + steps_trained_progress_bar = None + + if step % args.gradient_accumulation_steps == 0: + self.control = self.callback_handler.on_step_begin(args, self.state, self.control) + + # MeZO added: estimate gradient + if args.trainer == "zo": + tr_loss_step = self.zo_step(model, inputs) + else: + if ( + ((step + 1) % args.gradient_accumulation_steps != 0) + and args.local_rank != -1 + and args._no_sync_in_gradient_accumulation + ): + # Avoid unnecessary DDP synchronization since there will be no backward pass on this example. + with model.no_sync(): + tr_loss_step = self.training_step(model, inputs) + else: + tr_loss_step = self.training_step(model, inputs) + + if ( + args.logging_nan_inf_filter + and not is_torch_tpu_available() + and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step)) + ): + # if loss is nan or inf simply add the average of previous logged losses + tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged) + else: + tr_loss += tr_loss_step + + self.current_flos += float(self.floating_point_ops(inputs)) + + # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps + if self.deepspeed: + self.deepspeed.step() + + if (step + 1) % args.gradient_accumulation_steps == 0 or ( + # last step in epoch but step is always smaller than gradient_accumulation_steps + steps_in_epoch <= args.gradient_accumulation_steps + and (step + 1) == steps_in_epoch + ): + # MeZO added: update model with the estimated gradient + if args.trainer == "zo": + self.zo_update(model) + else: + # Gradient clipping + if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed: + # deepspeed does its own clipping + + if self.do_grad_scaling: + # Reduce gradients first for XLA + if is_torch_tpu_available(): + gradients = xm._fetch_gradients(self.optimizer) + xm.all_reduce("sum", gradients, scale=1.0 / xm.xrt_world_size()) + # AMP: gradients need unscaling + self.scaler.unscale_(self.optimizer) + + if is_sagemaker_mp_enabled() and args.fp16: + self.optimizer.clip_master_grads(args.max_grad_norm) + elif hasattr(self.optimizer, "clip_grad_norm"): + # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping + self.optimizer.clip_grad_norm(args.max_grad_norm) + elif hasattr(model, "clip_grad_norm_"): + # Some models (like FullyShardedDDP) have a specific way to do gradient clipping + model.clip_grad_norm_(args.max_grad_norm) + else: + # Revert to normal clipping otherwise, handling Apex or full precision + nn.utils.clip_grad_norm_( + amp.master_params(self.optimizer) if self.use_apex else model.parameters(), + args.max_grad_norm, + ) + + # Optimizer step + optimizer_was_run = True + if self.deepspeed: + pass # called outside the loop + elif is_torch_tpu_available(): + if self.do_grad_scaling: + self.scaler.step(self.optimizer) + self.scaler.update() + else: + xm.optimizer_step(self.optimizer) + elif self.do_grad_scaling: + scale_before = self.scaler.get_scale() + self.scaler.step(self.optimizer) + self.scaler.update() + scale_after = self.scaler.get_scale() + optimizer_was_run = scale_before <= scale_after + else: + self.optimizer.step() + + if optimizer_was_run and not self.deepspeed: + self.lr_scheduler.step() + model.zero_grad() + + self.state.global_step += 1 + self.state.epoch = epoch + (step + 1) / steps_in_epoch + self.control = self.callback_handler.on_step_end(args, self.state, self.control) + + self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval) + else: + self.control = self.callback_handler.on_substep_end(args, self.state, self.control) + + if self.control.should_epoch_stop or self.control.should_training_stop: + break + if step < 0: + logger.warning( + "There seems to be not a single sample in your epoch_iterator, stopping training at step" + f" {self.state.global_step}! This is expected if you're using an IterableDataset and set" + f" num_steps ({max_steps}) higher than the number of available samples." + ) + self.control.should_training_stop = True + + self.control = self.callback_handler.on_epoch_end(args, self.state, self.control) + self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval) + + if DebugOption.TPU_METRICS_DEBUG in self.args.debug: + if is_torch_tpu_available(): + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + else: + logger.warning( + "You enabled PyTorch/XLA debug metrics but you don't have a TPU " + "configured. Check your training configuration if this is unexpected." + ) + if self.control.should_training_stop: + break + + if args.past_index and hasattr(self, "_past"): + # Clean the state at the end of training + delattr(self, "_past") + + logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") + if args.load_best_model_at_end and self.state.best_model_checkpoint is not None: + # Wait for everyone to get here so we are sur the model has been saved by process 0. + if is_torch_tpu_available(): + xm.rendezvous("load_best_model_at_end") + elif args.local_rank != -1: + dist.barrier() + elif is_sagemaker_mp_enabled(): + smp.barrier() + + self._load_best_model() + + # add remaining tr_loss + self._total_loss_scalar += tr_loss.item() + train_loss = self._total_loss_scalar / self.state.global_step + + metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps) + self.store_flos() + metrics["total_flos"] = self.state.total_flos + metrics["train_loss"] = train_loss + + self.is_in_train = False + + self._memory_tracker.stop_and_update_metrics(metrics) + + self.log(metrics) + + run_dir = self._get_output_dir(trial) + checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir) + + # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint. + if self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1: + for checkpoint in checkpoints_sorted: + if checkpoint != self.state.best_model_checkpoint: + logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") + shutil.rmtree(checkpoint) + + self.control = self.callback_handler.on_train_end(args, self.state, self.control) + + return TrainOutput(self.state.global_step, train_loss, metrics) + + + ############## MeZO ############## + + + def zo_perturb_parameters(self, random_seed=None, scaling_factor=1): + """ + Perturb the parameters with random vector z. + Input: + - random_seed: random seed for MeZO in-place perturbation (if it's None, we will use self.zo_random_seed) + - scaling_factor: theta = theta + scaling_factor * z * eps + """ + + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(random_seed if random_seed is not None else self.zo_random_seed) + + for name, param in self.named_parameters_to_optim: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * self.args.zo_eps + + + def zo_forward(self, model, inputs): + """ + Get (no gradient) loss from the model. Dropout is turned off too. + """ + model.eval() + if self.args.non_diff: + # Non-differentiable objective (may require autoregressive generation) + return self.zo_forward_nondiff(model, inputs) + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + # Warning: this is copied from the original Huggingface Trainer. Untested. + loss = loss.mean() # mean() to average on multi-gpu parallel training + return loss.detach() + + + def zo_forward_nondiff(self, model, inputs): + """ + Get (no gradient) non-diffiable loss from the model. + """ + model.eval() + assert self.args.task_name == "SQuAD", "Non differentiable objective only supports SQuAD for now." + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + args = self.args + outputs = self.model.generate( + inputs["input_ids"], do_sample=args.sampling, temperature=args.temperature, + num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - inputs["input_ids"].size(1)), + num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id], + ) + output_text = [] + for i in range(len(outputs)): + output_text.append(self.tokenizer.decode(outputs[i][inputs["input_ids"].size(1):], skip_special_tokens=True).strip()) + f1s = [f1(output_text[i], inputs['gold'][i]) for i in range(len(output_text))] + + return -torch.tensor(np.mean(f1s), dtype=torch.float32) + + + def zo_step(self, model, inputs): + """ + Estimate gradient by MeZO. Return the loss from f(theta + z) + """ + args = self.args + + # What parameters to optimize + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + + # Sample the random seed for sampling z + self.zo_random_seed = np.random.randint(1000000000) + + # First function evaluation + self.zo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + # Second function evaluation + self.zo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + + # No gradient accumulation support + assert self.args.gradient_accumulation_steps == 1 + + # Reset model back to its parameters at start of step + self.zo_perturb_parameters(scaling_factor=1) + + return loss1 + + + def zo_update(self, model): + """ + Update the parameters with the estimated gradients. + """ + args = self.args + + # Reset the random seed for sampling zs + torch.manual_seed(self.zo_random_seed) + + for name, param in self.named_parameters_to_optim: + # Resample z + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * z + args.weight_decay * param.data) + else: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * z) + + self.lr_scheduler.step() + + + ############## Misc overload functions ############## + + + def _set_signature_columns_if_needed(self): + """ + We overload this function for non-differentiable objective training to pass "gold" -- the gold text for the task + """ + if self._signature_columns is None: + # Inspect model forward signature to keep only the arguments it accepts. + signature = inspect.signature(self.model.forward) + self._signature_columns = list(signature.parameters.keys()) + # Labels may be named label or label_ids, the default data collator handles that. + self._signature_columns += list(set(["label", "label_ids"] + self.label_names)) + self._signature_columns += ["gold"] + + + def save_model(self, output_dir: Optional[str] = None, _internal_call: bool = False): + """ + We overload this function to fix an FSDP saving bug (before fix, it will likely cause OOM) + """ + + if output_dir is None: + output_dir = self.args.output_dir + + if is_torch_tpu_available(): + self._save_tpu(output_dir) + elif is_sagemaker_mp_enabled(): + # Calling the state_dict needs to be done on the wrapped model and on all processes. + os.makedirs(output_dir, exist_ok=True) + state_dict = self.model_wrapped.state_dict() + if self.args.should_save: + self._save(output_dir, state_dict=state_dict) + if IS_SAGEMAKER_MP_POST_1_10: + # 'user_content.pt' indicates model state_dict saved with smp >= 1.10 + Path(os.path.join(output_dir, "user_content.pt")).touch() + elif ( + ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp + or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp + or self.fsdp is not None + ): + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, StateDictType, FullStateDictConfig + full_state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) + + # Fix the FSDP loading bug + with FSDP.state_dict_type(self.model, StateDictType.FULL_STATE_DICT, full_state_dict_config): + state_dict = self.model.state_dict() + # state_dict = self.model.state_dict() + + if self.args.should_save: + self._save(output_dir, state_dict=state_dict) + elif self.deepspeed: + # this takes care of everything as long as we aren't under zero3 + if self.args.should_save: + self._save(output_dir) + + if is_deepspeed_zero3_enabled(): + # It's too complicated to try to override different places where the weights dump gets + # saved, so since under zero3 the file is bogus, simply delete it. The user should + # either user deepspeed checkpoint to resume or to recover full weights use + # zero_to_fp32.py stored in the checkpoint. + if self.args.should_save: + file = os.path.join(output_dir, WEIGHTS_NAME) + if os.path.isfile(file): + # logger.info(f"deepspeed zero3: removing {file}, see zero_to_fp32.py to recover weights") + os.remove(file) + + # now save the real model if stage3_gather_16bit_weights_on_model_save=True + # if false it will not be saved. + # This must be called on all ranks + if not self.deepspeed.save_16bit_model(output_dir, WEIGHTS_NAME): + logger.warning( + "deepspeed.save_16bit_model didn't save the model, since" + " stage3_gather_16bit_weights_on_model_save=false. Saving the full checkpoint instead, use" + " zero_to_fp32.py to recover weights" + ) + self.deepspeed.save_checkpoint(output_dir) + + elif self.args.should_save: + self._save(output_dir) + + # Push to the Hub when `save_model` is called by the user. + if self.args.push_to_hub and not _internal_call: + self.push_to_hub(commit_message="Model save") diff --git a/baselines/lozo/large_models/utils.py b/baselines/lozo/large_models/utils.py new file mode 100644 index 0000000..317c039 --- /dev/null +++ b/baselines/lozo/large_models/utils.py @@ -0,0 +1,355 @@ +import json +import os +import contextlib +from typing import Optional, Union +import numpy as np +from dataclasses import dataclass, is_dataclass, asdict +import logging +import time +from torch.nn import CrossEntropyLoss +import torch.nn.functional as F +from transformers.modeling_outputs import CausalLMOutputWithPast +import torch +from transformers.utils import PaddingStrategy +from transformers import PreTrainedTokenizerBase +from transformers.data.data_collator import DataCollatorMixin +import transformers +from typing import Optional, Union, List, Dict, Any +import signal +from subprocess import call +from collections.abc import Mapping +from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union +InputDataClass = NewType("InputDataClass", Any) +from dataclasses import dataclass +from transformers.tokenization_utils_base import PreTrainedTokenizerBase + + + +logger = logging.getLogger(__name__) + + +def forward_wrap_with_option_len(self, input_ids=None, labels=None, option_len=None, num_options=None, return_dict=None, **kwargs): + """ + This is to replace the original forward function of Transformer models to enable: + (1) Partial target sequence: loss will only be calculated on part of the sequence + (2) Classification-style training: a classification loss (CE) will be calculated over several options + Input: + - input_ids, labels: same as the original forward function + - option_len: a list of int indicating the option lengths, and loss will be calculated only on the + last option_len tokens + - num_options: a list of int indicating the number of options for each example (this will be #label + words for classification tasks and #choices for multiple choice tasks), and a classification loss + will be calculated. + """ + outputs = self.original_forward(input_ids=input_ids, **kwargs) + if labels is None: + return outputs + logits = outputs.logits + + loss = None + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + # Here we use input_ids (which should always = labels) bc sometimes labels are correct candidate IDs + shift_labels = torch.clone(input_ids)[..., 1:].contiguous() + shift_labels[shift_labels == self.config.pad_token_id] = -100 + + # Apply option len (do not calculate loss on the non-option part) + for _i, _len in enumerate(option_len): + shift_labels[_i, :-_len] = -100 + + # Calculate the loss + loss_fct = CrossEntropyLoss(ignore_index=-100) + if num_options is not None: + # Train as a classification tasks + log_probs = F.log_softmax(shift_logits, dim=-1) + mask = shift_labels != -100 # Option part + shift_labels[~mask] = 0 # So that it doesn't mess up with indexing + + selected_log_probs = torch.gather(log_probs, dim=-1, index=shift_labels.unsqueeze(-1)).squeeze(-1) # (bsz x num_options, len) + selected_log_probs = (selected_log_probs * mask).sum(-1) / mask.sum(-1) # (bsz x num_options) + + if any([x != num_options[0] for x in num_options]): + # Multi choice tasks with different number of options + loss = 0 + start_id = 0 + count = 0 + while start_id < len(num_options): + end_id = start_id + num_options[start_id] + _logits = selected_log_probs[start_id:end_id].unsqueeze(0) # (1, num_options) + _labels = labels[start_id:end_id][0].unsqueeze(0) # (1) + loss = loss_fct(_logits, _labels) + loss + count += 1 + start_id = end_id + loss = loss / count + else: + num_options = num_options[0] + selected_log_probs = selected_log_probs.view(-1, num_options) # (bsz, num_options) + labels = labels.view(-1, num_options)[:, 0] # Labels repeat so we only take the first one + loss = loss_fct(selected_log_probs, labels) + else: + loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +def encode_prompt(task, template, train_samples, eval_sample, tokenizer, max_length, sfc=False, icl_sfc=False, generation=False, generation_with_gold=False, max_new_tokens=None): + """ + Encode prompts for eval_sample + Input: + - task, template: task and template class + - train_samples, eval_sample: demonstrations and the actual sample + - tokenizer, max_length: tokenizer and max length + - sfc: generate prompts for calibration (surface form competition; https://arxiv.org/abs/2104.08315) + - icl_sfc: generate prompts for ICL version calibration + - generation: whether it is an generation task + - generation_with_gold: whether to include the generation-task gold answers (for training) + - max_new_tokens: max number of new tokens to generate so that we can save enough space + (only for generation tasks) + Output: + - encodings: a list of N lists of tokens. N is the number of options for classification/multiple-choice. + - option_lens: a list of N integers indicating the number of option tokens. + """ + + # Demonstrations for ICL + train_prompts = [template.verbalize(sample, sample.correct_candidate).strip() for sample in train_samples] + train_prompts = task.train_sep.join(train_prompts).strip() + + # sfc or icl_sfc indicates that this example is used for calibration + if sfc or icl_sfc: + encode_fn = template.encode_sfc; verbalize_fn = template.verbalize_sfc + else: + encode_fn = template.encode; verbalize_fn = template.verbalize + + unverbalized_eval_prompt = encode_fn(eval_sample).strip(' ') + if not generation: + # We generate one prompt for each candidate (different classes in classification) + # or different choices in multiple-choice tasks + verbalized_eval_prompts = [verbalize_fn(eval_sample, cand).strip(' ') for cand in eval_sample.candidates] + unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt)) + option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts] + + if sfc: + # Without demonstrations + final_prompts = verbalized_eval_prompts + else: + # With demonstrations + final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts] + else: + assert not sfc and not icl_sfc, "Generation tasks do not support SFC" + if generation_with_gold: + verbalized_eval_prompts = [verbalize_fn(eval_sample, eval_sample.correct_candidate)] + unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt)) + option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts] + final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts] + else: + option_lens = [0] + final_prompts = [(train_prompts + task.train_sep + unverbalized_eval_prompt).lstrip().strip(' ')] + + # Tokenize + encodings = [tokenizer.encode(final_prompt) for final_prompt in final_prompts] + + # Truncate (left truncate as demonstrations are less important) + if generation and max_new_tokens is not None: + max_length = max_length - max_new_tokens + + if any([len(encoding) > max_length for encoding in encodings]): + logger.warn("Exceed max length") + if tokenizer.add_bos_token: + encodings = [encoding[0:1] + encoding[1:][-(max_length-1):] for encoding in encodings] + else: + encodings = [encoding[-max_length:] for encoding in encodings] + + return encodings, option_lens + + + +@dataclass +class ICLCollator: + """ + Collator for ICL + """ + tokenizer: PreTrainedTokenizerBase + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + if not isinstance(features[0], Mapping): + features = [vars(f) for f in features] + first = features[0] + batch = {} + + pad_id = self.tokenizer.pad_token_id + + pad_ids = {"input_ids": pad_id, "attention_mask": 0, "sfc_input_ids": pad_id, "sfc_attention_mask": 0, "labels": pad_id} + for key in first: + pp = pad_ids[key] + lens = [len(f[key]) for f in features] + max_len = max(lens) + feature = np.stack([np.pad(f[key], (0, max_len - lens[i]), "constant", constant_values=(0, pp)) for i, f in enumerate(features)]) + padded_feature = torch.from_numpy(feature).long() + batch[key] = padded_feature + + return batch + + +@dataclass +class DataCollatorWithPaddingAndNesting: + """ + Collator for training + """ + + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str, PaddingStrategy] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + return_tensors: str = "pt" + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + features = [ff for f in features for ff in f] + batch = self.tokenizer.pad( + features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors=self.return_tensors, + ) + if "label" in batch: + batch["labels"] = batch["label"] + del batch["label"] + if "label_ids" in batch: + batch["labels"] = batch["label_ids"] + del batch["label_ids"] + return batch + + +@dataclass +class NondiffCollator(DataCollatorMixin): + """ + Collator for non-differentiable objectives + """ + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str, PaddingStrategy] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + label_pad_token_id: int = -100 + return_tensors: str = "pt" + + def torch_call(self, features): + import torch + + label_name = "label" if "label" in features[0].keys() else "labels" + labels = [feature[label_name] for feature in features] if label_name in features[0].keys() else None + + no_labels_features = [{k: v for k, v in feature.items() if k != label_name and k != "gold"} for feature in features] + + batch = self.tokenizer.pad( + no_labels_features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors="pt", + ) + + if labels is None: + return batch + + sequence_length = batch["input_ids"].shape[1] + padding_side = self.tokenizer.padding_side + + def to_list(tensor_or_iterable): + if isinstance(tensor_or_iterable, torch.Tensor): + return tensor_or_iterable.tolist() + return list(tensor_or_iterable) + + if padding_side == "right": + batch[label_name] = [ + to_list(label) + [self.label_pad_token_id] * (sequence_length - len(label)) for label in labels + ] + else: + batch[label_name] = [ + [self.label_pad_token_id] * (sequence_length - len(label)) + to_list(label) for label in labels + ] + + batch[label_name] = torch.tensor(batch[label_name], dtype=torch.int64) + if "gold" in features[0]: + batch["gold"] = [feature["gold"] for feature in features] + + return batch + + +class SIGUSR1Callback(transformers.TrainerCallback): + """ + This callback is used to save the model when a SIGUSR1 signal is received + (SLURM stop signal or a keyboard interruption signal). + """ + + def __init__(self) -> None: + super().__init__() + self.signal_received = False + signal.signal(signal.SIGUSR1, self.handle_signal) + signal.signal(signal.SIGINT, self.handle_signal) + logger.warn("Handler registered") + + def handle_signal(self, signum, frame): + self.signal_received = True + logger.warn("Signal received") + + def on_step_end(self, args, state, control, **kwargs): + if self.signal_received: + control.should_save = True + control.should_training_stop = True + + def on_train_end(self, args, state, control, **kwargs): + if self.signal_received: + exit(0) + + +@dataclass +class Prediction: + correct_candidate: Union[int, str] + predicted_candidate: Union[int, str] + + +@contextlib.contextmanager +def count_time(name): + logger.info("%s..." % name) + start_time = time.time() + try: + yield + finally: + logger.info("Done with %.2fs" % (time.time() - start_time)) + + +@contextlib.contextmanager +def temp_seed(seed): + state = np.random.get_state() + np.random.seed(seed) + try: + yield + finally: + np.random.set_state(state) + + +class EnhancedJSONEncoder(json.JSONEncoder): + def default(self, o): + if is_dataclass(o): + return asdict(o) + return super().default(o) + + +def write_predictions_to_file(final_preds, output): + with open(output, "w") as f: + for pred in final_preds: + f.write(json.dumps(pred, cls=EnhancedJSONEncoder) + "\n") + + +def write_metrics_to_file(metrics, output): + json.dump(metrics, open(output, "w"), cls=EnhancedJSONEncoder, indent=4) \ No newline at end of file diff --git a/baselines/lozo/medium_models/README.md b/baselines/lozo/medium_models/README.md new file mode 100644 index 0000000..b702320 --- /dev/null +++ b/baselines/lozo/medium_models/README.md @@ -0,0 +1,68 @@ +# LOZO on Medium-sized Masked Language Models + +This part of the code is for LOZO experiments on RoBERTa-large. It is based on [LM-Kernel-FT](https://github.com/princeton-nlp/LM-Kernel-FT), [LM-BFF](https://github.com/princeton-nlp/LM-BFF) and [MeZO](https://github.com/princeton-nlp/MeZO). We add new files: `run_lozo.py`, `lozo.sh`, `src/LOZOtrainer.py` and `run_fewshot_lozo.sh`. These files support the replication of our experiments. + + +## Installation + +Please install the latest versions of PyTorch (`pytorch` following [https://pytorch.org](https://pytorch.org)) and Transformers (`transformers`). This code is tested on `torch==2.1.0.dev20230514+cu118` and `transformers==4.28.1` with Python 3.9.7, but should work with older/later versions of these packages too. + +## Prepare the data + +We pack the datasets [here](https://nlp.cs.princeton.edu/projects/lm-bff/datasets.tar). Please download it and extract the files to `./data/original`, or run the following commands: + +```bash +cd data +bash download_dataset.sh +``` + +Then use the following command (in the `medium_models` folder) to generate the data we need: + +```bash +for K in 16 512; do + # Generate k-shot splits for seeds 13,21,42,87,100 with a maximum of 1k test examples in data/k-shot-1k-test, + # where k is the number of training/validation examples per label + python tools/generate_k_shot_data.py --mode k-shot-1k-test --k $K +done +``` + +See `tools/generate_k_shot_data.py` for more options. For results in the paper, we use the default options: we take `K=16` and `K=512` and take 5 different seeds of 13, 21, 42, 87, 100. The few-shot data will be generated to `data/k-shot-1k-test`. In the directory of each dataset, there will be folders named as `$K-$SEED` indicating different dataset samples. + +## Usage + +Use `run_lozo.py` for all functions and refer to `run_lozo.py` for the usage of all arguments. +```bash +python run_lozo.py {ARGUMENTS} +``` + +To reproduce our results in the paper, we also provide two example files `finetune.sh` (for all fine-tuning experiments) `mezo.sh` (for all MeZO experiments) and `lozo.sh` (for all LOZO experiments). You can run them directly with the following commands (we use the following six datasets in our experiments -- `SST-2`, `sst-5`, `SNLI`, `MNLI`, `RTE`, and `trec`): +```bash +# Adam fine-tuning +TASK=SST-2 K=16 SEED=42 BS=8 LR=1e-5 MODEL=roberta-large bash finetune.sh + +# Adam fine-tuning + LoRA +TASK=SST-2 K=16 SEED=42 BS=8 LR=1e-4 MODEL=roberta-large EXTRA_TAG=lora bash finetune.sh --apply_lora --lora_r 8 --lora_alpha 16 + +# MeZO +TASK=SST-2 K=16 SEED=42 BS=64 LR=1e-6 EPS=1e-3 MODEL=roberta-large bash mezo.sh + +# MeZO + LoRA +TASK=SST-2 K=16 SEED=42 BS=64 LR=1e-4 EPS=1e-3 MODEL=roberta-large EXTRA_TAG=lora bash mezo.sh --apply_lora --lora_r 8 --lora_alpha 16 + +# LOZO +TASK=SST-2 K=16 SEED=42 BS=64 LR=1e-7 EPS=1e-3 MODEL=roberta-large RANK=4 STEP_INTERVAL=100 bash lozo.sh + +# LOZO-M +TASK=SST-2 K=16 SEED=42 BS=64 LR=1e-7 EPS=1e-3 MODEL=roberta-large RANK=4 STEP_INTERVAL=100 LOZO_OPTIMIZER=sgdm bash lozo.sh +``` + + +## Gather results + +All the results will be stored in `./log`. To analyze the results (for example, examine the grid search), use the following command +```bash +python tools/gather_result.py --condition "{'tag': 'k16-roberta-large-ft', 'task_name': 'sst-2'}" +``` + +Then the program will find all the trials that satisfy the condition in `./log`, and print the mean/std of the final results. Note that the task names are all lower-cased here. + diff --git a/baselines/lozo/medium_models/finetune.sh b/baselines/lozo/medium_models/finetune.sh new file mode 100644 index 0000000..abce1bc --- /dev/null +++ b/baselines/lozo/medium_models/finetune.sh @@ -0,0 +1,36 @@ +#!/bin/bash + + +TASK=${TASK:-SST-2} +K=${K:-16} +SEED=${SEED:-42} +BS=${BS:-8} +LR=${LR:-1e-5} +STEP=${STEP:-1000} +EVAL_STEP=${EVAL_STEP:-100} +MODEL=${MODEL:-"../../../Model/roberta-large"} + +LOGITS=$(jq -n '{"SNLI": 3, "MNLI": 3, "trec": 6, "sst-5": 5}["'$TASK'"] // 2') + +echo "TASK: $TASK" +echo "K: $K" +echo "Seed: $SEED" +echo "BS: $BS" +echo "LR: $LR" +echo "Step: $STEP; Eval step: $EVAL_STEP" + +GR_TAG=seed$SEED-bs$BS-lr$LR-eps$EPS-wd$WD-step$STEP-evalstep$EVAL_STEP +EXTRA_TAG=${EXTRA_TAG:-ft} +TAG=${TAG:-k${K}-${MODELNAME}-${EXTRA_TAG}} + +echo "Grid search tag: $GR_TAG" +echo "Tag: $TAG" + +# 创建日志目录 +mkdir -p log_dir +# Redirect all output to a log file based on the TAG +exec &> >(tee "log_dir/${TASK}-${GR_TAG}-${TAG}.log") + +TYPE=prompt GRID_TAG=$GR_TAG TAG=$TAG STEPS=$STEP TASK=$TASK SEED=$SEED MODEL=$MODEL K=$K \ + bash run_fewshot.sh --per_device_train_batch_size $BS --learning_rate $LR --eval_steps $EVAL_STEP \ + $@ diff --git a/baselines/lozo/medium_models/lozo.sh b/baselines/lozo/medium_models/lozo.sh new file mode 100644 index 0000000..106f1e4 --- /dev/null +++ b/baselines/lozo/medium_models/lozo.sh @@ -0,0 +1,45 @@ +#!/bin/bash + +TASK=${TASK:-SNLI} +K=${K:-16} +SEED=${SEED:-42} +BS=${BS:-64} +LR=${LR:-1e-6} +EPS=${EPS:-1e-3} +WD=${WD:-0} +STEP=${STEP:-100000} +EVAL_STEP=${EVAL_STEP:-10000} +STEP_INTERVAL=${STEP_INTERVAL:-50} +RANK=${RANK:-4} +LOZO_OPTIMIZER=${LOZO_OPTIMIZER:-'sgd'} +BETA1=${BETA1:-0.9} +MODEL=${MODEL:-"../../../Model/roberta-large"} +MODELNAME=${MODELNAME:-"roberta-large"} + +LOGITS=$(jq -n '{"SNLI": 3, "MNLI": 3, "trec": 6, "sst-5": 5}["'$TASK'"] // 2') + +echo "TASK: $TASK" +echo "K: $K" +echo "Seed: $SEED" +echo "BS: $BS" +echo "LR: $LR" +echo "EPS: $EPS" +echo "Step: $STEP; Eval step: $EVAL_STEP" + +GR_TAG=seed$SEED-bs$BS-lr$LR-eps$EPS-wd$WD-step$STEP-evalstep$EVAL_STEP-step-interval$STEP_INTERVAL-rank$RANK +EXTRA_TAG=${EXTRA_TAG:-ft} +TAG=${TAG:-k${K}-${MODELNAME}-lowrank-${EXTRA_TAG}-${LOZO_OPTIMIZER}-beta1-${BETA1}} + +echo "Grid search tag: $GR_TAG" +echo "Tag: $TAG" + +# 创建日志目录 +mkdir -p log_dir +# Redirect all output to a log file based on the TAG +exec &> >(tee "log_dir/${TASK}-${GR_TAG}-${TAG}.log") + +TYPE=prompt GRID_TAG=$GR_TAG TAG=$TAG STEPS=$STEP TASK=$TASK SEED=$SEED MODEL=$MODEL K=$K \ + bash run_fewshot_lozo.sh --per_device_train_batch_size $BS --learning_rate $LR --eval_steps $EVAL_STEP --weight_decay $WD --zo_eps $EPS \ + --zero_order_optim --lr_scheduler_type "constant" --optimizer "sgd" --efficient_zero_order \ + --lozo_optimizer $LOZO_OPTIMIZER --beta1 $BETA1 --step_interval $STEP_INTERVAL --rank $RANK \ + $@ diff --git a/baselines/lozo/medium_models/mezo.sh b/baselines/lozo/medium_models/mezo.sh new file mode 100644 index 0000000..db68043 --- /dev/null +++ b/baselines/lozo/medium_models/mezo.sh @@ -0,0 +1,44 @@ +#!/bin/bash +# -*- coding: utf-8 -*- +export CUDA_VISIBLE_DEVICES=0 +export WANDB_DISABLED=true +export TQDM_DISABLE=1 + +TASK=${TASK:-SNLI} +K=${K:-16} +SEED=${SEED:-42} +BS=${BS:-64} +LR=${LR:-1e-6} +EPS=${EPS:-1e-3} +WD=${WD:-0} +STEP=${STEP:-100000} +EVAL_STEP=${EVAL_STEP:-10000} +MODEL=${MODEL:-"../../../Model/roberta-large"} +MODELNAME=${MODELNAME:-"roberta-large"} + +LOGITS=$(jq -n '{"SNLI": 3, "MNLI": 3, "trec": 6, "sst-5": 5}["'$TASK'"] // 2') + +echo "TASK: $TASK" +echo "K: $K" +echo "Seed: $SEED" +echo "BS: $BS" +echo "LR: $LR" +echo "EPS: $EPS" +echo "Step: $STEP; Eval step: $EVAL_STEP" + +GR_TAG=seed$SEED-bs$BS-lr$LR-eps$EPS-wd$WD-step$STEP-evalstep$EVAL_STEP +EXTRA_TAG=${EXTRA_TAG:-ft} +TAG=${TAG:-k${K}-${MODELNAME}-mezo-${EXTRA_TAG}} + +echo "Grid search tag: $GR_TAG" +echo "Tag: $TAG" + +# 创建日志目录 +mkdir -p log_dir +# Redirect all output to a log file based on the TAG +exec &> >(tee "log_dir/${TASK}-${GR_TAG}-${TAG}.log") + +TYPE=prompt GRID_TAG=$GR_TAG TAG=$TAG STEPS=$STEP TASK=$TASK SEED=$SEED MODEL=$MODEL K=$K \ + bash run_fewshot.sh --per_device_train_batch_size $BS --learning_rate $LR --eval_steps $EVAL_STEP --weight_decay $WD --zero_order_eps $EPS \ + --zero_order_optim --lr_scheduler_type "constant" --optimizer "sgd" --efficient_zero_order \ + $@ diff --git a/baselines/lozo/medium_models/run_fewshot.sh b/baselines/lozo/medium_models/run_fewshot.sh new file mode 100644 index 0000000..5adda43 --- /dev/null +++ b/baselines/lozo/medium_models/run_fewshot.sh @@ -0,0 +1,120 @@ +#!/bin/bash + +# Main settings with default values +TASK=${TASK:-"SST-2"} # see all the options in the "cases" below +SEED=${SEED:-13} # random seed and also data seed, by default the data split seeds are {13, 21, 42, 87, 100} +K=${K:-16} # choose from {16, 64, 512} by default +MODEL=${MODEL:-"roberta-large"} # pick a RoBERTa or BERT model +MODELNAME=${MODELNAME:-"roberta-large"} +TYPE=${TYPE:-"prompt"} # fine-tuning setting, choose from "finetune" and "prompt" +TRAINER=${TRAINER:-"standard"} # choose from "standard" and "linearhead" +TAG=${TAG:-} # set a tag to distinguish and aggregate runs in the log +NUM_GPU=${NUM_GPU:-1} # by default use 1 GPU, set to 0 for CPU-only training +OPT=${OPT:-"adam"} +STEPS=${STEPS:-1000} + +TASK_EXTRA="" +case $TASK in + SST-2) + TEMPLATE=*cls**sent_0*_It_was*mask*.*sep+* + MAPPING="{'0':'terrible','1':'great'}" + ;; + sst-5) + TEMPLATE=*cls**sent_0*_It_was*mask*.*sep+* + MAPPING="{0:'terrible',1:'bad',2:'okay',3:'good',4:'great'}" + TASK_EXTRA="--first_sent_limit 110 --other_sent_limit 20 --double_demo" + ;; + QQP) + TEMPLATE=*cls**sent_0**mask*,*+sentl_1**sep+* + MAPPING="{'0':'No','1':'Yes'}" + ;; + QNLI) + TEMPLATE=*cls**sent-_0*?*mask*,*+sentl_1**sep+* + MAPPING="{'not_entailment':'No','entailment':'Yes'}" + ;; + MNLI) + TEMPLATE=*cls**sent-_0*?*mask*,*+sentl_1**sep+* + MAPPING="{'contradiction':'No','entailment':'Yes','neutral':'Maybe'}" + TASK_EXTRA="--max_seq_len 256 --first_sent_limit 240" + ;; + SNLI) + TEMPLATE=*cls**sent-_0*?*mask*,*+sentl_1**sep+* + MAPPING="{'contradiction':'No','entailment':'Yes','neutral':'Maybe'}" + TASK_EXTRA="--max_seq_len 256 --num_sample 4" + ;; + trec) + TEMPLATE="*cls**mask*:*+sent_0**sep+*" + MAPPING="{0:'Description',1:'Entity',2:'Expression',3:'Human',4:'Location',5:'Number'}" + TASK_EXTRA="--first_sent_limit 110" + ;; + mr) + TEMPLATE=*cls**sent_0*_It_was*mask*.*sep+* + MAPPING="{0:'terrible',1:'great'}" + TASK_EXTRA="--first_sent_limit 110 --other_sent_limit 50" + ;; + cr) + TEMPLATE=*cls**sent_0*_It_was*mask*.*sep+* + MAPPING="{0:'terrible',1:'great'}" + TASK_EXTRA="--first_sent_limit 110 --other_sent_limit 50" + ;; + mpqa) + TEMPLATE=*cls**sent_0*_It_was*mask*.*sep+* + MAPPING="{0:'terrible',1:'great'}" + TASK_EXTRA="--first_sent_limit 110" + ;; + CoLA) + TEMPLATE=*cls**sent_0*_This_is*mask*.*sep+* + MAPPING="{'0':'incorrect','1':'correct'}" + ;; + subj) + TEMPLATE=*cls**sent_0*_This_is*mask*.*sep+* + MAPPING="{0:'subjective',1:'objective'}" + TASK_EXTRA="--first_sent_limit 110 --other_sent_limit 50" + ;; + MRPC) + TEMPLATE=*cls**sent_0**mask*,*+sentl_1**sep+* + MAPPING="{'0':'No','1':'Yes'}" + ;; + RTE) + TEMPLATE=*cls**sent-_0*?*mask*,*+sentl_1**sep+* + MAPPING="{'not_entailment':'No','entailment':'Yes'}" + TASK_EXTRA="--max_seq_len 256 --first_sent_limit 240" + ;; +esac + +ALL_ARGS_TOGETHER=" + --model_name_or_path $MODEL --few_shot_type $TYPE + --task_name $TASK --template $TEMPLATE --mapping $MAPPING + --data_dir data/k-shot-1k-test/$TASK/$K-$SEED + --overwrite_output_dir --output_dir result/$TASK-$MODELNAME-$TYPE-$TRAINER-$TAG-$GRID_TAG/$K-$SEED + --num_k $K + --tag $TAG + --max_seq_length 128 + --seed $SEED + --do_eval --do_predict --do_train + --trainer $TRAINER + --optimizer $OPT --max_steps $STEPS + --logging_steps 10 + --per_device_eval_batch_size 4 + --evaluate_during_training + $TASK_EXTRA + $LOAD_KERNELS + $@ +" + +if [[ $NUM_GPU > 1 ]]; then + # Randomly set a port number + # If you encounter "address already used" error, just run again or manually set an available port id. + PORT_ID=$(expr $RANDOM + 1000) + + # Allow multiple threads + export OMP_NUM_THREADS=8 + + python -m torch.distributed.launch --nproc_per_node $NUM_GPU --master_port $PORT_ID run_mezo.py \ + $ALL_ARGS_TOGETHER +else + python run_mezo.py \ + $ALL_ARGS_TOGETHER +fi + +# rm -rf result/$TASK-$MODELNAME-$TYPE-$TRAINER-$TAG-$GRID_TAG/$K-$SEED diff --git a/baselines/lozo/medium_models/run_fewshot_lozo.sh b/baselines/lozo/medium_models/run_fewshot_lozo.sh new file mode 100644 index 0000000..772feb3 --- /dev/null +++ b/baselines/lozo/medium_models/run_fewshot_lozo.sh @@ -0,0 +1,119 @@ +#!/bin/bash + +# Main settings with default values +TASK=${TASK:-"SST-2"} # see all the options in the "cases" below +SEED=${SEED:-13} # random seed and also data seed, by default the data split seeds are {13, 21, 42, 87, 100} +K=${K:-16} # choose from {16, 64, 512} by default +MODEL=${MODEL:-"roberta-large"} # pick a RoBERTa or BERT model +MODELNAME=${MODELNAME:-"roberta-large"} +TYPE=${TYPE:-"prompt"} # fine-tuning setting, choose from "finetune" and "prompt" +TRAINER=${TRAINER:-"standard"} # choose from "standard" and "linearhead" +TAG=${TAG:-} # set a tag to distinguish and aggregate runs in the log +NUM_GPU=${NUM_GPU:-1} # by default use 1 GPU, set to 0 for CPU-only training +OPT=${OPT:-"adam"} +STEPS=${STEPS:-1000} + +TASK_EXTRA="" +case $TASK in + SST-2) + TEMPLATE=*cls**sent_0*_It_was*mask*.*sep+* + MAPPING="{'0':'terrible','1':'great'}" + ;; + sst-5) + TEMPLATE=*cls**sent_0*_It_was*mask*.*sep+* + MAPPING="{0:'terrible',1:'bad',2:'okay',3:'good',4:'great'}" + TASK_EXTRA="--first_sent_limit 110 --other_sent_limit 20 --double_demo" + ;; + QQP) + TEMPLATE=*cls**sent_0**mask*,*+sentl_1**sep+* + MAPPING="{'0':'No','1':'Yes'}" + ;; + QNLI) + TEMPLATE=*cls**sent-_0*?*mask*,*+sentl_1**sep+* + MAPPING="{'not_entailment':'No','entailment':'Yes'}" + ;; + MNLI) + TEMPLATE=*cls**sent-_0*?*mask*,*+sentl_1**sep+* + MAPPING="{'contradiction':'No','entailment':'Yes','neutral':'Maybe'}" + TASK_EXTRA="--max_seq_len 256 --first_sent_limit 240" + ;; + SNLI) + TEMPLATE=*cls**sent-_0*?*mask*,*+sentl_1**sep+* + MAPPING="{'contradiction':'No','entailment':'Yes','neutral':'Maybe'}" + TASK_EXTRA="--max_seq_len 256 --num_sample 4" + ;; + trec) + TEMPLATE="*cls**mask*:*+sent_0**sep+*" + MAPPING="{0:'Description',1:'Entity',2:'Expression',3:'Human',4:'Location',5:'Number'}" + TASK_EXTRA="--first_sent_limit 110" + ;; + mr) + TEMPLATE=*cls**sent_0*_It_was*mask*.*sep+* + MAPPING="{0:'terrible',1:'great'}" + TASK_EXTRA="--first_sent_limit 110 --other_sent_limit 50" + ;; + cr) + TEMPLATE=*cls**sent_0*_It_was*mask*.*sep+* + MAPPING="{0:'terrible',1:'great'}" + TASK_EXTRA="--first_sent_limit 110 --other_sent_limit 50" + ;; + mpqa) + TEMPLATE=*cls**sent_0*_It_was*mask*.*sep+* + MAPPING="{0:'terrible',1:'great'}" + TASK_EXTRA="--first_sent_limit 110" + ;; + CoLA) + TEMPLATE=*cls**sent_0*_This_is*mask*.*sep+* + MAPPING="{'0':'incorrect','1':'correct'}" + ;; + subj) + TEMPLATE=*cls**sent_0*_This_is*mask*.*sep+* + MAPPING="{0:'subjective',1:'objective'}" + TASK_EXTRA="--first_sent_limit 110 --other_sent_limit 50" + ;; + MRPC) + TEMPLATE=*cls**sent_0**mask*,*+sentl_1**sep+* + MAPPING="{'0':'No','1':'Yes'}" + ;; + RTE) + TEMPLATE=*cls**sent-_0*?*mask*,*+sentl_1**sep+* + MAPPING="{'not_entailment':'No','entailment':'Yes'}" + TASK_EXTRA="--max_seq_len 256 --first_sent_limit 240" + ;; +esac + +ALL_ARGS_TOGETHER=" + --model_name_or_path $MODEL --few_shot_type $TYPE + --task_name $TASK --template $TEMPLATE --mapping $MAPPING + --data_dir data/k-shot-1k-test/$TASK/$K-$SEED + --overwrite_output_dir --output_dir result/$TASK-$MODELNAME-$TYPE-$TRAINER-$TAG-$GRID_TAG/$K-$SEED + --num_k $K + --tag $TAG + --max_seq_length 128 + --seed $SEED + --do_eval --do_predict --do_train + --trainer $TRAINER + --optimizer $OPT --max_steps $STEPS + --logging_steps 10 + --per_device_eval_batch_size 4 + --evaluate_during_training + $TASK_EXTRA + $LOAD_KERNELS + $@ +" + +if [[ $NUM_GPU > 1 ]]; then + # Randomly set a port number + # If you encounter "address already used" error, just run again or manually set an available port id. + PORT_ID=$(expr $RANDOM + 1000) + + # Allow multiple threads + export OMP_NUM_THREADS=8 + + python -m torch.distributed.launch --nproc_per_node $NUM_GPU --master_port $PORT_ID run_lozo.py \ + $ALL_ARGS_TOGETHER +else + python run_lozo.py \ + $ALL_ARGS_TOGETHER +fi + diff --git a/baselines/lozo/medium_models/run_lozo.py b/baselines/lozo/medium_models/run_lozo.py new file mode 100644 index 0000000..7e94f9c --- /dev/null +++ b/baselines/lozo/medium_models/run_lozo.py @@ -0,0 +1,1155 @@ +"""Finetuning the library models for sequence classification on GLUE.""" + +import dataclasses +import logging +import os +import sys +from dataclasses import dataclass, field +from typing import Callable, Dict, Optional, Union, List +import torch +import torch.nn.functional as F + +import numpy as np + +from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, EvalPrediction, PreTrainedTokenizerBase +from src.modeling_roberta import RobertaConfig +from src.modeling_opt import OPTConfig +from transformers import GlueDataTrainingArguments as DataTrainingArguments +from transformers import HfArgumentParser, TrainingArguments, set_seed + +from src.linearhead_trainer import LinearHeadTrainer +from src.dataset import FewShotDataset, OurInputFeatures +from src.models import MODEL_TYPES, resize_token_type_embeddings, convert_opt_model +from src.LOZOtrainer import LowRankTrainer +from src.processors import processors_mapping, num_labels_mapping, output_modes_mapping, compute_metrics_mapping, bound_mapping + +from filelock import FileLock +from datetime import datetime + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. + """ + model_name_or_path: str = field( + metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} + ) + config_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} + ) + tokenizer_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} + ) + cache_dir: Optional[str] = field( + default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} + ) + # Few-shot type + # - finetune: standard fine-tuning + # - prompt: prompt-based fine-tuning + # - prompt-demo: prompt-based fine-tuning with demonstrations + few_shot_type: str = field( + default='prompt-demo', + metadata={"help": "Few-shot learning model type. Choice: finetune, prompt, prompt-demo"} + ) + + # Only for BERT-type model + random_segment: bool = field( + default=False, + metadata={"help": "Whether to reinitialize the token type embeddings (only for BERT)."} + ) + l2_loss: bool = field( + default=False, + metadata={"help": "Whether to use L2 loss (only makes a difference in standard FT)."} + ) + use_task_word: bool = field( + default=False, + metadata={'help': 'uses the task words MLM logit for kernel computation'} + ) + + # LoRA arguments: only for BERT-type model + apply_lora: bool = field( + default=False, + metadata={'help': 'use LoRA for finetuning'} + ) + lora_alpha: int = field( + default=None, + metadata={'help': 'initialization scale for one of the low rank matrices in lora'} + ) + lora_r: int = field( + default=None, + metadata={'help': 'inner rank for lora matrices'} + ) + + # Calibration + sfc: bool = field( + default=False, + metadata={"help": "Whether to use surface form calibration."} + ) + + icl_sfc: bool = field( + default=False, + metadata={"help": "Use in-context learning demos in sfc."} + ) + + +@dataclass +class DynamicDataTrainingArguments(DataTrainingArguments): + """ + Arguments for dynamic training. + """ + num_k: Optional[int] = field( + default=16, + metadata={"help": "Number of training instances per class"} + ) + + num_sample: Optional[int] = field( + default=16, + metadata={"help": "Number of samples (for inference) in fine-tuning with demonstrations"} + ) + + num_demo: Optional[int] = field( + default=1, + metadata={"help": "Number of demonstrations from each class"} + ) + + auto_demo: bool = field( + default=True, + metadata={"help": "Automatically generate template for using demonstrations"} + ) + + # For prompting + sfc_prompt: str = field( + default=None, + metadata={"help": "SFC prompt"} + ) + + template: str = field( + default=None, + metadata={"help": "Template"} + ) + + mapping: str = field( + default=None, + metadata={"help": "Label word mapping"} + ) + + template_path: str = field( + default=None, + metadata={"help": "Path to a txt file that stores all the templates, one per line. Do not set this when prompt_path is used"} + ) + + mapping_path: str = field( + default=None, + metadata={"help": "Path to a txt file that stores all the label word mappings, one per line. Do not set this when prompt_path is used"} + ) + + prompt_path: str = field( + default=None, + metadata={"help": "Path to a txt file that stores all the prompts (templates and mappings), one per line"} + ) + + template_id: int = field( + default=None, + metadata={"help": "Template id if using template_path"} + ) + + mapping_id: int = field( + default=None, + metadata={"help": "Mapping id if using template_path"} + ) + + prompt_id: int = field( + default=None, + metadata={"help": "Prompt id if using prompt_path"} + ) + + top_n_template: int = field( + default=None, + metadata={"help": "Use top-n template in the template path"} + ) + + # For logging + tag: str = field( + default='', + metadata={"help": "Set the tag and find the result easier in the log."} + ) + + # For filtering when using demonstrations + demo_filter: bool = field( + default=False, + metadata={"help": "Only use similar instances in demonstrations"} + ) + + demo_filter_rate: float = field( + default=0.5, + metadata={"help": "Only use top-x\% similar instances in demonstrations"} + ) + + demo_filter_model: str = field( + default=None, + metadata={"help": "Model name for demonstration filter embeddings. Will load embeddings based on the model name."} + ) + + debug_mode: bool = field( + default=False, + metadata={"help": "Debug mode"} + ) + + # For max length + double_demo: bool = field( + default=False, + metadata={"help": "Use double length for using demonstrations"} + ) + + first_sent_limit: int = field( + default=None, + metadata={"help": "Limit the length of the first sentence (i.e., sent_0)"} + ) + + other_sent_limit: int = field( + default=None, + metadata={"help": "Limit the length of sentences other than the first sentence"} + ) + + use_full_length: bool = field( + default=None, + metadata={"help": "Use the full length (512)"} + ) + + # GPT-3's in-context learning + gpt3_in_context_head: bool = field( + default=False, + metadata={"help": "GPT-3's in-context learning (context at the beginning)"} + ) + + gpt3_in_context_tail: bool = field( + default=False, + metadata={"help": "GPT-3's in-context learning (context at the end)"} + ) + + gpt3_in_context_num: int = field( + default=32, + metadata={"help": "Number of context examples"} + ) + + gpt3_demo_separator: str = field( + default="\n\n\n", + metadata={"help": "Separator between demonstrations"} + ) + + truncate_head: bool = field( + default=False, + metadata={"help": "When exceeding the maximum length, truncate the head instead of the tail."} + ) + + # Do not set up the following fields. They are set up automatically. + prompt: bool = field( + default=False, + metadata={"help": "Whether to use prompt-based fine-tuning"} + ) + template_list: List[str] = field( + default=None, + metadata={"help": "(DO NOT List of templates (only initialized after the program starts."}, + + ) + + +@dataclass +class DynamicTrainingArguments(TrainingArguments): + + # =================== LOZO Arguments ===================== + lowrank_zo: bool = field( + default=True, + metadata={"help": "where use low rank zeroth order"} + ) + rank: int = field( + default=2, + metadata={"help": "rank of u and v"} + ) + step_interval: int = field( + default=50, + metadata={"help": "frequency of updating v"} + ) + zo_eps: float = field( + default=1e-3, + metadata={"help": "epsilon of lowrank"} + ) + beta1: float = field( + default=0.7, + metadata={"help": "coefficient of momentum term"} + ) + lozo_optimizer: str = field( + default='sgd', + metadata={"help": "optimizer selection"} + ) + # ======================================================= + + evaluate_during_training: bool = field( + default=False, + metadata={"help": "Whether to run evaluation during training or at the."} + ) + log_file: str = field( + default='log' + ) + + # For ensemble + array_id: int = field( + default=-1, + metadata={"help": "Array ID (contains seed and hyper-parameter search) to idenfity the model"} + ) + + model_id: int = field( + default=-1, + metadata={"help": "Model ID (contains template information) to identify the model"} + ) + + save_logit: bool = field( + default=False, + metadata={"help": "Save test file logit with name $TASK-$MODEL_ID-$ARRAY_ID.npy"} + ) + + save_logit_dir: str = field( + default=None, + metadata={"help": "Where to save the prediction result"} + ) + + # Regularization + fix_layers: int = field( + default=0, + metadata={"help": "Fix bottom-n layers when optimizing"} + ) + + # Training + save_at_last: bool = field( + default=False, + metadata={"help": "Instead of saving the best (dev performance) checkpoint, save the last checkpoint"} + ) + + # Turn off train/test + no_train: bool = field( + default=False, + metadata={"help": "No training"} + ) + no_predict: bool = field( + default=False, + metadata={"help": "No test"} + ) + optimizer: str = field( + default='adam', + metadata={'help': 'choose sgd or adam. default is adam'} + ) + optimizer_variant: str = field( + default='', + metadata={'help': 'define variants on optimizer: signgd'} + ) + + trainer: str = field( + default="standard", + metadata={"help": "Pick from {standard, kernel, linearhead}"} + ) + from_linearhead: bool = field( + default=False, + metadata={"help": "Whether to initialize head with the linearhead solution. Works for both normal and kernel trainer."} + ) + lp_early_stopping: bool = field( + default=False, + metadata={"help": "When on, increases the tolerance and lowers max_iter in scikit LogisticRegression solver to encourage early stopping."} + ) + random_model_init: bool = field( + default=False, + metadata={'help': 'reinit the model randomly'} + ) + sweep: bool = field( + default=False, + metadata={'help': 'configures the output directories to be informative when running W&B sweep'} + ) + kernel_formula: str = field( + default='sgd', + metadata={"help": "choose kernel formula from {sgd, signgd, asymmetric_signgd}"} + ) + kernel_solver: str = field( + default="logistic", + metadata={"help": "choose kernel solver from {lstsq, logistic, svr, svc, asym (only for asymmetric_signgd)}"} + ) + load_kernels: str = field( + default=None, + metadata={'help': 'when specified, loads the kernels from the folder given here'} + ) + overwrite_kernels: bool = field( + default=False, + metadata={'help': 'when specified, overwrites the kernels in the output_dir and computes them from scratch'} + ) + + exclude_embeddings: bool = field( + default=False, + metadata={"help": "Don't use embeddings for kernel computation "} + ) + exclude_head: bool = field( + default=False, + metadata={"help": "Don't use head for kernel computation "} + ) + only_biases: bool = field( + default=False, + metadata={"help": "Only use bias parameters for kernel computation for BitFit-style kernel"} + ) + exclude_first_layers: int = field( + default=-1, + metadata={'help': 'excludes the first N layers from kernel computation'} + ) + sync_embedding_layers: bool = field( + default=False, + metadata={'help': 'sync the input embedding to match output embedding (use with --exclude_first_layers)'} + ) + + kernel_regularization: float = field( + default=0.0, + metadata={"help": "Regularization constant for kernel"} + ) + kernel_gamma: float = field( + default=1.0, + metadata={"help": "Gamma for asymmetric kernel solver"} + ) + binary_classification: bool = field( + default=False, + metadata={"help": "If num_classes=2, convert two softmax logits to single sigmoid logit"} + ) + adjust_for_init: bool = field( + default=False, + metadata={'help': 'when on, trains kernel on y-f0 and adds f0 at test time'} + ) + f0_scaling: float = field( + default=1.0, + metadata={'help': 'adjust label scaling, might help with --adjust_for_init perf'} + ) + zero_order_optim: bool = field( + default=False, + metadata={'help': 'when on, trains the model by zero-order optimization'} + ) + zero_order_eps: float = field( + default=1e-3, + metadata={'help': 'eps for zero order optim'} + ) + prob_as_feature: bool = field( + default=False, + metadata={'help': 'in linear head, use log prob as feature'} + ) + zero_order_use_trainer_optim: bool = field( + default=False, + metadata={"help": "Use trainer optimizer for zero order optimization"} + ) + efficient_zero_order: bool = field( + default=False, + metadata={"help": "Efficient zero-order: resample noise vectors instead of saving them. enable different model loading using --hf_inference_model"} + ) + hf_inference_model: bool = field( + default=False, + metadata={"help": "loads the HF model in inference mode across many GPUs. incompatible with --zero_order_use_trainer_optim."} + ) + efficient_zero_order_fp16: bool = field( + default=False, + metadata={"help": "Use fp16 for efficient zero order"} + ) + zero_order_sample_scheduler: str = field( + default=None, + metadata={"help": "Have a sample scheduler. None, 'linear', 'power', or 'constant."} + ) + scale_lr_with_samples: bool = field( + default=False, + metadata={"help": "Scales the LR proportionally to the number of z samples. --learning_rate will be the LR for one z sample."} + ) + zero_order_sample: int = field( + default=1, + metadata={"help": "Sample times for zero-order estimate. If scheduler is 'linear', this number is the max sample number."} + ) + zero_order_clip_grad: bool = field( + default=False, + metadata={"help": "Clip the norm of the gradient for zero order (only when using trainer optimizer)"} + ) + + # MeZO variants + zo_by_layer: bool = field( + default=False, + metadata={"help": "For ZO: estimate the gradients on each layer individually, scales number of forward passes per grad step by a factor of L"} + ) + zo_variant: str = field( + default=None, + metadata={"help": "Choose the MeZO variant: grad_norm or param_norm (see documentation)"} + ) + use_zo_grad_est: bool = field( + default=False, + metadata={"help": "Use zero-order estimate of the gradient for zo variants"} + ) + recompute_norms: bool = field( + default=False, + metadata={'help': 'Recompute the grad or parameter norm (whichever was specified as --zo_variant) at the start of each epoch.'} + ) + scale_norm_by_num_params: bool = field( + default=False, + metadata={'help': 'Scale grad or param norm by 1 / sqrt(num params)'} + ) + norm_running_update: bool = field( + default=False, + metadata={"help": "When performing --zo_by_layer and using --zo_variant 'grad_norm', update the layer grad norms as they are recomputed at each step"} + ) + change_grad_estimate: bool = field( + default=False, + metadata={"help": "Changes the expectation of the ZO gradient estimate according to zo_variant, instead of just modifying the variance"} + ) + + # prefix tuning hyperparameters + prefix_tuning: bool = field( + default=False, + metadata={"help": "Prefix tuning"} + ) + num_prefix: int = field( + default=10, + metadata={"help": "How many prefix tokens to use"} + ) + no_reparam: bool = field( + default=False, + metadata={"help": "No reparameterization trick"} + ) + prefix_init_by_real_act: bool = field( + default=False, + metadata={"help": "For no_reparam case, randomly sample words and take their actual key/value pairs as initialization"} + ) + layer_wise_optim: bool = field( + default=False, + metadata={'help': 'Optimize layer-by-layer (only for prefix + ZO)'} + ) + + max_zo_forward_steps: int = field( + default=0, + metadata={'help': 'Stop at this number of ZO forward steps. The trainer will take whichever is reached first, max_steps or max_zo_forward_steps.'} + ) + + untie_emb: bool = field( + default=False, + metadata={"help": "Untie embeddings from lm head. Only work for OPT!!"} + ) + tie_emb: bool = field( + default=False, + metadata={"help": "Tie embeddings from lm head. Only work for RoBERTa!!"} + ) + + optimize_acc: bool = field( + default=False, + metadata={"help": "Maximize accuracy instead of minimizing loss"} + ) + + + ## hessian trainer args + num_hvp_vecs: int = field( + default=128, + metadata={"help": "Number of vectors to use to estimate HVPs"} + ) + mc_tol: float = field( + default=0.1, + metadata={"help": "Tolerance (on std dev) after which MC estimate is deemed converged"} + ) + + head_tuning: bool = field( + default=False, + metadata={"help": "Tune the head only"} + ) + + +@dataclass +class MyDataCollatorWithPadding: + """ + Implements padding for LM-BFF inputs. + Args: + tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]): + The tokenizer used for encoding the data. + padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`): + Select a strategy to pad the returned sequences (according to the model's padding side and padding index) + among: + - `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single + sequence is provided). + - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum + acceptable input length for the model if that argument is not provided. + - `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths). + max_length (`int`, *optional*): + Maximum length of the returned list and optionally padding length (see above). + pad_to_multiple_of (`int`, *optional*): + If set will pad the sequence to a multiple of the provided value. + This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >= + 7.5 (Volta). + return_tensors (`str`): + The type of Tensor to return. Allowable values are "np", "pt" and "tf". + """ + + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + return_tensors: str = "pt" + + def __call__(self, features): + mask_pos = [] + standard_features = [] + if features[0].sfc_input_ids is not None: + sfc_batch = self.__call__([OurInputFeatures(input_ids=x.sfc_input_ids, attention_mask=x.sfc_attention_mask, mask_pos=x.sfc_mask_pos) for x in features]) + + for item in features: + standard_item = {} + for field in ["input_ids", "label", "attention_mask", "token_type_ids"]: + if getattr(item, field) is not None: + standard_item[field] = getattr(item, field) + standard_features.append(standard_item) + mask_pos.append(item.mask_pos) + + batch = self.tokenizer.pad( + standard_features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors=self.return_tensors, + ) + + if any(mask_pos): + batch["mask_pos"] = torch.tensor(mask_pos) + + if "label" in batch: + batch["labels"] = batch["label"] + del batch["label"] + if "label_ids" in batch: + batch["labels"] = batch["label_ids"] + del batch["label_ids"] + + if features[0].sfc_input_ids is not None: + batch["sfc_input_ids"] = sfc_batch["input_ids"] + batch["sfc_attention_mask"] = sfc_batch["attention_mask"] + batch["sfc_mask_pos"] = sfc_batch["mask_pos"] + return batch + + +def main(): + parser = HfArgumentParser((ModelArguments, DynamicDataTrainingArguments, DynamicTrainingArguments)) + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + # If we pass only one argument to the script and it's the path to a json file, + # let's parse it to get our arguments. + model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + if training_args.sweep: + now = datetime.now() + dt_str = now.strftime('%m_%d_%H_%M_%S') + training_args.output_dir = os.path.join(training_args.output_dir, dt_str) + + #if model_args.apply_lora: + # assert 'roberta' in model_args.model_name_or_path, 'LoRA only implemented for RoBERTa models' + + if training_args.kernel_formula == 'asymmetric_signgd': + assert training_args.binary_classification, 'asymmetric solver not implemented for multi-class setting, use --binary_classification' + + if training_args.optimizer_variant != '': + assert training_args.optimizer == 'sgd', 'variants on optimizer are only implemented for SGD' + + if 'prompt' in model_args.few_shot_type: + data_args.prompt = True + + + if training_args.no_train: + training_args.do_train = False + if training_args.no_predict: + training_args.do_predict = False + + # Setup logging + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, + ) + + # Load prompt/template/mapping file + if data_args.prompt: + if data_args.prompt_path is not None: + assert data_args.prompt_id is not None + prompt_list = [] + with open(data_args.prompt_path) as f: + for line in f: + line = line.strip() + template, mapping = line.split('\t') + prompt_list.append((template, mapping)) + + data_args.template, data_args.mapping = prompt_list[data_args.prompt_id] + logger.info("Specify load the %d-th prompt: %s | %s" % (data_args.prompt_id, data_args.template, data_args.mapping)) + else: + if data_args.template_path is not None: + with open(data_args.template_path) as f: + data_args.template_list = [] + for line in f: + line = line.strip() + if len(line) > 0: + data_args.template_list.append(line) + + # Load top-n templates + if data_args.top_n_template is not None: + data_args.template_list = data_args.template_list[:data_args.top_n_template] + logger.info("Load top-%d templates from %s" % (len(data_args.template_list), data_args.template_path)) + + # ... or load i-th template + if data_args.template_id is not None: + data_args.template = data_args.template_list[data_args.template_id] + data_args.template_list = None + logger.info("Specify load the %d-th template: %s" % (data_args.template_id, data_args.template)) + + if data_args.mapping_path is not None: + assert data_args.mapping_id is not None # Only can use one label word mapping + with open(data_args.mapping_path) as f: + mapping_list = [] + for line in f: + line = line.strip() + mapping_list.append(line) + + data_args.mapping = mapping_list[data_args.mapping_id] + logger.info("Specify using the %d-th mapping: %s" % (data_args.mapping_id, data_args.mapping)) + + # Check save path + if ( + os.path.exists(training_args.output_dir) + and os.listdir(training_args.output_dir) + and training_args.do_train + and not training_args.overwrite_output_dir + ): + raise ValueError(f"Output directory ({training_args.output_dir}) already exists.") + + logger.warning( + "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", + training_args.local_rank, + training_args.device, + training_args.n_gpu, + bool(training_args.local_rank != -1), + training_args.fp16, + ) + logger.info("Training/evaluation parameters %s", training_args) + + # Set seed + set_seed(training_args.seed) + + try: + num_labels = num_labels_mapping[data_args.task_name] + output_mode = output_modes_mapping[data_args.task_name] + logger.info("Task name: {}, number of labels: {}, output mode: {}".format(data_args.task_name, num_labels, output_mode)) + except KeyError: + raise ValueError("Task not found: %s" % (data_args.task_name)) + + # Automatically generate template for using demonstrations + if data_args.auto_demo and model_args.few_shot_type == 'prompt-demo': + # GPT-3's in-context learning + if data_args.gpt3_in_context_head or data_args.gpt3_in_context_tail: + logger.info("Automatically convert the template to GPT-3's in-context learning.") + assert data_args.template_list is None + + old_template = data_args.template + new_template = old_template + '' + new_sfc_template = data_args.sfc_prompt + '' + old_template = old_template.replace('*cls*', '') + old_template = old_template.replace('*bos*', '') + if data_args.gpt3_in_context_head: + new_template = new_template.replace('*cls*', '') + new_template = new_template.replace('*bos*', '') + + # Single sentence or sentence pair? + sent_num = 1 + if "_1" in old_template: + sent_num = 2 + for instance_id in range(data_args.gpt3_in_context_num): + sub_template = old_template + '' + # Replace sent_id + for sent_id in range(sent_num): + sub_template = sub_template.replace("_{}*".format(sent_id), "_{}*".format(sent_num + sent_num * instance_id + sent_id)) + # Replace mask + if "opt" in model_args.model_name_or_path or "gpt" in model_args.model_name_or_path: + sub_template = sub_template + "*labelx_{}*".format(instance_id) + else: + sub_template = sub_template.replace("*mask*", "*labelx_{}*".format(instance_id)) + if data_args.gpt3_in_context_tail: + new_template = new_template + data_args.gpt3_demo_separator + sub_template # Put context at the end + new_sfc_template = new_sfc_template + data_args.gpt3_demo_separator + sub_template + else: + new_template = sub_template + data_args.gpt3_demo_separator + new_template # Put context at the beginning + new_sfc_template = sub_template + data_args.gpt3_demo_separator + new_sfc_template + if data_args.gpt3_in_context_head: + new_template = "*bos*" + new_template + new_sfc_template = "*bos*" + new_sfc_template + logger.info("| {} => {}".format(data_args.template, new_template)) + logger.info("New SFC template (in-context learning): {}".format(new_sfc_template)) + data_args.template = new_template + if model_args.icl_sfc: + data_args.icl_sfc_prompt = new_sfc_template + else: + logger.info("Automatically convert the template to using demonstrations.") + if data_args.template_list is not None: + for i in range(len(data_args.template_list)): + old_template = data_args.template_list[i] + new_template = old_template + '' + old_template = old_template.replace('*cls*', '') + # Single sentence or sentence pair? + sent_num = 1 + if "_1" in old_template: + sent_num = 2 + for label_id in range(num_labels): + sub_template = old_template + '' + # Replace sent id + for sent_id in range(sent_num): + sub_template = sub_template.replace("_{}*".format(sent_id), "_{}*".format(sent_num + sent_num * label_id + sent_id)) + # Replace mask + sub_template = sub_template.replace("*mask*", "*label_{}*".format(label_id)) + new_template = new_template + sub_template + logger.info("| {} => {}".format(data_args.template_list[i], new_template)) + data_args.template_list[i] = new_template + else: + old_template = data_args.template + new_template = old_template + '' + old_template = old_template.replace('*cls*', '') + # Single sentence or sentence pair? + sent_num = 1 + if "_1" in old_template: + sent_num = 2 + for label_id in range(num_labels): + sub_template = old_template + '' + # Replace sent id + for sent_id in range(sent_num): + sub_template = sub_template.replace("_{}".format(sent_id), "_{}".format(sent_num + sent_num * label_id + sent_id)) + # Replace mask + sub_template = sub_template.replace("*mask*", "*label_{}*".format(label_id)) + new_template = new_template + sub_template + logger.info("| {} => {}".format(data_args.template, new_template)) + data_args.template = new_template + + # Create config + config_kwargs = {'apply_lora': model_args.apply_lora, + 'lora_alpha': model_args.lora_alpha, + 'lora_r': model_args.lora_r} + if model_args.apply_lora: + if 'roberta' in model_args.model_name_or_path: + config = RobertaConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir, + **config_kwargs) + else: + config = OPTConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir, + **config_kwargs + ) + else: + config = AutoConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir + ) + + if training_args.untie_emb: + logger.warn("Untie embeddings and lm head") + logger.warn("NOTE that this only works for OPT. By default RoBERTa model embeddings are already untied.") + config.tie_word_embeddings = False + + if 'prompt' in model_args.few_shot_type: + model_fn = MODEL_TYPES[config.model_type] + elif model_args.few_shot_type == 'finetune': + if training_args.from_linearhead: + model_fn = MODEL_TYPES[config.model_type] + else: + model_fn = AutoModelForSequenceClassification + else: + raise NotImplementedError + special_tokens = [] + + # Create tokenizer + tokenizer = AutoTokenizer.from_pretrained( + model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, + additional_special_tokens=special_tokens, + cache_dir=model_args.cache_dir, + ) + if "opt" in model_args.model_name_or_path: + # Set SEP token + tokenizer.sep_token_id = tokenizer.eos_token_id + tokenizer.bos_token_id = 0 + if "gpt2" in model_args.model_name_or_path: + tokenizer.sep_token_id = tokenizer.eos_token_id + tokenizer.pad_token_id = tokenizer.eos_token_id + + + if training_args.hf_inference_model: + free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) + max_memory = f'{free_in_GB-5}GB' + n_gpus = torch.cuda.device_count() + max_memory = {i: max_memory for i in range(n_gpus)} + + model = model_fn.from_pretrained( + model_args.model_name_or_path, + config=config, + device_map='auto', + torch_dtype=torch.float16 if training_args.efficient_zero_order_fp16 else torch.float32, + max_memory=max_memory, + ) + else: + model = model_fn.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + ) + + if training_args.tie_emb: + logger.warn("Tie embeddings. Only work for RoBERTa (in our code by default they are not tied)") + model.tie_emb() + + if training_args.head_tuning: + if model.config.model_type == "roberta": + head_name = "lm_head" + + for n, p in model.named_parameters(): + if head_name not in n: + p.requires_grad = False + else: + logger.info(f"Only tuning {n}") + + tokenizer.model_type = model.config.model_type + + if training_args.exclude_first_layers != -1: + model = convert_opt_model(model, config, training_args.exclude_first_layers) + + if training_args.prefix_tuning: + from src.prefix import PrefixTuning + PrefixTuning(model, num_prefix=training_args.num_prefix, reparam=not training_args.no_reparam, float16=training_args.efficient_zero_order_fp16, init_by_real_act=training_args.prefix_init_by_real_act) + + # Get our special datasets. + train_dataset = ( + FewShotDataset(data_args, tokenizer=tokenizer, mode="train", use_demo=("demo" in model_args.few_shot_type)) + if training_args.do_train + else None + ) + eval_dataset = ( + FewShotDataset(data_args, tokenizer=tokenizer, mode="dev", use_demo=("demo" in model_args.few_shot_type)) + if training_args.do_eval + else None + ) + test_dataset = ( + FewShotDataset(data_args, tokenizer=tokenizer, mode="test", use_demo=("demo" in model_args.few_shot_type)) + if training_args.do_predict + else None + ) + + set_seed(training_args.seed) + + if training_args.random_model_init: + model.init_weights() # reinit weights to random + + # For BERT, increase the size of the segment (token type) embeddings + if config.model_type == 'bert': + model.resize_token_embeddings(len(tokenizer)) + resize_token_type_embeddings(model, new_num_types=10, random_segment=model_args.random_segment) + + # Pass dataset and argument information to the model + if eval_dataset.label_word_list is not None: + model.label_word_list = torch.tensor(eval_dataset.label_word_list).long().to(training_args.device) + if output_modes_mapping[data_args.task_name] == 'regression': + # lower / upper bounds + model.lb, model.ub = bound_mapping[data_args.task_name] + model.model_args = model_args + model.data_args = data_args + model.tokenizer = tokenizer + + if model_args.apply_lora: + for name, param in model.named_parameters(): + if (name.startswith('roberta') and "lora" not in name) or (name.startswith('opt') and "lora" not in name): + param.requires_grad_(False) + + # Build metric + def build_compute_metrics_fn(task_name: str) -> Callable[[EvalPrediction], Dict]: + def compute_metrics_fn(p: EvalPrediction): + # Note: the eval dataloader is sequential, so the examples are in order. + # We average the logits over each sample for using demonstrations. + predictions = p.predictions + num_logits = predictions.shape[-1] + + num_sample = test_dataset.num_sample if eval_dataset is None else eval_dataset.num_sample + logits = predictions.reshape([num_sample, -1, num_logits]) + logits = logits.mean(axis=0) + + if num_logits == 1: + preds = np.squeeze(logits) + else: + preds = np.argmax(logits, axis=1) + + # Just for sanity, assert label ids are the same. + label_ids = p.label_ids.reshape([num_sample, -1]) + label_ids_avg = label_ids.mean(axis=0) + label_ids_avg = label_ids_avg.astype(p.label_ids.dtype) + assert (label_ids_avg - label_ids[0]).mean() < 1e-2 + label_ids = label_ids[0] + + return compute_metrics_mapping[task_name](task_name, preds, label_ids) + + return compute_metrics_fn + + # Initialize our Trainer + trainer_classes = { + "standard": LowRankTrainer, + "linearhead": LinearHeadTrainer, + "Lowrank": LowRankTrainer + } + trainer_class = trainer_classes[training_args.trainer] + trainer_kwargs = {} + trainer = trainer_class( + model=model, + args=training_args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + compute_metrics=build_compute_metrics_fn(data_args.task_name), + data_collator=MyDataCollatorWithPadding(tokenizer), + **trainer_kwargs + ) + + # Calibration + if model_args.sfc: + inputs = tokenizer([data_args.sfc_prompt.replace("_", " ")], return_tensors="pt") + logger.info(f"Calibrating SFC with prompt: {data_args.sfc_prompt}") + logger.info("Inputs: {}".format(inputs.input_ids)) + inputs = inputs.to(model.device) + with torch.no_grad(): + model.eval() + logits = model(**inputs)[0] + model.sfc_bias = F.log_softmax(logits.squeeze(0).detach()) + logger.info("SFC bias: {}".format(model.sfc_bias)) + + + # Training + if training_args.do_train: + train_result = trainer.train(model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None) + + if training_args.trainer == "hessian": + # Write the result to log + with FileLock('log_hessian.lock'): + with open('log_hessian', 'a') as f: + train_result.update(vars(model_args)) + train_result.update(vars(training_args)) + train_result.update(vars(data_args)) + if 'evaluation_strategy' in train_result: + train_result.pop('evaluation_strategy') + f.write(str(train_result) + '\n') + exit() + + # Use the early stop, so do not save the model in the end (unless specify save_at_last) + + if training_args.trainer == "standard" or training_args.trainer == "linearhead": + if training_args.save_at_last: + trainer.save_model(training_args.output_dir) + + if trainer.is_world_process_zero(): + tokenizer.save_pretrained(training_args.output_dir) + torch.save(model_args, os.path.join(training_args.output_dir, "model_args.bin")) + torch.save(data_args, os.path.join(training_args.output_dir, "data_args.bin")) + + if training_args.evaluate_during_training: + # Reload the best checkpoint (for eval) + # model.load_state_dict(trainer.best_model_ckpt) + # if training_args.prefix_tuning: + # # We can load prefix by directly using load_state_dict + # model.load_state_dict(torch.load(os.path.join(training_args.output_dir, "pytorch_model.bin"))) + # else: + # model = model_fn.from_pretrained(training_args.output_dir) + # if training_args.exclude_first_layers != -1: + # model = convert_opt_model(model, config, training_args.exclude_first_layers) + + # model = model.to(training_args.device) + + # Now we just reload this from memory instead of disk <-- much faster + trainer.model.load_state_dict(trainer.best_model_ckpt) + + # Evaluation + final_result = { + 'time': str(datetime.today()), + 'output_dir': training_args.output_dir + } + + eval_results = {} + if training_args.do_eval: + logger.info("*** Validate ***") + + eval_datasets = [eval_dataset] + + for eval_dataset in eval_datasets: + trainer.compute_metrics = build_compute_metrics_fn(eval_dataset.args.task_name) + output = trainer.evaluate(eval_dataset=eval_dataset) + eval_result = output.metrics + + output_eval_file = os.path.join( + training_args.output_dir, f"eval_results_{eval_dataset.args.task_name}.txt" + ) + if trainer.is_world_process_zero(): + with open(output_eval_file, "w") as writer: + logger.info("***** Eval results {} *****".format(eval_dataset.args.task_name)) + for key, value in eval_result.items(): + logger.info(" %s = %s", key, value) + writer.write("%s = %s\n" % (key, value)) + final_result[eval_dataset.args.task_name + '_dev_' + key] = value + eval_results.update(eval_result) + + test_results = {} + if training_args.do_predict: + logging.info("*** Test ***") + test_datasets = [test_dataset] + ### Don't evaluate on mnli-mm for our purposes + # if data_args.task_name == "mnli": + # mnli_mm_data_args = dataclasses.replace(data_args, task_name="mnli-mm") + # test_datasets.append( + # FewShotDataset(mnli_mm_data_args, tokenizer=tokenizer, mode="test", use_demo=('demo' in model_args.few_shot_type)) + # ) + + for test_dataset in test_datasets: + trainer.compute_metrics = build_compute_metrics_fn(test_dataset.args.task_name) + output = trainer.evaluate(eval_dataset=test_dataset) + test_result = output.metrics + + output_test_file = os.path.join( + training_args.output_dir, f"test_results_{test_dataset.args.task_name}.txt" + ) + if trainer.is_world_process_zero(): + with open(output_test_file, "w") as writer: + logger.info("***** Test results {} *****".format(test_dataset.args.task_name)) + for key, value in test_result.items(): + logger.info(" %s = %s", key, value) + writer.write("%s = %s\n" % (key, value)) + final_result[test_dataset.args.task_name + '_test_' + key] = value + + if training_args.save_logit: + predictions = output.predictions + num_logits = predictions.shape[-1] + logits = predictions.reshape([test_dataset.num_sample, -1, num_logits]).mean(axis=0) + np.save(os.path.join(training_args.save_logit_dir, "{}-{}-{}.npy".format(test_dataset.task_name, training_args.model_id, training_args.array_id)), logits) + + test_results.update(test_result) + + + if trainer.is_world_process_zero(): + with FileLock('log.lock'): + with open(training_args.log_file, 'a') as f: + final_result.update(vars(model_args)) + final_result.update(vars(training_args)) + final_result.update(vars(data_args)) + if 'evaluation_strategy' in final_result: + final_result.pop('evaluation_strategy') + f.write(str(final_result) + '\n') + + logger.info('****** Output Dir *******') + logger.info(training_args.output_dir) + + return eval_results + +if __name__ == "__main__": + main() diff --git a/baselines/lozo/medium_models/run_mezo.py b/baselines/lozo/medium_models/run_mezo.py new file mode 100644 index 0000000..c7afccd --- /dev/null +++ b/baselines/lozo/medium_models/run_mezo.py @@ -0,0 +1,1126 @@ +"""Finetuning the library models for sequence classification on GLUE.""" + +import dataclasses +import logging +import os +import sys +from dataclasses import dataclass, field +from typing import Callable, Dict, Optional, Union, List +import torch +import torch.nn.functional as F + +import numpy as np + +from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, EvalPrediction, PreTrainedTokenizerBase +from src.modeling_roberta import RobertaConfig +from src.modeling_opt import OPTConfig +from transformers import GlueDataTrainingArguments as DataTrainingArguments +from transformers import HfArgumentParser, TrainingArguments, set_seed + +from src.linearhead_trainer import LinearHeadTrainer +from src.dataset import FewShotDataset, OurInputFeatures +from src.models import MODEL_TYPES, resize_token_type_embeddings, convert_opt_model +from src.trainer import Trainer +from src.processors import processors_mapping, num_labels_mapping, output_modes_mapping, compute_metrics_mapping, bound_mapping + +from filelock import FileLock +from datetime import datetime + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. + """ + model_name_or_path: str = field( + metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} + ) + config_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} + ) + tokenizer_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} + ) + cache_dir: Optional[str] = field( + default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} + ) + # Few-shot type + # - finetune: standard fine-tuning + # - prompt: prompt-based fine-tuning + # - prompt-demo: prompt-based fine-tuning with demonstrations + few_shot_type: str = field( + default='prompt-demo', + metadata={"help": "Few-shot learning model type. Choice: finetune, prompt, prompt-demo"} + ) + + # Only for BERT-type model + random_segment: bool = field( + default=False, + metadata={"help": "Whether to reinitialize the token type embeddings (only for BERT)."} + ) + l2_loss: bool = field( + default=False, + metadata={"help": "Whether to use L2 loss (only makes a difference in standard FT)."} + ) + use_task_word: bool = field( + default=False, + metadata={'help': 'uses the task words MLM logit for kernel computation'} + ) + + # LoRA arguments: only for BERT-type model + apply_lora: bool = field( + default=False, + metadata={'help': 'use LoRA for finetuning'} + ) + lora_alpha: int = field( + default=None, + metadata={'help': 'initialization scale for one of the low rank matrices in lora'} + ) + lora_r: int = field( + default=None, + metadata={'help': 'inner rank for lora matrices'} + ) + + # Calibration + sfc: bool = field( + default=False, + metadata={"help": "Whether to use surface form calibration."} + ) + + icl_sfc: bool = field( + default=False, + metadata={"help": "Use in-context learning demos in sfc."} + ) + + +@dataclass +class DynamicDataTrainingArguments(DataTrainingArguments): + """ + Arguments for dynamic training. + """ + num_k: Optional[int] = field( + default=16, + metadata={"help": "Number of training instances per class"} + ) + + num_sample: Optional[int] = field( + default=16, + metadata={"help": "Number of samples (for inference) in fine-tuning with demonstrations"} + ) + + num_demo: Optional[int] = field( + default=1, + metadata={"help": "Number of demonstrations from each class"} + ) + + auto_demo: bool = field( + default=True, + metadata={"help": "Automatically generate template for using demonstrations"} + ) + + # For prompting + sfc_prompt: str = field( + default=None, + metadata={"help": "SFC prompt"} + ) + + template: str = field( + default=None, + metadata={"help": "Template"} + ) + + mapping: str = field( + default=None, + metadata={"help": "Label word mapping"} + ) + + template_path: str = field( + default=None, + metadata={"help": "Path to a txt file that stores all the templates, one per line. Do not set this when prompt_path is used"} + ) + + mapping_path: str = field( + default=None, + metadata={"help": "Path to a txt file that stores all the label word mappings, one per line. Do not set this when prompt_path is used"} + ) + + prompt_path: str = field( + default=None, + metadata={"help": "Path to a txt file that stores all the prompts (templates and mappings), one per line"} + ) + + template_id: int = field( + default=None, + metadata={"help": "Template id if using template_path"} + ) + + mapping_id: int = field( + default=None, + metadata={"help": "Mapping id if using template_path"} + ) + + prompt_id: int = field( + default=None, + metadata={"help": "Prompt id if using prompt_path"} + ) + + top_n_template: int = field( + default=None, + metadata={"help": "Use top-n template in the template path"} + ) + + # For logging + tag: str = field( + default='', + metadata={"help": "Set the tag and find the result easier in the log."} + ) + + # For filtering when using demonstrations + demo_filter: bool = field( + default=False, + metadata={"help": "Only use similar instances in demonstrations"} + ) + + demo_filter_rate: float = field( + default=0.5, + metadata={"help": "Only use top-x\% similar instances in demonstrations"} + ) + + demo_filter_model: str = field( + default=None, + metadata={"help": "Model name for demonstration filter embeddings. Will load embeddings based on the model name."} + ) + + debug_mode: bool = field( + default=False, + metadata={"help": "Debug mode"} + ) + + # For max length + double_demo: bool = field( + default=False, + metadata={"help": "Use double length for using demonstrations"} + ) + + first_sent_limit: int = field( + default=None, + metadata={"help": "Limit the length of the first sentence (i.e., sent_0)"} + ) + + other_sent_limit: int = field( + default=None, + metadata={"help": "Limit the length of sentences other than the first sentence"} + ) + + use_full_length: bool = field( + default=None, + metadata={"help": "Use the full length (512)"} + ) + + # GPT-3's in-context learning + gpt3_in_context_head: bool = field( + default=False, + metadata={"help": "GPT-3's in-context learning (context at the beginning)"} + ) + + gpt3_in_context_tail: bool = field( + default=False, + metadata={"help": "GPT-3's in-context learning (context at the end)"} + ) + + gpt3_in_context_num: int = field( + default=32, + metadata={"help": "Number of context examples"} + ) + + gpt3_demo_separator: str = field( + default="\n\n\n", + metadata={"help": "Separator between demonstrations"} + ) + + truncate_head: bool = field( + default=False, + metadata={"help": "When exceeding the maximum length, truncate the head instead of the tail."} + ) + + # Do not set up the following fields. They are set up automatically. + prompt: bool = field( + default=False, + metadata={"help": "Whether to use prompt-based fine-tuning"} + ) + template_list: List[str] = field( + default=None, + metadata={"help": "(DO NOT List of templates (only initialized after the program starts."}, + + ) + + +@dataclass +class DynamicTrainingArguments(TrainingArguments): + evaluate_during_training: bool = field( + default=False, + metadata={"help": "Whether to run evaluation during training or at the."} + ) + log_file: str = field( + default='log' + ) + + # For ensemble + array_id: int = field( + default=-1, + metadata={"help": "Array ID (contains seed and hyper-parameter search) to idenfity the model"} + ) + + model_id: int = field( + default=-1, + metadata={"help": "Model ID (contains template information) to identify the model"} + ) + + save_logit: bool = field( + default=False, + metadata={"help": "Save test file logit with name $TASK-$MODEL_ID-$ARRAY_ID.npy"} + ) + + save_logit_dir: str = field( + default=None, + metadata={"help": "Where to save the prediction result"} + ) + + # Regularization + fix_layers: int = field( + default=0, + metadata={"help": "Fix bottom-n layers when optimizing"} + ) + + # Training + save_at_last: bool = field( + default=False, + metadata={"help": "Instead of saving the best (dev performance) checkpoint, save the last checkpoint"} + ) + + # Turn off train/test + no_train: bool = field( + default=False, + metadata={"help": "No training"} + ) + no_predict: bool = field( + default=False, + metadata={"help": "No test"} + ) + optimizer: str = field( + default='adam', + metadata={'help': 'choose sgd or adam. default is adam'} + ) + optimizer_variant: str = field( + default='', + metadata={'help': 'define variants on optimizer: signgd'} + ) + + trainer: str = field( + default="standard", + metadata={"help": "Pick from {standard, kernel, linearhead}"} + ) + from_linearhead: bool = field( + default=False, + metadata={"help": "Whether to initialize head with the linearhead solution. Works for both normal and kernel trainer."} + ) + lp_early_stopping: bool = field( + default=False, + metadata={"help": "When on, increases the tolerance and lowers max_iter in scikit LogisticRegression solver to encourage early stopping."} + ) + random_model_init: bool = field( + default=False, + metadata={'help': 'reinit the model randomly'} + ) + sweep: bool = field( + default=False, + metadata={'help': 'configures the output directories to be informative when running W&B sweep'} + ) + kernel_formula: str = field( + default='sgd', + metadata={"help": "choose kernel formula from {sgd, signgd, asymmetric_signgd}"} + ) + kernel_solver: str = field( + default="logistic", + metadata={"help": "choose kernel solver from {lstsq, logistic, svr, svc, asym (only for asymmetric_signgd)}"} + ) + load_kernels: str = field( + default=None, + metadata={'help': 'when specified, loads the kernels from the folder given here'} + ) + overwrite_kernels: bool = field( + default=False, + metadata={'help': 'when specified, overwrites the kernels in the output_dir and computes them from scratch'} + ) + + exclude_embeddings: bool = field( + default=False, + metadata={"help": "Don't use embeddings for kernel computation "} + ) + exclude_head: bool = field( + default=False, + metadata={"help": "Don't use head for kernel computation "} + ) + only_biases: bool = field( + default=False, + metadata={"help": "Only use bias parameters for kernel computation for BitFit-style kernel"} + ) + exclude_first_layers: int = field( + default=-1, + metadata={'help': 'excludes the first N layers from kernel computation'} + ) + sync_embedding_layers: bool = field( + default=False, + metadata={'help': 'sync the input embedding to match output embedding (use with --exclude_first_layers)'} + ) + + kernel_regularization: float = field( + default=0.0, + metadata={"help": "Regularization constant for kernel"} + ) + kernel_gamma: float = field( + default=1.0, + metadata={"help": "Gamma for asymmetric kernel solver"} + ) + binary_classification: bool = field( + default=False, + metadata={"help": "If num_classes=2, convert two softmax logits to single sigmoid logit"} + ) + adjust_for_init: bool = field( + default=False, + metadata={'help': 'when on, trains kernel on y-f0 and adds f0 at test time'} + ) + f0_scaling: float = field( + default=1.0, + metadata={'help': 'adjust label scaling, might help with --adjust_for_init perf'} + ) + zero_order_optim: bool = field( + default=False, + metadata={'help': 'when on, trains the model by zero-order optimization'} + ) + zero_order_eps: float = field( + default=1e-3, + metadata={'help': 'eps for zero order optim'} + ) + prob_as_feature: bool = field( + default=False, + metadata={'help': 'in linear head, use log prob as feature'} + ) + zero_order_use_trainer_optim: bool = field( + default=False, + metadata={"help": "Use trainer optimizer for zero order optimization"} + ) + efficient_zero_order: bool = field( + default=False, + metadata={"help": "Efficient zero-order: resample noise vectors instead of saving them. enable different model loading using --hf_inference_model"} + ) + hf_inference_model: bool = field( + default=False, + metadata={"help": "loads the HF model in inference mode across many GPUs. incompatible with --zero_order_use_trainer_optim."} + ) + efficient_zero_order_fp16: bool = field( + default=False, + metadata={"help": "Use fp16 for efficient zero order"} + ) + zero_order_sample_scheduler: str = field( + default=None, + metadata={"help": "Have a sample scheduler. None, 'linear', 'power', or 'constant."} + ) + scale_lr_with_samples: bool = field( + default=False, + metadata={"help": "Scales the LR proportionally to the number of z samples. --learning_rate will be the LR for one z sample."} + ) + zero_order_sample: int = field( + default=1, + metadata={"help": "Sample times for zero-order estimate. If scheduler is 'linear', this number is the max sample number."} + ) + zero_order_clip_grad: bool = field( + default=False, + metadata={"help": "Clip the norm of the gradient for zero order (only when using trainer optimizer)"} + ) + + # MeZO variants + zo_by_layer: bool = field( + default=False, + metadata={"help": "For ZO: estimate the gradients on each layer individually, scales number of forward passes per grad step by a factor of L"} + ) + zo_variant: str = field( + default=None, + metadata={"help": "Choose the MeZO variant: grad_norm or param_norm (see documentation)"} + ) + use_zo_grad_est: bool = field( + default=False, + metadata={"help": "Use zero-order estimate of the gradient for zo variants"} + ) + recompute_norms: bool = field( + default=False, + metadata={'help': 'Recompute the grad or parameter norm (whichever was specified as --zo_variant) at the start of each epoch.'} + ) + scale_norm_by_num_params: bool = field( + default=False, + metadata={'help': 'Scale grad or param norm by 1 / sqrt(num params)'} + ) + norm_running_update: bool = field( + default=False, + metadata={"help": "When performing --zo_by_layer and using --zo_variant 'grad_norm', update the layer grad norms as they are recomputed at each step"} + ) + change_grad_estimate: bool = field( + default=False, + metadata={"help": "Changes the expectation of the ZO gradient estimate according to zo_variant, instead of just modifying the variance"} + ) + + # prefix tuning hyperparameters + prefix_tuning: bool = field( + default=False, + metadata={"help": "Prefix tuning"} + ) + num_prefix: int = field( + default=10, + metadata={"help": "How many prefix tokens to use"} + ) + no_reparam: bool = field( + default=False, + metadata={"help": "No reparameterization trick"} + ) + prefix_init_by_real_act: bool = field( + default=False, + metadata={"help": "For no_reparam case, randomly sample words and take their actual key/value pairs as initialization"} + ) + layer_wise_optim: bool = field( + default=False, + metadata={'help': 'Optimize layer-by-layer (only for prefix + ZO)'} + ) + + max_zo_forward_steps: int = field( + default=0, + metadata={'help': 'Stop at this number of ZO forward steps. The trainer will take whichever is reached first, max_steps or max_zo_forward_steps.'} + ) + + untie_emb: bool = field( + default=False, + metadata={"help": "Untie embeddings from lm head. Only work for OPT!!"} + ) + tie_emb: bool = field( + default=False, + metadata={"help": "Tie embeddings from lm head. Only work for RoBERTa!!"} + ) + + optimize_acc: bool = field( + default=False, + metadata={"help": "Maximize accuracy instead of minimizing loss"} + ) + + + ## hessian trainer args + num_hvp_vecs: int = field( + default=128, + metadata={"help": "Number of vectors to use to estimate HVPs"} + ) + mc_tol: float = field( + default=0.1, + metadata={"help": "Tolerance (on std dev) after which MC estimate is deemed converged"} + ) + + head_tuning: bool = field( + default=False, + metadata={"help": "Tune the head only"} + ) + + +@dataclass +class MyDataCollatorWithPadding: + """ + Implements padding for LM-BFF inputs. + Args: + tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]): + The tokenizer used for encoding the data. + padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`): + Select a strategy to pad the returned sequences (according to the model's padding side and padding index) + among: + - `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single + sequence is provided). + - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum + acceptable input length for the model if that argument is not provided. + - `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths). + max_length (`int`, *optional*): + Maximum length of the returned list and optionally padding length (see above). + pad_to_multiple_of (`int`, *optional*): + If set will pad the sequence to a multiple of the provided value. + This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >= + 7.5 (Volta). + return_tensors (`str`): + The type of Tensor to return. Allowable values are "np", "pt" and "tf". + """ + + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + return_tensors: str = "pt" + + def __call__(self, features): + mask_pos = [] + standard_features = [] + if features[0].sfc_input_ids is not None: + sfc_batch = self.__call__([OurInputFeatures(input_ids=x.sfc_input_ids, attention_mask=x.sfc_attention_mask, mask_pos=x.sfc_mask_pos) for x in features]) + + for item in features: + standard_item = {} + for field in ["input_ids", "label", "attention_mask", "token_type_ids"]: + if getattr(item, field) is not None: + standard_item[field] = getattr(item, field) + standard_features.append(standard_item) + mask_pos.append(item.mask_pos) + + batch = self.tokenizer.pad( + standard_features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors=self.return_tensors, + ) + + if any(mask_pos): + batch["mask_pos"] = torch.tensor(mask_pos) + + if "label" in batch: + batch["labels"] = batch["label"] + del batch["label"] + if "label_ids" in batch: + batch["labels"] = batch["label_ids"] + del batch["label_ids"] + + if features[0].sfc_input_ids is not None: + batch["sfc_input_ids"] = sfc_batch["input_ids"] + batch["sfc_attention_mask"] = sfc_batch["attention_mask"] + batch["sfc_mask_pos"] = sfc_batch["mask_pos"] + return batch + + +def main(): + parser = HfArgumentParser((ModelArguments, DynamicDataTrainingArguments, DynamicTrainingArguments)) + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + # If we pass only one argument to the script and it's the path to a json file, + # let's parse it to get our arguments. + model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + if training_args.sweep: + now = datetime.now() + dt_str = now.strftime('%m_%d_%H_%M_%S') + training_args.output_dir = os.path.join(training_args.output_dir, dt_str) + + #if model_args.apply_lora: + # assert 'roberta' in model_args.model_name_or_path, 'LoRA only implemented for RoBERTa models' + + if training_args.kernel_formula == 'asymmetric_signgd': + assert training_args.binary_classification, 'asymmetric solver not implemented for multi-class setting, use --binary_classification' + + if training_args.optimizer_variant != '': + assert training_args.optimizer == 'sgd', 'variants on optimizer are only implemented for SGD' + + if 'prompt' in model_args.few_shot_type: + data_args.prompt = True + + + if training_args.no_train: + training_args.do_train = False + if training_args.no_predict: + training_args.do_predict = False + + # Setup logging + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, + ) + + # Load prompt/template/mapping file + if data_args.prompt: + if data_args.prompt_path is not None: + assert data_args.prompt_id is not None + prompt_list = [] + with open(data_args.prompt_path) as f: + for line in f: + line = line.strip() + template, mapping = line.split('\t') + prompt_list.append((template, mapping)) + + data_args.template, data_args.mapping = prompt_list[data_args.prompt_id] + logger.info("Specify load the %d-th prompt: %s | %s" % (data_args.prompt_id, data_args.template, data_args.mapping)) + else: + if data_args.template_path is not None: + with open(data_args.template_path) as f: + data_args.template_list = [] + for line in f: + line = line.strip() + if len(line) > 0: + data_args.template_list.append(line) + + # Load top-n templates + if data_args.top_n_template is not None: + data_args.template_list = data_args.template_list[:data_args.top_n_template] + logger.info("Load top-%d templates from %s" % (len(data_args.template_list), data_args.template_path)) + + # ... or load i-th template + if data_args.template_id is not None: + data_args.template = data_args.template_list[data_args.template_id] + data_args.template_list = None + logger.info("Specify load the %d-th template: %s" % (data_args.template_id, data_args.template)) + + if data_args.mapping_path is not None: + assert data_args.mapping_id is not None # Only can use one label word mapping + with open(data_args.mapping_path) as f: + mapping_list = [] + for line in f: + line = line.strip() + mapping_list.append(line) + + data_args.mapping = mapping_list[data_args.mapping_id] + logger.info("Specify using the %d-th mapping: %s" % (data_args.mapping_id, data_args.mapping)) + + # Check save path + if ( + os.path.exists(training_args.output_dir) + and os.listdir(training_args.output_dir) + and training_args.do_train + and not training_args.overwrite_output_dir + ): + raise ValueError(f"Output directory ({training_args.output_dir}) already exists.") + + logger.warning( + "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", + training_args.local_rank, + training_args.device, + training_args.n_gpu, + bool(training_args.local_rank != -1), + training_args.fp16, + ) + logger.info("Training/evaluation parameters %s", training_args) + + # Set seed + set_seed(training_args.seed) + + try: + num_labels = num_labels_mapping[data_args.task_name] + output_mode = output_modes_mapping[data_args.task_name] + logger.info("Task name: {}, number of labels: {}, output mode: {}".format(data_args.task_name, num_labels, output_mode)) + except KeyError: + raise ValueError("Task not found: %s" % (data_args.task_name)) + + # Automatically generate template for using demonstrations + if data_args.auto_demo and model_args.few_shot_type == 'prompt-demo': + # GPT-3's in-context learning + if data_args.gpt3_in_context_head or data_args.gpt3_in_context_tail: + logger.info("Automatically convert the template to GPT-3's in-context learning.") + assert data_args.template_list is None + + old_template = data_args.template + new_template = old_template + '' + new_sfc_template = data_args.sfc_prompt + '' + old_template = old_template.replace('*cls*', '') + old_template = old_template.replace('*bos*', '') + if data_args.gpt3_in_context_head: + new_template = new_template.replace('*cls*', '') + new_template = new_template.replace('*bos*', '') + + # Single sentence or sentence pair? + sent_num = 1 + if "_1" in old_template: + sent_num = 2 + for instance_id in range(data_args.gpt3_in_context_num): + sub_template = old_template + '' + # Replace sent_id + for sent_id in range(sent_num): + sub_template = sub_template.replace("_{}*".format(sent_id), "_{}*".format(sent_num + sent_num * instance_id + sent_id)) + # Replace mask + if "opt" in model_args.model_name_or_path or "gpt" in model_args.model_name_or_path: + sub_template = sub_template + "*labelx_{}*".format(instance_id) + else: + sub_template = sub_template.replace("*mask*", "*labelx_{}*".format(instance_id)) + if data_args.gpt3_in_context_tail: + new_template = new_template + data_args.gpt3_demo_separator + sub_template # Put context at the end + new_sfc_template = new_sfc_template + data_args.gpt3_demo_separator + sub_template + else: + new_template = sub_template + data_args.gpt3_demo_separator + new_template # Put context at the beginning + new_sfc_template = sub_template + data_args.gpt3_demo_separator + new_sfc_template + if data_args.gpt3_in_context_head: + new_template = "*bos*" + new_template + new_sfc_template = "*bos*" + new_sfc_template + logger.info("| {} => {}".format(data_args.template, new_template)) + logger.info("New SFC template (in-context learning): {}".format(new_sfc_template)) + data_args.template = new_template + if model_args.icl_sfc: + data_args.icl_sfc_prompt = new_sfc_template + else: + logger.info("Automatically convert the template to using demonstrations.") + if data_args.template_list is not None: + for i in range(len(data_args.template_list)): + old_template = data_args.template_list[i] + new_template = old_template + '' + old_template = old_template.replace('*cls*', '') + # Single sentence or sentence pair? + sent_num = 1 + if "_1" in old_template: + sent_num = 2 + for label_id in range(num_labels): + sub_template = old_template + '' + # Replace sent id + for sent_id in range(sent_num): + sub_template = sub_template.replace("_{}*".format(sent_id), "_{}*".format(sent_num + sent_num * label_id + sent_id)) + # Replace mask + sub_template = sub_template.replace("*mask*", "*label_{}*".format(label_id)) + new_template = new_template + sub_template + logger.info("| {} => {}".format(data_args.template_list[i], new_template)) + data_args.template_list[i] = new_template + else: + old_template = data_args.template + new_template = old_template + '' + old_template = old_template.replace('*cls*', '') + # Single sentence or sentence pair? + sent_num = 1 + if "_1" in old_template: + sent_num = 2 + for label_id in range(num_labels): + sub_template = old_template + '' + # Replace sent id + for sent_id in range(sent_num): + sub_template = sub_template.replace("_{}".format(sent_id), "_{}".format(sent_num + sent_num * label_id + sent_id)) + # Replace mask + sub_template = sub_template.replace("*mask*", "*label_{}*".format(label_id)) + new_template = new_template + sub_template + logger.info("| {} => {}".format(data_args.template, new_template)) + data_args.template = new_template + + # Create config + config_kwargs = {'apply_lora': model_args.apply_lora, + 'lora_alpha': model_args.lora_alpha, + 'lora_r': model_args.lora_r} + if model_args.apply_lora: + if 'roberta' in model_args.model_name_or_path: + config = RobertaConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir, + **config_kwargs) + else: + config = OPTConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir, + **config_kwargs + ) + else: + config = AutoConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir + ) + + if training_args.untie_emb: + logger.warn("Untie embeddings and lm head") + logger.warn("NOTE that this only works for OPT. By default RoBERTa model embeddings are already untied.") + config.tie_word_embeddings = False + + if 'prompt' in model_args.few_shot_type: + model_fn = MODEL_TYPES[config.model_type] + elif model_args.few_shot_type == 'finetune': + if training_args.from_linearhead: + model_fn = MODEL_TYPES[config.model_type] + else: + model_fn = AutoModelForSequenceClassification + else: + raise NotImplementedError + special_tokens = [] + + # Create tokenizer + tokenizer = AutoTokenizer.from_pretrained( + model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, + additional_special_tokens=special_tokens, + cache_dir=model_args.cache_dir, + ) + if "opt" in model_args.model_name_or_path: + # Set SEP token + tokenizer.sep_token_id = tokenizer.eos_token_id + tokenizer.bos_token_id = 0 + if "gpt2" in model_args.model_name_or_path: + tokenizer.sep_token_id = tokenizer.eos_token_id + tokenizer.pad_token_id = tokenizer.eos_token_id + + + if training_args.hf_inference_model: + free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) + max_memory = f'{free_in_GB-5}GB' + n_gpus = torch.cuda.device_count() + max_memory = {i: max_memory for i in range(n_gpus)} + + model = model_fn.from_pretrained( + model_args.model_name_or_path, + config=config, + device_map='auto', + torch_dtype=torch.float16 if training_args.efficient_zero_order_fp16 else torch.float32, + max_memory=max_memory, + ) + else: + model = model_fn.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + ) + + if training_args.tie_emb: + logger.warn("Tie embeddings. Only work for RoBERTa (in our code by default they are not tied)") + model.tie_emb() + + if training_args.head_tuning: + if model.config.model_type == "roberta": + head_name = "lm_head" + + for n, p in model.named_parameters(): + if head_name not in n: + p.requires_grad = False + else: + logger.info(f"Only tuning {n}") + + tokenizer.model_type = model.config.model_type + + if training_args.exclude_first_layers != -1: + model = convert_opt_model(model, config, training_args.exclude_first_layers) + + if training_args.prefix_tuning: + from src.prefix import PrefixTuning + PrefixTuning(model, num_prefix=training_args.num_prefix, reparam=not training_args.no_reparam, float16=training_args.efficient_zero_order_fp16, init_by_real_act=training_args.prefix_init_by_real_act) + + # Get our special datasets. + train_dataset = ( + FewShotDataset(data_args, tokenizer=tokenizer, mode="train", use_demo=("demo" in model_args.few_shot_type)) + if training_args.do_train + else None + ) + eval_dataset = ( + FewShotDataset(data_args, tokenizer=tokenizer, mode="dev", use_demo=("demo" in model_args.few_shot_type)) + if training_args.do_eval + else None + ) + test_dataset = ( + FewShotDataset(data_args, tokenizer=tokenizer, mode="test", use_demo=("demo" in model_args.few_shot_type)) + if training_args.do_predict + else None + ) + + set_seed(training_args.seed) + + if training_args.random_model_init: + model.init_weights() # reinit weights to random + + # For BERT, increase the size of the segment (token type) embeddings + if config.model_type == 'bert': + model.resize_token_embeddings(len(tokenizer)) + resize_token_type_embeddings(model, new_num_types=10, random_segment=model_args.random_segment) + + # Pass dataset and argument information to the model + if eval_dataset.label_word_list is not None: + model.label_word_list = torch.tensor(eval_dataset.label_word_list).long().to(training_args.device) + if output_modes_mapping[data_args.task_name] == 'regression': + # lower / upper bounds + model.lb, model.ub = bound_mapping[data_args.task_name] + model.model_args = model_args + model.data_args = data_args + model.tokenizer = tokenizer + + if model_args.apply_lora: + for name, param in model.named_parameters(): + if (name.startswith('roberta') and "lora" not in name) or (name.startswith('opt') and "lora" not in name): + param.requires_grad_(False) + + # Build metric + def build_compute_metrics_fn(task_name: str) -> Callable[[EvalPrediction], Dict]: + def compute_metrics_fn(p: EvalPrediction): + # Note: the eval dataloader is sequential, so the examples are in order. + # We average the logits over each sample for using demonstrations. + predictions = p.predictions + num_logits = predictions.shape[-1] + + num_sample = test_dataset.num_sample if eval_dataset is None else eval_dataset.num_sample + logits = predictions.reshape([num_sample, -1, num_logits]) + logits = logits.mean(axis=0) + + if num_logits == 1: + preds = np.squeeze(logits) + else: + preds = np.argmax(logits, axis=1) + + # Just for sanity, assert label ids are the same. + label_ids = p.label_ids.reshape([num_sample, -1]) + label_ids_avg = label_ids.mean(axis=0) + label_ids_avg = label_ids_avg.astype(p.label_ids.dtype) + assert (label_ids_avg - label_ids[0]).mean() < 1e-2 + label_ids = label_ids[0] + + return compute_metrics_mapping[task_name](task_name, preds, label_ids) + + return compute_metrics_fn + + # Initialize our Trainer + trainer_classes = { + "standard": Trainer, + "linearhead": LinearHeadTrainer, + } + trainer_class = trainer_classes[training_args.trainer] + trainer_kwargs = {} + trainer = trainer_class( + model=model, + args=training_args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + compute_metrics=build_compute_metrics_fn(data_args.task_name), + data_collator=MyDataCollatorWithPadding(tokenizer), + **trainer_kwargs + ) + + # Calibration + if model_args.sfc: + inputs = tokenizer([data_args.sfc_prompt.replace("_", " ")], return_tensors="pt") + logger.info(f"Calibrating SFC with prompt: {data_args.sfc_prompt}") + logger.info("Inputs: {}".format(inputs.input_ids)) + inputs = inputs.to(model.device) + with torch.no_grad(): + model.eval() + logits = model(**inputs)[0] + model.sfc_bias = F.log_softmax(logits.squeeze(0).detach()) + logger.info("SFC bias: {}".format(model.sfc_bias)) + + + # Training + if training_args.do_train: + train_result = trainer.train(model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None) + + if training_args.trainer == "hessian": + # Write the result to log + with FileLock('log_hessian.lock'): + with open('log_hessian', 'a') as f: + train_result.update(vars(model_args)) + train_result.update(vars(training_args)) + train_result.update(vars(data_args)) + if 'evaluation_strategy' in train_result: + train_result.pop('evaluation_strategy') + f.write(str(train_result) + '\n') + exit() + + # Use the early stop, so do not save the model in the end (unless specify save_at_last) + + if training_args.trainer == "standard" or training_args.trainer == "linearhead": + if training_args.save_at_last: + trainer.save_model(training_args.output_dir) + + if trainer.is_world_process_zero(): + tokenizer.save_pretrained(training_args.output_dir) + torch.save(model_args, os.path.join(training_args.output_dir, "model_args.bin")) + torch.save(data_args, os.path.join(training_args.output_dir, "data_args.bin")) + + if training_args.evaluate_during_training: + # Reload the best checkpoint (for eval) + # model.load_state_dict(trainer.best_model_ckpt) + # if training_args.prefix_tuning: + # # We can load prefix by directly using load_state_dict + # model.load_state_dict(torch.load(os.path.join(training_args.output_dir, "pytorch_model.bin"))) + # else: + # model = model_fn.from_pretrained(training_args.output_dir) + # if training_args.exclude_first_layers != -1: + # model = convert_opt_model(model, config, training_args.exclude_first_layers) + + # model = model.to(training_args.device) + + # Now we just reload this from memory instead of disk <-- much faster + trainer.model.load_state_dict(trainer.best_model_ckpt) + + # Evaluation + final_result = { + 'time': str(datetime.today()), + 'output_dir': training_args.output_dir + } + + eval_results = {} + if training_args.do_eval: + logger.info("*** Validate ***") + + eval_datasets = [eval_dataset] + + for eval_dataset in eval_datasets: + trainer.compute_metrics = build_compute_metrics_fn(eval_dataset.args.task_name) + output = trainer.evaluate(eval_dataset=eval_dataset) + eval_result = output.metrics + + output_eval_file = os.path.join( + training_args.output_dir, f"eval_results_{eval_dataset.args.task_name}.txt" + ) + if trainer.is_world_process_zero(): + with open(output_eval_file, "w") as writer: + logger.info("***** Eval results {} *****".format(eval_dataset.args.task_name)) + for key, value in eval_result.items(): + logger.info(" %s = %s", key, value) + writer.write("%s = %s\n" % (key, value)) + final_result[eval_dataset.args.task_name + '_dev_' + key] = value + eval_results.update(eval_result) + + test_results = {} + if training_args.do_predict: + logging.info("*** Test ***") + test_datasets = [test_dataset] + ### Don't evaluate on mnli-mm for our purposes + # if data_args.task_name == "mnli": + # mnli_mm_data_args = dataclasses.replace(data_args, task_name="mnli-mm") + # test_datasets.append( + # FewShotDataset(mnli_mm_data_args, tokenizer=tokenizer, mode="test", use_demo=('demo' in model_args.few_shot_type)) + # ) + + for test_dataset in test_datasets: + trainer.compute_metrics = build_compute_metrics_fn(test_dataset.args.task_name) + output = trainer.evaluate(eval_dataset=test_dataset) + test_result = output.metrics + + output_test_file = os.path.join( + training_args.output_dir, f"test_results_{test_dataset.args.task_name}.txt" + ) + if trainer.is_world_process_zero(): + with open(output_test_file, "w") as writer: + logger.info("***** Test results {} *****".format(test_dataset.args.task_name)) + for key, value in test_result.items(): + logger.info(" %s = %s", key, value) + writer.write("%s = %s\n" % (key, value)) + final_result[test_dataset.args.task_name + '_test_' + key] = value + + if training_args.save_logit: + predictions = output.predictions + num_logits = predictions.shape[-1] + logits = predictions.reshape([test_dataset.num_sample, -1, num_logits]).mean(axis=0) + np.save(os.path.join(training_args.save_logit_dir, "{}-{}-{}.npy".format(test_dataset.task_name, training_args.model_id, training_args.array_id)), logits) + + test_results.update(test_result) + + + if trainer.is_world_process_zero(): + with FileLock('log.lock'): + with open(training_args.log_file, 'a') as f: + final_result.update(vars(model_args)) + final_result.update(vars(training_args)) + final_result.update(vars(data_args)) + if 'evaluation_strategy' in final_result: + final_result.pop('evaluation_strategy') + f.write(str(final_result) + '\n') + + logger.info('****** Output Dir *******') + logger.info(training_args.output_dir) + + return eval_results + +if __name__ == "__main__": + main() diff --git a/baselines/lozo/medium_models/src/LOZOtrainer.py b/baselines/lozo/medium_models/src/LOZOtrainer.py new file mode 100644 index 0000000..e9314ce --- /dev/null +++ b/baselines/lozo/medium_models/src/LOZOtrainer.py @@ -0,0 +1,711 @@ +########## The following part is copied from Transformers' trainer (3.4.0) and later ported to be compatible with v4.4.2 and to support initialization from linear head probing. ########## + +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. +""" + +import collections +import inspect +import math +import os +import re +import shutil +import warnings +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Tuple, Union +from loguru import logger +import numpy as np +import torch +from packaging import version +from torch import nn +from torch.utils.data.dataloader import DataLoader +from torch.utils.data.dataset import Dataset +from torch.utils.data.distributed import DistributedSampler +from torch.utils.data.sampler import RandomSampler, SequentialSampler +from torch.optim.lr_scheduler import LambdaLR +import math +import time + +import transformers +from transformers.file_utils import is_datasets_available, is_in_notebook, is_torch_tpu_available +from transformers.integrations import ( + is_comet_available, + is_optuna_available, + is_ray_available, + is_tensorboard_available, + is_wandb_available, +) +from transformers.optimization import AdamW, get_linear_schedule_with_warmup, get_scheduler + +from transformers.trainer_callback import ( + DefaultFlowCallback, + ProgressCallback, +) +from transformers.trainer_utils import ( + default_compute_objective, +) +from transformers.training_args import TrainingArguments +from transformers.utils import logging +from transformers.trainer_utils import TrainOutput +from transformers.modeling_utils import unwrap_model +from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES +from tqdm import tqdm, trange +from torch.optim import SGD +import torch.nn.functional as F + +from src.linearhead_trainer import LinearHeadTrainer +from transformers.trainer_callback import TrainerState + +import copy + +_use_native_amp = False +_use_apex = False + +DEFAULT_CALLBACKS = [DefaultFlowCallback] +DEFAULT_PROGRESS_CALLBACK = ProgressCallback + +if is_in_notebook(): + from transformers.utils.notebook import NotebookProgressCallback + + DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback + +# Check if Pytorch version >= 1.6 to switch between Native AMP and Apex +if version.parse(torch.__version__) < version.parse("1.6"): + from transformers.file_utils import is_apex_available + + if is_apex_available(): + from apex import amp + _use_apex = True +else: + _use_native_amp = True + from torch.cuda.amp import autocast + +if version.parse(torch.__version__) < version.parse("1.2"): + _use_ddp_no_sync = False +else: + _use_ddp_no_sync = True + +if is_datasets_available(): + import datasets + +if is_torch_tpu_available(): + import torch_xla.core.xla_model as xm + import torch_xla.debug.metrics as met + import torch_xla.distributed.parallel_loader as pl + +if is_tensorboard_available(): + from transformers.integrations import TensorBoardCallback + + DEFAULT_CALLBACKS.append(TensorBoardCallback) + + +if is_wandb_available(): + from transformers.integrations import WandbCallback + + DEFAULT_CALLBACKS.append(WandbCallback) + +if is_comet_available(): + from transformers.integrations import CometCallback + + DEFAULT_CALLBACKS.append(CometCallback) + +if is_optuna_available(): + import optuna + +if is_ray_available(): + from ray import tune + +logger = logging.get_logger(__name__) +logger.setLevel(logging.INFO) + +########## The above part is copied from Transformers' trainer (3.4.0) ########## + +def default_dev_objective(metrics): + """ + Objective used for picking the best model on development sets + """ + if "eval_mnli/acc" in metrics: + return metrics["eval_mnli/acc"] + elif "eval_mnli-mm/acc" in metrics: + return metrics["eval_mnli-mm/acc"] + elif "eval_f1" in metrics: + return metrics["eval_f1"] + elif "eval_mcc" in metrics: + return metrics["eval_mcc"] + elif "eval_pearson" in metrics: + return metrics["eval_pearson"] + elif "eval_acc" in metrics: + return metrics["eval_acc"] + + raise Exception("No metric founded for {}".format(metrics)) + +class LowRankTrainer(LinearHeadTrainer): + """ + Adding some functions based on Transformers' Trainer class. + """ + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.named_parameters_to_optim = [(name, param) for name, param in self.model.named_parameters() if param.requires_grad] + + def create_optimizer_and_scheduler(self, num_training_steps: int): + """ + Based on Transformers' default one, we add fixing layer option where the bottom n layers' parameters + are fixed and only the top layers are further fine-tuned. + """ + if self.args.hf_inference_model: + return + + if self.optimizer is None: + params = {} + for n, p in self.model.named_parameters(): + if self.args.fix_layers > 0: + if 'encoder.layer' in n: + try: + layer_num = int(n[n.find('encoder.layer') + 14:].split('.')[0]) + except: + print(n) + raise Exception("") + if layer_num >= self.args.fix_layers: + print('yes', n) + params[n] = p + else: + print('no ', n) + elif 'embeddings' in n: + print('no ', n) + else: + print('yes', n) + params[n] = p + else: + params[n] = p + no_decay = ["bias", "LayerNorm.weight"] + optimizer_grouped_parameters = [ + { + "params": [p for n, p in params.items() if not any(nd in n for nd in no_decay)], + "weight_decay": self.args.weight_decay, + }, + { + "params": [p for n, p in params.items() if any(nd in n for nd in no_decay)], + "weight_decay": 0.0, + }, + ] + if self.args.optimizer == 'adam': + self.optimizer = AdamW( + optimizer_grouped_parameters, + lr=self.args.learning_rate, + betas=(self.args.adam_beta1, self.args.adam_beta2), + eps=self.args.adam_epsilon, + ) + elif self.args.optimizer == 'sgd': + self.optimizer = SGD( + optimizer_grouped_parameters, + lr=self.args.learning_rate + ) + else: + raise NotImplementedError + if self.lr_scheduler is None: + self.lr_scheduler = get_scheduler( + self.args.lr_scheduler_type, + optimizer=self.optimizer, + num_warmup_steps=self.args.get_warmup_steps(num_training_steps), + num_training_steps=num_training_steps, + ) + + def zo_forward(self, model, inputs): + """ + Get (no gradient) loss from the model. Dropout is turned off too. + """ + model.eval() + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + # Warning: this is copied from the original Huggingface Trainer. Untested. + loss = loss.mean() # mean() to average on multi-gpu parallel training + return loss.detach() + + + def zo_forward_nondiff(self, model, inputs): + """ + Get (no gradient) non-diffiable loss from the model. + """ + model.eval() + assert self.args.task_name == "SQuAD", "Non differentiable objective only supports SQuAD for now." + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + args = self.args + outputs = self.model.generate( + inputs["input_ids"], do_sample=args.sampling, temperature=args.temperature, + num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - inputs["input_ids"].size(1)), + num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id], + ) + output_text = [] + for i in range(len(outputs)): + output_text.append(self.tokenizer.decode(outputs[i][inputs["input_ids"].size(1):], skip_special_tokens=True).strip()) + f1s = [f1(output_text[i], inputs['gold'][i]) for i in range(len(output_text))] + + return -torch.tensor(np.mean(f1s), dtype=torch.float32) + + def random_gaussian_matrix(self, m, n, device, dtype, random_seed=None): + if random_seed is not None: + torch.manual_seed(random_seed) + + random_matrix = torch.randn(m, n, device=device, dtype=dtype) + return random_matrix + + + + # =========================================== LOZO Functions ======================================================================= + + def lowrank_zo_perturb_parameters(self, random_seed=None, scaling_factor=1): + """ + Perturb the parameters with random vector uv^t. + """ + args = self.args + step = self.step + + torch.manual_seed(random_seed if random_seed is not None else self.zo_random_seed) + + for name, param in self.named_parameters_to_optim: + if param.data.ndim >= 2: + if step % args.step_interval == 0: + v = torch.randn(param.data.size(1), args.rank, device=param.data.device, dtype=param.data.dtype) + self.v[name] = v + else: + v = self.v[name] + u = self.random_gaussian_matrix(m=param.data.size(0), n=args.rank, device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * (u@v.t()) * self.args.zo_eps + else: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * self.args.zo_eps + + def lowrank_zo_step(self, model, inputs): + """ + Estimate gradient by Lowrank-zo. Return the loss from f(theta + uv^t) + """ + args = self.args + if hasattr(self, 'step'): + self.step += 1 + else: + self.step = 0 + self.v = {} + self.v_old = {} + self.exp_avg_m = {} + self.exp_avg_sq = {} + + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + + # Sample the random seed for sampling z + self.zo_random_seed = np.random.randint(1000000000) + + # First function evaluation + self.lowrank_zo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + # Second function evaluation + self.lowrank_zo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + + # No gradient accumulation support + assert self.args.gradient_accumulation_steps == 1 + + # Reset model back to its parameters at start of step + self.lowrank_zo_perturb_parameters(scaling_factor=1) + return loss1 + + def lowrank_zo_update(self): + args = self.args + + # Reset the random seed for sampling zs + torch.manual_seed(self.zo_random_seed) + + for name, param in self.named_parameters_to_optim: + if param.data.ndim >= 2: + v = self.v[name] + u = self.random_gaussian_matrix(m=param.data.size(0), n=args.rank, device=param.data.device, dtype=param.data.dtype) + + + if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * (u@v.t()) + args.weight_decay * param.data) + else: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * (u@v.t())) + else: + # Resample z + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * z + args.weight_decay * param.data) + else: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * z) + + self.lr_scheduler.step() + + def lowrank_zo_update_momentum(self): + args = self.args + + # Reset the random seed for sampling zs + torch.manual_seed(self.zo_random_seed) + + for name, param in self.named_parameters_to_optim: + if param.data.ndim >= 2: + v = self.v[name] + u = self.random_gaussian_matrix(m=param.data.size(0), n=args.rank, device=param.data.device, dtype=param.data.dtype) + + if self.step % args.step_interval == 0: + if name in self.v_old: + v_old = self.v_old[name] + n = v_old.shape[0] + self.exp_avg_m[name] = args.beta1 * self.exp_avg_m[name] @ v_old.t() @ v / n + (1 - args.beta1) * self.projected_grad * u + else: + self.exp_avg_m[name] = self.projected_grad * u + elif self.step % args.step_interval == args.step_interval - 1: + self.v_old[name] = v + self.exp_avg_m[name] = args.beta1 * self.exp_avg_m[name] + (1 - args.beta1) * self.projected_grad * u + else: + self.exp_avg_m[name] = args.beta1 * self.exp_avg_m[name] + (1 - args.beta1) * self.projected_grad * u + + + if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + + param.data = param.data - self._get_learning_rate() * (self.exp_avg_m[name] @ v.t() + args.weight_decay * param.data) + else: + param.data = param.data - self._get_learning_rate() * (self.exp_avg_m[name] @ v.t()) + else: + # Resample z + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + if self.step == 0: + self.exp_avg_m[name] = self.projected_grad * z + else: + self.exp_avg_m[name] = args.beta1 * self.exp_avg_m[name] + (1 - args.beta1) * self.projected_grad * z + if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + param.data = param.data - self._get_learning_rate() * (self.exp_avg_m[name] + args.weight_decay * param.data) + else: + param.data = param.data - self._get_learning_rate() * (self.exp_avg_m[name]) + + self.lr_scheduler.step() + + # ===================================================================================================================================== + + + def get_num_samples(self): + if self.args.zero_order_sample_scheduler is None: + noise_sample_time = 1 + elif self.args.zero_order_sample_scheduler == "linear": + noise_sample_time = max(1, int(self.state.global_step / self.args.max_steps * self.args.zero_order_sample)) + elif self.args.zero_order_sample_scheduler == "constant": + noise_sample_time = int(self.args.zero_order_sample) + else: + raise NotImplementedError + # print("Sample %d zs" % (noise_sample_time)) + + return noise_sample_time + + def train(self, model_path=None, dev_objective=None): + """ + Main training entry point. + + The training logic is directly borrowed from transformers.Trainer (version 3.0.2). + Add early stopping. + """ + if self.args.from_linearhead and model_path is None: + super().train(model_path, dev_objective) # Train output layer using LinearHeadTrainer + + self.best_dir = None + self.objective = -float("inf") + self.dev_objective = dev_objective if dev_objective is not None else default_dev_objective + + # Data loading. + train_dataloader = self.get_train_dataloader() + num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps + if num_update_steps_per_epoch == 0: + num_update_steps_per_epoch = 1 + if self.args.max_steps > 0: + t_total = self.args.max_steps + num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int( + self.args.max_steps % num_update_steps_per_epoch > 0 + ) + else: + t_total = int(len(train_dataloader) // self.args.gradient_accumulation_steps * self.args.num_train_epochs) + num_train_epochs = self.args.num_train_epochs + + self.create_optimizer_and_scheduler(num_training_steps=t_total) + optimizer = self.optimizer + scheduler = self.lr_scheduler + + # Check if saved optimizer or scheduler states exist + if ( + model_path is not None + and os.path.isfile(os.path.join(model_path, "optimizer.pt")) + and os.path.isfile(os.path.join(model_path, "scheduler.pt")) + ): + # Load in optimizer and scheduler states + optimizer.load_state_dict( + torch.load(os.path.join(model_path, "optimizer.pt"), map_location=self.args.device) + ) + scheduler.load_state_dict(torch.load(os.path.join(model_path, "scheduler.pt"))) + + model = self.model + + if self.args.fp16 and _use_apex: + if not transformers.is_apex_available(): + raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") + model, optimizer = amp.initialize(model, optimizer, opt_level=self.args.fp16_opt_level) + + # Multi-gpu training (should be after apex fp16 initialization) + if self.args.n_gpu > 1: + model = torch.nn.DataParallel(model) + + # Distributed training (should be after apex fp16 initialization) + if self.args.local_rank != -1: + model = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.args.local_rank], + output_device=self.args.local_rank, + find_unused_parameters=True, + ) + + # Train + if transformers.is_torch_tpu_available(): + total_train_batch_size = self.args.train_batch_size * xm.xrt_world_size() + else: + total_train_batch_size = ( + self.args.train_batch_size + * self.args.gradient_accumulation_steps + * (torch.distributed.get_world_size() if self.args.local_rank != -1 else 1) + ) + logger.info("***** Running training *****") + logger.info(" Num examples = %d", self.num_examples(train_dataloader)) + logger.info(" Num Epochs = %d", num_train_epochs) + logger.info(" Instantaneous batch size per device = %d", self.args.per_device_train_batch_size) + logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d", total_train_batch_size) + logger.info(" Gradient Accumulation steps = %d", self.args.gradient_accumulation_steps) + logger.info(" Total optimization steps = %d", t_total) + + self.state = TrainerState() + self.state.global_step = 0 + start_time = time.time() + self.state.zo_forward_step = 0 + self.epoch = 0 + epochs_trained = 0 + steps_trained_in_current_epoch = 0 + + if self.args.gradient_checkpointing: + model.gradient_checkpointing_enable() + + # Check if continuing training from a checkpoint + if model_path is not None: + # set global_step to global_step of last saved checkpoint from model path + try: + self.state.global_step = int(model_path.split("-")[-1].split("/")[0]) + epochs_trained = self.state.global_step // (len(train_dataloader) // self.args.gradient_accumulation_steps) + steps_trained_in_current_epoch = self.state.global_step % ( + len(train_dataloader) // self.args.gradient_accumulation_steps + ) + + logger.info(" Continuing training from checkpoint, will skip to saved global_step") + logger.info(" Continuing training from epoch %d", epochs_trained) + logger.info(" Continuing training from global step %d", self.state.global_step) + logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch) + except ValueError: + self.state.global_step = 0 + logger.info(" Starting fine-tuning.") + + tr_loss = torch.tensor(0.0).to(self.args.device) + logging_loss_scalar = 0.0 + model.zero_grad() + metrics = None + for epoch in range(epochs_trained, int(num_train_epochs)): + if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): + train_dataloader.sampler.set_epoch(epoch) + + if transformers.is_torch_tpu_available(): + parallel_loader = pl.ParallelLoader(train_dataloader, [self.args.device]).per_device_loader( + self.args.device + ) + epoch_iterator = tqdm(parallel_loader, desc="Iteration", disable=not self.is_local_process_zero()) + else: + epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=True) + + # Reset the past mems state at the beginning of each epoch if necessary. + if self.args.past_index >= 0: + self._past = None + + for step, inputs in enumerate(epoch_iterator): + if self.args.sync_embedding_layers: + assert model.module.model_type == 'opt', 'did not implement embedding layer synchronization for non-OPT models' + model.module.model.decoder.embed_tokens.weight = model.module.lm_head.weight + + # estimate c's (param or grad norm) on epoch 0 + if epoch == 0 and step == 0 and self.args.zo_variant is not None: + self.initialize_c(model, inputs) + elif step == 0 and self.args.zo_variant is not None and self.args.recompute_norms: + self.initialize_c(model, inputs) + + # Skip past any already trained steps if resuming training + if steps_trained_in_current_epoch > 0: + steps_trained_in_current_epoch -= 1 + continue + + if self.args.lowrank_zo: + tr_loss_step = self.lowrank_zo_step(model, inputs) + # tr_loss += tr_loss_step + if self.args.lozo_optimizer == 'sgd': + self.lowrank_zo_update() + elif self.args.lozo_optimizer == 'sgdm': + self.lowrank_zo_update_momentum() + else: + raise ValueError(f"Unsupported optimizer: {self.args.lozo_optimizer}") + self.state.global_step += 1 + self.epoch = epoch + (step + 1) / len(epoch_iterator) + if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or ( + self.state.global_step == 1 and self.args.logging_first_step + ): + logs = {} + logs["loss"] = tr_loss_step.item() + logs["learning_rate"] = self.args.learning_rate + logs["global_step"] = self.state.global_step + logs["max_steps"] = self.args.max_steps + logs["time"] = int(time.time() - start_time) + self.log(logs) + logger.info(str(logs)) + # standard, non-ZO optimization + else: + tr_loss += self.training_step(model, inputs) + + if (step + 1) % self.args.gradient_accumulation_steps == 0 or ( + # last step in epoch but step is always smaller than gradient_accumulation_steps + len(epoch_iterator) <= self.args.gradient_accumulation_steps + and (step + 1) == len(epoch_iterator) + ): + if self.args.fp16 and _use_native_amp: + self.scaler.unscale_(optimizer) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm) + elif self.args.fp16: + norm = torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), self.args.max_grad_norm) + else: + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm) + + if self.args.optimizer_variant == 'signgd': + for n,p in model.named_parameters(): + if p.grad is not None: + p.grad = torch.sign(p.grad) + + if transformers.is_torch_tpu_available(): + xm.optimizer_step(optimizer) + elif self.args.fp16 and _use_native_amp: + self.scaler.step(optimizer) + self.scaler.update() + else: + optimizer.step() + + scheduler.step() + model.zero_grad() + self.state.global_step += 1 + self.epoch = epoch + (step + 1) / len(epoch_iterator) + + if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or ( + self.state.global_step == 1 and self.args.logging_first_step + ): + logs = {} + tr_loss_scalar = tr_loss.item() + logs["loss"] = (tr_loss_scalar - logging_loss_scalar) / self.args.logging_steps + logs["norm"] = norm.item() + # backward compatibility for pytorch schedulers + logs["learning_rate"] = ( + scheduler.get_last_lr()[0] + if version.parse(torch.__version__) >= version.parse("1.4") + else scheduler.get_lr()[0] + ) + logging_loss_scalar = tr_loss_scalar + + self.log(logs) + logger.info(str(logs)) + + if self.args.max_steps > 0 and self.state.global_step > self.args.max_steps or (self.args.max_zo_forward_steps > 0 and self.state.zo_forward_step > self.args.max_zo_forward_steps): + epoch_iterator.close() + break + + if self.args.evaluate_during_training and self.state.global_step % self.args.eval_steps == 0: + output = self.evaluate() + metrics = output.metrics + objective = self.dev_objective(metrics) + if objective > self.objective: + logger.info("Best dev result: {}".format(objective)) + self.objective = objective + # self.save_model(self.args.output_dir) + + # Now we save this to (CPU) memory instead of disk <-- much faster + self.best_model_ckpt = {k: v.detach().cpu() for k, v in model.state_dict().items()} + + if self.args.max_steps > 0 and self.state.global_step > self.args.max_steps or (self.args.max_zo_forward_steps > 0 and self.state.zo_forward_step > self.args.max_zo_forward_steps): + # train_iterator.close() + break + if self.args.tpu_metrics_debug or self.args.debug: + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + + if self.args.past_index and hasattr(self, "_past"): + # Clean the state at the end of training + delattr(self, "_past") + + logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") + return TrainOutput(self.state.global_step, tr_loss / self.state.global_step, metrics), self.objective + + + """ + Difference compared to original implementation: return output instead of output.metrics (so there is also the logits) + """ + def evaluate(self, eval_dataset: Optional[Dataset] = None) -> Dict[str, float]: + """ + Run evaluation and returns metrics. + + The calling script will be responsible for providing a method to compute metrics, as they are + task-dependent (pass it to the init :obj:`compute_metrics` argument). + + You can also subclass and override this method to inject custom behavior. + + Args: + eval_dataset (:obj:`Dataset`, `optional`): + Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, + columns not accepted by the ``model.forward()`` method are automatically removed. It must implement + the :obj:`__len__` method. + + Returns: + A dictionary containing the evaluation loss and the potential metrics computed from the predictions. + """ + if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): + raise ValueError("eval_dataset must implement __len__") + + eval_dataloader = self.get_eval_dataloader(eval_dataset) + + output = self.prediction_loop(eval_dataloader, description="Evaluation") + + self.log(output.metrics) + logger.info(output.metrics) + + if self.args.tpu_metrics_debug or self.args.debug: + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + + return output + diff --git a/baselines/lozo/medium_models/src/dataset.py b/baselines/lozo/medium_models/src/dataset.py new file mode 100644 index 0000000..f770dea --- /dev/null +++ b/baselines/lozo/medium_models/src/dataset.py @@ -0,0 +1,695 @@ +"""Dataset utils for different data settings for GLUE.""" + +import os +import logging +import torch +import numpy as np +import time +from filelock import FileLock +import json +from src.processors import processors_mapping, num_labels_mapping, output_modes_mapping, compute_metrics_mapping, median_mapping +from transformers.data.processors.utils import InputFeatures +import dataclasses +from dataclasses import dataclass +from typing import List, Optional, Union +import pandas as pd + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +@dataclass(frozen=True) +class OurInputFeatures(InputFeatures): + """ + Inherit from Transformers' InputFeatuers. + """ + + input_ids: List[int] + attention_mask: Optional[List[int]] = None + token_type_ids: Optional[List[int]] = None + label: Optional[Union[int, float]] = None + mask_pos: Optional[List[int]] = None # Position of the mask token + label_word_list: Optional[List[int]] = None # Label word mapping (dynamic) + + # For icl sfc + sfc_input_ids: List[int] = None + sfc_attention_mask: Optional[List[int]] = None + sfc_mask_pos: Optional[List[int]] = None + + def to_json_string(self): + """Serializes this instance to a JSON string.""" + return json.dumps(dataclasses.asdict(self)) + "\n" + +def input_example_to_string(example, sep_token): + if example.text_b is None: + return example.text_a + else: + # Warning: very simple hack here + return example.text_a + ' ' + sep_token + ' ' + example.text_b + +def input_example_to_tuple(example): + if example.text_b is None: + if pd.isna(example.text_a) or example.text_a is None: + return [''] + logger.warn("Empty input") + else: + return [example.text_a] + else: + return [example.text_a, example.text_b] + +def tokenize_multipart_input( + input_text_list, + max_length, + tokenizer, + task_name=None, + prompt=False, + template=None, + label_word_list=None, + first_sent_limit=None, + other_sent_limit=None, + gpt3=False, + truncate_head=False, + support_labels=None, +): + def enc(text): + return tokenizer.encode(text, add_special_tokens=False) + + input_ids = [] + attention_mask = [] + token_type_ids = [] # Only for BERT + mask_pos = None # Position of the mask token + + if prompt: + """ + Concatenate all sentences and prompts based on the provided template. + Template example: '*cls*It was*mask*.*sent_0***label_0:*sent_1****label_1*:*sent_2***' + *xx* represent variables: + *cls*: cls_token + *mask*: mask_token + *sep*: sep_token + *sep+*: sep_token, also means +1 for segment id + *sent_i*: sentence i (input_text_list[i]) + *sent-_i*: same as above, but delete the last token + *sentl_i*: same as above, but use lower case for the first word + *sentl-_i*: same as above, but use lower case for the first word and delete the last token + *+sent_i*: same as above, but add a space before the sentence + *+sentl_i*: same as above, but add a space before the sentence and use lower case for the first word + *label_i*: label_word_list[i] + *label_x*: label depends on the example id (support_labels needed). this is only used in GPT-3's in-context learning + + Use "_" to replace space. + PAY ATTENTION TO SPACE!! DO NOT leave space before variables, for this will lead to extra space token. + """ + assert template is not None + + special_token_mapping = { + 'bos': tokenizer.bos_token_id, 'cls': tokenizer.cls_token_id, 'eos': tokenizer.eos_token_id, 'mask': tokenizer.mask_token_id, 'sep': tokenizer.sep_token_id, 'sep+': tokenizer.sep_token_id, + } + template_list = template.split('*') # Get variable list in the template + segment_id = 0 # Current segment id. Segment id +1 if encountering sep+. + + for part_id, part in enumerate(template_list): + new_tokens = [] + segment_plus_1_flag = False + if part in special_token_mapping: + if (part == 'cls' or part == 'bos') and ('T5' in type(tokenizer).__name__ or tokenizer.model_type == "gpt2"): + # T5 or GPT-2 do not have cls token + continue + new_tokens.append(special_token_mapping[part]) + if part == 'sep+': + segment_plus_1_flag = True + elif part[:6] == 'label_': + # Note that label_word_list already has extra space, so do not add more space ahead of it. + label_id = int(part.split('_')[1]) + label_word = label_word_list[label_id] + new_tokens.append(label_word) + elif part[:7] == 'labelx_': + instance_id = int(part.split('_')[1]) + label_id = support_labels[instance_id] + label_word = label_word_list[label_id] + new_tokens.append(label_word) + elif part[:5] == 'sent_': + sent_id = int(part.split('_')[1]) + new_tokens += enc(input_text_list[sent_id]) + elif part[:6] == '+sent_': + # Add space + sent_id = int(part.split('_')[1]) + new_tokens += enc(' ' + input_text_list[sent_id]) + elif part[:6] == 'sent-_': + # Delete the last token + sent_id = int(part.split('_')[1]) + new_tokens += enc(input_text_list[sent_id][:-1]) + elif part[:6] == 'sentl_': + # Lower case the first token + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].lower() + text[1:] + new_tokens += enc(text) + elif part[:7] == '+sentl_': + # Lower case the first token and add space + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].lower() + text[1:] + new_tokens += enc(' ' + text) + elif part[:7] == 'sentl-_': + # Lower case the first token and discard the last token + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].lower() + text[1:] + new_tokens += enc(text[:-1]) + elif part[:6] == 'sentu_': + # Upper case the first token + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].upper() + text[1:] + new_tokens += enc(text) + elif part[:7] == '+sentu_': + # Upper case the first token and add space + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].upper() + text[1:] + new_tokens += enc(' ' + text) + elif part[:8] == '+sentu-_': + # Upper case the first token and add space + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].upper() + text[1:] + new_tokens += enc(' ' + text[:-1]) + else: + # Just natural language prompt + part = part.replace('_', ' ') + # handle special case when T5 tokenizer might add an extra space + if len(part) == 1: + new_tokens.append(tokenizer.convert_tokens_to_ids(part)) + else: + new_tokens += enc(part) + + if part[:4] == 'sent' or part[1:5] == 'sent': + # If this part is the sentence, limit the sentence length + sent_id = int(part.split('_')[1]) + if sent_id == 0: + if first_sent_limit is not None: + new_tokens = new_tokens[:first_sent_limit] + else: + if other_sent_limit is not None: + new_tokens = new_tokens[:other_sent_limit] + + input_ids += new_tokens + attention_mask += [1 for i in range(len(new_tokens))] + token_type_ids += [segment_id for i in range(len(new_tokens))] + + if segment_plus_1_flag: + segment_id += 1 + else: + if tokenizer.cls_token_id is not None: + input_ids = [tokenizer.cls_token_id] + attention_mask = [1] + token_type_ids = [0] + else: + input_ids = [] + attention_mask = [] + token_type_ids = [] + + for sent_id, input_text in enumerate(input_text_list): + if input_text is None: + # Do not have text_b + continue + if pd.isna(input_text) or input_text is None: + # Empty input + input_text = '' + input_tokens = enc(input_text) + [tokenizer.sep_token_id] + input_ids += input_tokens + attention_mask += [1 for i in range(len(input_tokens))] + token_type_ids += [sent_id for i in range(len(input_tokens))] + + if 'T5' in type(tokenizer).__name__: # T5 does not have CLS token + input_ids = input_ids[1:] + attention_mask = attention_mask[1:] + token_type_ids = token_type_ids[1:] + + # Padding + if first_sent_limit is not None and len(input_ids) > max_length: + # If using sentence limit, the total length still exceeds the maximum limit, report a warning + logger.warn("Input exceeds max_length limit: {}".format(tokenizer.decode(input_ids))) + + ### Code below is commented out, because we use dynamic padding rather than static padding to max_length + # while len(input_ids) < max_length: + # input_ids.append(tokenizer.pad_token_id) + # attention_mask.append(0) + # token_type_ids.append(0) + + # Truncate + if len(input_ids) > max_length: + if truncate_head: + input_ids = input_ids[-max_length:] + attention_mask = attention_mask[-max_length:] + token_type_ids = token_type_ids[-max_length:] + else: + # Default is to truncate the tail + input_ids = input_ids[:max_length] + attention_mask = attention_mask[:max_length] + token_type_ids = token_type_ids[:max_length] + + # Find mask token + if prompt and tokenizer.mask_token_id is not None: + # Make sure that the masked position is inside the max_length + assert tokenizer.mask_token_id in input_ids, \ + "Mask token not found for input: {} {}".format(input_text_list, input_ids) + mask_pos = [input_ids.index(tokenizer.mask_token_id)] + assert mask_pos[0] < max_length + elif prompt and tokenizer.mask_token_id is None: + # autoregressive model + mask_pos = [len(input_ids) - 1] + + result = {'input_ids': input_ids, 'attention_mask': attention_mask} + if 'BERT' in type(tokenizer).__name__: + # Only provide token type ids for BERT + result['token_type_ids'] = token_type_ids + + if prompt: + result['mask_pos'] = mask_pos + + return result + + + +class FewShotDataset(torch.utils.data.Dataset): + """Few-shot dataset.""" + + def __init__(self, args, tokenizer, cache_dir=None, mode="train", use_demo=False): + self.args = args + self.task_name = args.task_name + + self.processor = processors_mapping[args.task_name] + + self.tokenizer = tokenizer + self.mode = mode + + # If not using demonstrations, use use_demo=True + self.use_demo = use_demo + if self.use_demo: + logger.info("Use demonstrations") + assert mode in ["train", "dev", "test"] + + # Get label list and (for prompt) label word list + self.label_list = self.processor.get_labels() + self.num_labels = len(self.label_list) + if args.prompt and args.mapping is not None: + self.label_to_word = eval(args.mapping) + + for key in self.label_to_word: + # For RoBERTa/BART/T5, tokenization also considers space, so we use space+word as label words. + if self.label_to_word[key][0] not in ['<', '[', '.', ',']: + # Make sure space+word is in the vocabulary + assert len(tokenizer.tokenize(' ' + self.label_to_word[key])) == 1 + self.label_to_word[key] = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(' ' + self.label_to_word[key])[0]) + else: + self.label_to_word[key] = tokenizer.convert_tokens_to_ids(self.label_to_word[key]) + logger.info("Label {} to word {} ({})".format(key, tokenizer.convert_ids_to_tokens(self.label_to_word[key]), self.label_to_word[key])) + + if len(self.label_list) > 1: + self.label_word_list = [self.label_to_word[label] for label in self.label_list] + else: + # Regression task + # '0' represents low polarity and '1' represents high polarity. + self.label_word_list = [self.label_to_word[label] for label in ['0', '1']] + else: + self.label_to_word = None + self.label_word_list = None + + # Multiple sampling: when using demonstrations, we sample different combinations of demonstrations during + # inference and aggregate the results by averaging the logits. The number of different samples is num_sample. + if (mode == "train") or not self.use_demo: + # We do not do multiple sampling when not using demonstrations or when it's the training mode + self.num_sample = 1 + else: + self.num_sample = args.num_sample + + # If we use multiple templates, we also need to do multiple sampling during inference. + if args.prompt and args.template_list is not None: + logger.info("There are %d templates. Multiply num_sample by %d" % (len(args.template_list), len(args.template_list))) + self.num_sample *= len(args.template_list) + + logger.info("Total num_sample for mode %s: %d" % (mode, self.num_sample)) + + # Load cache + # Cache name distinguishes mode, task name, tokenizer, and length. So if you change anything beyond these elements, make sure to clear your cache. + cached_features_file = os.path.join( + cache_dir if cache_dir is not None else args.data_dir, + "cached_{}_{}_{}_{}".format( + mode, + tokenizer.__class__.__name__ + "-" + tokenizer.model_type, + str(args.max_seq_length), + args.task_name, + ), + ) + + logger.info(f"Creating/loading examples from dataset file at {args.data_dir}") + + lock_path = cached_features_file + ".lock" + with FileLock(lock_path): + + if os.path.exists(cached_features_file) and not args.overwrite_cache: + start = time.time() + self.support_examples, self.query_examples = torch.load(cached_features_file) + logger.info( + f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start + ) + else: + logger.info(f"Creating features from dataset file at {args.data_dir}") + + # The support examples are sourced from the training set. + self.support_examples = self.processor.get_train_examples(args.data_dir) + + if mode == "dev": + self.query_examples = self.processor.get_dev_examples(args.data_dir) + elif mode == "test": + self.query_examples = self.processor.get_test_examples(args.data_dir) + else: + self.query_examples = self.support_examples + + start = time.time() + torch.save([self.support_examples, self.query_examples], cached_features_file) + # ^ This seems to take a lot of time so I want to investigate why and how we can improve. + logger.info( + "Saving features into cached file %s [took %.3f s]", cached_features_file, time.time() - start + ) + + # For filtering in using demonstrations, load pre-calculated embeddings + if self.use_demo and args.demo_filter: + split_name = '' + if mode == 'train': + split_name = 'train' + elif mode == 'dev': + if args.task_name == 'mnli': + split_name = 'dev_matched' + elif args.task_name == 'mnli-mm': + split_name = 'dev_mismatched' + else: + split_name = 'dev' + elif mode == 'test': + if args.task_name == 'mnli': + split_name = 'test_matched' + elif args.task_name == 'mnli-mm': + split_name = 'test_mismatched' + else: + split_name = 'test' + else: + raise NotImplementedError + + self.support_emb = np.load(os.path.join(args.data_dir, "train_{}.npy".format(args.demo_filter_model))) + self.query_emb = np.load(os.path.join(args.data_dir, "{}_{}.npy".format(split_name, args.demo_filter_model))) + logger.info("Load embeddings (for demonstration filtering) from {}".format(os.path.join(args.data_dir, "{}_{}.npy".format(split_name, args.demo_filter_model)))) + + assert len(self.support_emb) == len(self.support_examples) + assert len(self.query_emb) == len(self.query_examples) + + # Size is expanded by num_sample + self.size = len(self.query_examples) * self.num_sample + + # Prepare examples (especially for using demonstrations) + support_indices = list(range(len(self.support_examples))) + self.example_idx = [] + for sample_idx in range(self.num_sample): + for query_idx in range(len(self.query_examples)): + # If training, exclude the current example. Else keep all. + if self.use_demo and args.demo_filter: + # Need sentence_transformers for demonstrations, + # which is not included in the requirements for us, but see original LM-BFF repo. + from sentence_transformers import SentenceTransformer, util + + # Demonstration filtering + candidate = [support_idx for support_idx in support_indices + if support_idx != query_idx or mode != "train"] + sim_score = [] + for support_idx in candidate: + sim_score.append((support_idx, util.pytorch_cos_sim(self.support_emb[support_idx], self.query_emb[query_idx]))) + sim_score.sort(key=lambda x: x[1], reverse=True) + if self.num_labels == 1: + # Regression task + limit_each_label = int(len(sim_score) // 2 * args.demo_filter_rate) + count_each_label = {'0': 0, '1': 0} + context_indices = [] + + if args.debug_mode: + print("Query %s: %s" % (self.query_examples[query_idx].label, self.query_examples[query_idx].text_a)) # debug + for support_idx, score in sim_score: + if count_each_label['0' if float(self.support_examples[support_idx].label) <= median_mapping[args.task_name] else '1'] < limit_each_label: + count_each_label['0' if float(self.support_examples[support_idx].label) <= median_mapping[args.task_name] else '1'] += 1 + context_indices.append(support_idx) + if args.debug_mode: + print(" %.4f %s | %s" % (score, self.support_examples[support_idx].label, self.support_examples[support_idx].text_a)) # debug + else: + limit_each_label = int(len(sim_score) // self.num_labels * args.demo_filter_rate) + count_each_label = {label: 0 for label in self.label_list} + context_indices = [] + + if args.debug_mode: + print("Query %s: %s" % (self.query_examples[query_idx].label, self.query_examples[query_idx].text_a)) # debug + for support_idx, score in sim_score: + if count_each_label[self.support_examples[support_idx].label] < limit_each_label: + count_each_label[self.support_examples[support_idx].label] += 1 + context_indices.append(support_idx) + if args.debug_mode: + print(" %.4f %s | %s" % (score, self.support_examples[support_idx].label, self.support_examples[support_idx].text_a)) # debug + else: + # Using demonstrations without filtering + context_indices = [support_idx for support_idx in support_indices + if support_idx != query_idx or mode != "train"] + + # We'll subsample context_indices further later. + self.example_idx.append((query_idx, context_indices, sample_idx)) + + # If it is not training, we pre-process the data; otherwise, we process the data online. + if mode != "train": + self.features = [] + _ = 0 + for query_idx, context_indices, bootstrap_idx in self.example_idx: + # The input (query) example + example = self.query_examples[query_idx] + # The demonstrations + supports = self.select_context([self.support_examples[i] for i in context_indices]) + + if args.template_list is not None: + template = args.template_list[sample_idx % len(args.template_list)] # Use template in order + else: + template = args.template + self.features.append(self.convert_fn( + example=example, + supports=supports, + use_demo=self.use_demo, + label_list=self.label_list, + prompt=args.prompt, + template=template, + sfc_template=getattr(args, "icl_sfc_prompt", None), + label_word_list=self.label_word_list, + verbose=True if _ == 0 else False, + )) + + _ += 1 + else: + self.features = None + + def select_context(self, context_examples): + """ + Select demonstrations from provided examples. + """ + max_demo_per_label = 1 + counts = {k: 0 for k in self.label_list} + if len(self.label_list) == 1: + # Regression + counts = {'0': 0, '1': 0} + selection = [] + + if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail: + # For GPT-3's in-context learning, we sample gpt3_in_context_num demonstrations randomly. + order = np.random.permutation(len(context_examples)) + for i in range(min(self.args.gpt3_in_context_num, len(order))): + selection.append(context_examples[order[i]]) + else: + # Our sampling strategy + order = np.random.permutation(len(context_examples)) + + for i in order: + label = context_examples[i].label + if len(self.label_list) == 1: + # Regression + label = '0' if float(label) <= median_mapping[self.args.task_name] else '1' + if counts[label] < max_demo_per_label: + selection.append(context_examples[i]) + counts[label] += 1 + if sum(counts.values()) == len(counts) * max_demo_per_label: + break + + assert len(selection) > 0 + + return selection + + def __len__(self): + return self.size + + def __getitem__(self, i): + if self.features is None: + query_idx, context_indices, bootstrap_idx = self.example_idx[i] + # The input (query) example + example = self.query_examples[query_idx] + # The demonstrations + supports = self.select_context([self.support_examples[i] for i in context_indices]) + + if self.args.template_list is not None: + template = self.args.template_list[sample_idx % len(self.args.template_list)] + else: + template = self.args.template + + features = self.convert_fn( + example=example, + supports=supports, + use_demo=self.use_demo, + label_list=self.label_list, + prompt=self.args.prompt, + template=template, + label_word_list=self.label_word_list, + verbose=False, + ) + + else: + features = self.features[i] + + return features + + def get_labels(self): + return self.label_list + + + def convert_fn( + self, + example, + supports, + use_demo=False, + label_list=None, + prompt=False, + template=None, + sfc_template=None, + label_word_list=None, + verbose=False + ): + """ + Returns a list of processed "InputFeatures". + """ + max_length = self.args.max_seq_length + + # Prepare labels + label_map = {label: i for i, label in enumerate(label_list)} # Mapping the label names to label ids + if len(label_list) == 1: + # Regression + label_map = {'0': 0, '1': 1} + + # Get example's label id (for training/inference) + if example.label is None: + example_label = None + elif len(label_list) == 1: + # Regerssion + example_label = float(example.label) + else: + example_label = label_map[example.label] + + # Prepare other features + if not use_demo: + # No using demonstrations + inputs = tokenize_multipart_input( + input_text_list=input_example_to_tuple(example), + max_length=max_length, + tokenizer=self.tokenizer, + task_name=self.args.task_name, + prompt=prompt, + template=template, + label_word_list=label_word_list, + first_sent_limit=self.args.first_sent_limit, + other_sent_limit=self.args.other_sent_limit, + ) + features = OurInputFeatures(**inputs, label=example_label) + + else: + # Using demonstrations + + # Max length + if self.args.double_demo: + # When using demonstrations, double the maximum length + # Note that in this case, args.max_seq_length is the maximum length for a single sentence + max_length = max_length * 2 + if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail: + # When using GPT-3's in-context learning, take the maximum tokenization length of the model (512) + if self.tokenizer.model_type == "gpt2": + max_length = 1024 + elif self.tokenizer.model_type == "opt": + max_length = 2048 + else: + max_length = 512 + + # All input sentences, including the query and the demonstrations, are put into augmented_examples, + # and are numbered based on the order (starting from 0). For single sentence tasks, the input (query) + # is the sentence 0; for sentence-pair tasks, the input (query) is the sentence 0 and 1. Note that for GPT-3's + # in-context learning, the input (query) might be at the end instead of the beginning (gpt3_in_context_head) + augmented_example = [] + query_text = input_example_to_tuple(example) # Input sentence list for query + support_by_label = [[] for i in range(len(label_map))] + + if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail: + support_labels = [] + augmented_example = query_text + for support_example in supports: + augmented_example += input_example_to_tuple(support_example) + current_label = support_example.label + if len(label_list) == 1: + current_label = '0' if float(current_label) <= median_mapping[self.args.task_name] else '1' # Regression + support_labels.append(label_map[current_label]) + else: + # Group support examples by label + for label_name, label_id in label_map.items(): + if len(label_list) == 1: + # Regression + for support_example in filter(lambda s: ('0' if float(s.label) <= median_mapping[self.args.task_name] else '1') == label_name, supports): + support_by_label[label_id] += input_example_to_tuple(support_example) + else: + for support_example in filter(lambda s: s.label == label_name, supports): + support_by_label[label_id] += input_example_to_tuple(support_example) + + augmented_example = query_text + for label_id in range(len(label_map)): + augmented_example += support_by_label[label_id] + + # Tokenization (based on the template) + inputs = tokenize_multipart_input( + input_text_list=augmented_example, + max_length=max_length, + tokenizer=self.tokenizer, + task_name=self.args.task_name, + prompt=prompt, + template=template, + label_word_list=label_word_list, + first_sent_limit=self.args.first_sent_limit, + other_sent_limit=self.args.other_sent_limit, + truncate_head=self.args.truncate_head, + gpt3=self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail, + support_labels=None if not (self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail) else support_labels + ) + if sfc_template is not None: + # Process sfc example + if verbose: + logger.info("*** SFC Example ***") + sfc_feature = self.convert_fn( + example, supports, use_demo=use_demo, label_list=label_list, prompt=prompt, template=sfc_template, label_word_list=label_word_list, verbose=verbose + ) + features = OurInputFeatures(**inputs, label=example_label, sfc_input_ids=sfc_feature.input_ids, sfc_attention_mask=sfc_feature.attention_mask, sfc_mask_pos=sfc_feature.mask_pos) + else: + features = OurInputFeatures(**inputs, label=example_label) + + if verbose: + logger.info("*** Example ***") + logger.info("guid: %s" % (example.guid)) + logger.info("features: %s" % features) + logger.info("text: %s" % self.tokenizer.decode(features.input_ids)) + + return features + + + diff --git a/baselines/lozo/medium_models/src/kernel_solvers.py b/baselines/lozo/medium_models/src/kernel_solvers.py new file mode 100644 index 0000000..03dd4b9 --- /dev/null +++ b/baselines/lozo/medium_models/src/kernel_solvers.py @@ -0,0 +1,298 @@ +from transformers.utils import logging +import torch +import torch.nn.functional as F +from sklearn.svm import SVC, SVR +from sklearn.linear_model import LogisticRegressionCV +logger = logging.get_logger(__name__) + +class BaseKernelSolver: + def __init__(self, args): + self.args = args + + # initialized with fit() + self.num_labels = None + self.kernel_dtype = None + + def get_regularized_kernel(self, kernel): + if self.args.kernel_regularization: + _, S, _ = torch.svd(kernel) + op_norm = S.max() + + reg = (self.args.kernel_regularization * op_norm).to(kernel.dtype) + + identity = torch.eye(kernel.shape[1], dtype=kernel.dtype).unsqueeze(0) + return kernel + identity * reg + else: + return kernel + + def metrics(self): + return {} + + def get_target_coords(self, targets): + if self.num_labels == 1: # Regression + return targets.flatten().to(self.kernel_dtype).unsqueeze(1) + else: + return torch.nn.functional.one_hot(targets.flatten(), self.num_labels).to(self.kernel_dtype) + + def loss(self, preds, targets): + targets_coords = self.get_target_coords(targets) + return 1/targets_coords.shape[0] * ((preds - targets_coords)**2).sum().item() + + def fit(self, train_kernel, train_targets, train_logits=None): + raise NotImplementedError("BaseKernelSolver is just the abstract base class") + + def predict(self, eval_kernel, eval_targets, eval_logits=None): + raise NotImplementedError("BaseKernelSolver is just the abstract base class") + + +class LstsqKernelSolver(BaseKernelSolver): + def __init__(self, args): + super().__init__(args) + + # initialized with fit() + self.kernel_solution = None + self.residual = None + self.rank = None + + def metrics(self): + metrics_dict = super().metrics() + if self.rank is not None: + if self.rank.numel() > 1: + for i,r in enumerate(self.rank.tolist()): + metrics_dict["rank{}".format(i)] = r + else: + metrics_dict["rank0"] = self.rank.item() + return metrics_dict + + def fit(self, train_kernel, train_targets, train_logits=None): + self.num_labels = train_kernel.size(0) + self.kernel_dtype = train_kernel.dtype + + kernel = self.get_regularized_kernel(train_kernel) + train_targets_coords = self.get_target_coords(train_targets) + + if train_logits is not None and self.args.f0_scaling > 0: + train_targets_coords -= train_logits / self.args.f0_scaling + + self.kernel_solution, self.residuals, self.rank, _ = torch.linalg.lstsq(kernel, train_targets_coords.t()) + + def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs): + assert self.kernel_solution is not None, "Must call fit() before predict()" + assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()" + + eval_preds = torch.bmm( + eval_kernel.transpose(1, 2), + self.kernel_solution.unsqueeze(2) + ).squeeze(2).transpose(0, 1) # shape [#dataset_outer, #classes] + + if eval_logits is not None and self.args.f0_scaling > 0: + eval_preds += eval_logits / self.args.f0_scaling + + eval_loss = self.loss(eval_preds, eval_targets) + return eval_loss, eval_preds + + +class AsymmetricLstsqKernelSolver(LstsqKernelSolver): + def __init__(self, args): + super().__init__(args) + + self.N = None + self.train_targets = None + + def fit(self, train_kernel, train_targets, train_logits=None): + self.num_labels = train_kernel.size(0) + self.kernel_dtype = train_kernel.dtype + assert self.num_labels == 1, "SVMKernelSolver only works for regression tasks or binary_classification" + + kernel = self.get_regularized_kernel(train_kernel) + train_targets_coords = self.get_target_coords(train_targets) + + if train_logits is not None and self.args.f0_scaling > 0: + train_targets_coords -= train_logits / self.args.f0_scaling + + kernel = kernel.squeeze() + H = torch.zeros(kernel.shape) + Y = train_targets_coords.squeeze() + N = H.shape[0] + + for i in range(N): + for j in range(N): + H[i,j] = Y[i] * (kernel[i,j]* Y[j]) + + # # system with biases + # A = torch.zeros(2*N + 2, 2*N + 2, dtype=self.kernel_dtype) + # A[0, 2:2+N] = Y + # A[1, 2+N:] = Y + # A[2:2+N, 0] = Y + # A[2+N:, 1] = Y + # A[2:2+N, 2:2+N] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later + # A[2:2+N, 2+N:] = H + # A[2+N:, 2:2+N] = H.T + # A[2+N:, 2+N:] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later + + # B = torch.zeros(2*N+2, dtype=self.kernel_dtype) + # B[2:] = 1 + + # system without biases + A = torch.zeros(2*N, 2*N, dtype=self.kernel_dtype) + A[:N, :N] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later + A[:N, N:] = H + A[N:, :N] = H.T + A[N:, N:] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later + B = torch.ones(2*N, dtype=self.kernel_dtype) + + self.N = N + self.Y = Y + self.kernel_solution, self.residuals, self.rank, _ = torch.linalg.lstsq(A, B) + + def predict(self, eval_kernel, eval_targets, eval_logits=None, eval_kernel_flipped=None, **unused_kwargs): + assert self.kernel_solution is not None, "Must call fit() before predict()" + assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()" + + N = self.N + # beta_bias = self.kernel_solution[0] + # alpha_bias = self.kernel_solution[1] + # alpha = self.kernel_solution[2:2+N].unsqueeze(0) + # beta = self.kernel_solution[2+N:].unsqueeze(0) + alpha = self.kernel_solution[:N].unsqueeze(0) + beta = self.kernel_solution[N:].unsqueeze(0) + + omega = torch.bmm( + eval_kernel.transpose(1, 2), + (alpha*self.Y).unsqueeze(2) + ).squeeze(2).transpose(0, 1) #+ alpha_bias + nu = torch.bmm( + eval_kernel_flipped.transpose(1, 2), + (beta*self.Y).unsqueeze(2) + ).squeeze(2).transpose(0, 1) #+ beta_bias + + eval_preds = (self.args.kernel_lambda * omega + (1-self.args.kernel_lambda) * nu) + + if eval_logits is not None and self.args.f0_scaling > 0: + eval_preds += eval_logits / self.args.f0_scaling + + eval_loss = self.loss(eval_preds, eval_targets) + return eval_loss, eval_preds + + +class SVRKernelSolver(BaseKernelSolver): + def __init__(self, args): + super().__init__(args) + + self.svms = None + + def fit(self, train_kernel, train_targets, train_logits=None): + self.num_labels = train_kernel.size(0) + self.kernel_dtype = train_kernel.dtype + + kernel = self.get_regularized_kernel(train_kernel) + train_targets_coords = self.get_target_coords(train_targets) + + if train_logits is not None and self.args.f0_scaling > 0: + train_targets_coords -= train_logits / self.args.f0_scaling + + self.svms = [] + for k in range(self.num_labels): + svm = SVR(kernel='precomputed') + svm.fit(kernel[k].cpu().numpy(), train_targets_coords[:,k].cpu().t().numpy()) + self.svms.append(svm) + + def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs): + assert self.svms is not None, "Must call fit() before predict()" + assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()" + + eval_preds = [] + for k in range(self.num_labels): + predict_k = self.svms[k].predict(eval_kernel[k].cpu().t().numpy()) + eval_preds.append(torch.tensor(predict_k, dtype=self.kernel_dtype, device=eval_kernel.device)) + eval_preds = torch.stack(eval_preds, dim=1) + print(eval_preds, eval_targets) + + if eval_logits is not None and self.args.f0_scaling > 0: + eval_preds += eval_logits / self.args.f0_scaling + + eval_loss = self.loss(eval_preds, eval_targets) + return eval_loss, eval_preds + + +class SVCKernelSolver(BaseKernelSolver): + def __init__(self, args): + super().__init__(args) + + self.svms = None + + def fit(self, train_kernel, train_targets, train_logits=None): + self.num_labels = train_kernel.size(0) + self.kernel_dtype = train_kernel.dtype + assert self.num_labels == 1, "SVMKernelSolver only works for binary_classification" + assert train_logits is None, "SVMKernelSolver does not support train_logits" + + kernel = self.get_regularized_kernel(train_kernel) + train_targets = ((train_targets + 1) / 2).int() # convert back from {-1, 1} to {0, 1} + + self.svms = [] + for k in range(self.num_labels): + svm = SVC(kernel='precomputed') + svm.fit(kernel[k].cpu().numpy(), train_targets.cpu().numpy()) + self.svms.append(svm) + + def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs): + assert self.svms is not None, "Must call fit() before predict()" + assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()" + assert eval_logits is None, "SVMKernelSolver does not support train_logits" + + eval_preds = [] + for k in range(self.num_labels): + predict_k = self.svms[k].predict(eval_kernel[k].cpu().t().numpy()) + eval_preds.append(torch.tensor(predict_k, dtype=self.kernel_dtype, device=eval_kernel.device)) + eval_preds = torch.stack(eval_preds, dim=1) + + eval_preds = (eval_preds * 2 - 1) # convert back from {0, 1} to {-1, 1} + + eval_loss = self.loss(eval_preds, eval_targets) + return eval_loss, eval_preds + + +class LogisticKernelSolver(BaseKernelSolver): + def __init__(self, args): + super().__init__(args) + + self.logistic_model = None + + def fit(self, train_kernel, train_targets, train_logits=None): + self.num_labels = train_kernel.size(0) + self.kernel_dtype = train_kernel.dtype + assert self.num_labels == 1, "SVMKernelSolver only works for binary_classification" + + kernel = self.get_regularized_kernel(train_kernel).squeeze(0) + train_targets = ((train_targets + 1) / 2).int() # convert back from {-1, 1} to {0, 1} + + self.logistic_model = LogisticRegressionCV(max_iter=10000, random_state=0) + self.logistic_model.fit(kernel.cpu().numpy(), train_targets.cpu().numpy()) + + def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs): + assert self.logistic_model is not None, "Must call fit() before predict()" + assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()" + + log_proba = self.logistic_model.predict_log_proba(eval_kernel.cpu().squeeze().t().numpy()) + log_proba = torch.tensor(log_proba, dtype=self.kernel_dtype, device=eval_kernel.device) + + eval_loss = self.loss(log_proba, eval_targets) + + eval_preds = (log_proba[:,1] - log_proba[:,0]).unsqueeze(1) + + return eval_loss, eval_preds + + def loss(self, preds, targets): + targets = ((targets + 1) / 2).long() # convert back from {-1, 1} to {0, 1} + return F.cross_entropy(preds, targets).item() + + + +SOLVERS = { + "lstsq": LstsqKernelSolver, + "svr": SVRKernelSolver, + "svc": SVCKernelSolver, + "asym": AsymmetricLstsqKernelSolver, + "logistic": LogisticKernelSolver +} diff --git a/baselines/lozo/medium_models/src/kernel_trainer.py b/baselines/lozo/medium_models/src/kernel_trainer.py new file mode 100644 index 0000000..e62cd45 --- /dev/null +++ b/baselines/lozo/medium_models/src/kernel_trainer.py @@ -0,0 +1,471 @@ +########## The following part was originally copied from Transformers' trainer (3.4.0) and then changed heavily to compute eNTKs. ########## + +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +The trainer for computing eNTKs +""" + +import os +from typing import Any, Callable, Dict, List, Optional, Tuple, Union +import re + +import torch +import torch.nn as nn +from torch.utils.data.dataloader import DataLoader +from torch.utils.data.dataset import Dataset +from torch.utils.data.sampler import SequentialSampler + +from functorch import vmap, jvp, jacrev, make_functional_with_buffers + +import transformers +from transformers.data.data_collator import DataCollator +from transformers.file_utils import is_torch_tpu_available + +from transformers.modeling_utils import PreTrainedModel +from transformers.training_args import TrainingArguments +from transformers.trainer import SequentialDistributedSampler +from transformers.trainer_utils import PredictionOutput, EvalPrediction +from transformers.utils import logging +if is_torch_tpu_available(): + import torch_xla.core.xla_model as xm +import gc +from transformers.trainer_utils import TrainOutput + +from src.linearhead_trainer import varsize_tensor_all_gather, LinearHeadTrainer + +import numpy as np +from tqdm import tqdm +from src.kernel_solvers import SOLVERS + +logger = logging.get_logger(__name__) + + +class LogitModelWrapper(nn.Module): + def __init__(self, model, binary_classification): + super().__init__() + self.model = model + self.binary_classification = binary_classification + + def forward(self, input_ids, attention_mask, mask_pos): + logits = self.model(input_ids, attention_mask, mask_pos=mask_pos)[0] # don't provide labels + if self.binary_classification: + assert logits.size(1) == 2, "--binary_classification should have 2 logits" + logits = (logits[:,1] - logits[:,0]).unsqueeze(-1) + return logits + # label = (label * 2 - 1).float() # convert from {0, 1} to {-1, 1} + + +def param_to_buffer(module, module_name, predicate): + """Turns all parameters of a module into buffers.""" + modules = module.named_modules(prefix=str(module_name)) + next(modules) # Skip itself + + params = [] + for name, param in module.named_parameters(recurse=False, prefix=str(module_name)): + if predicate(name): + params.append((name.split(".")[-1], param)) + + for name, param in params: + delattr(module, name) # Unregister parameter + module.register_buffer(name, param) + for name, module in modules: + param_to_buffer(module, name, predicate) + + +class KernelTrainerFunc(LinearHeadTrainer): + """ + Adding some functions based on Transformers' Trainer class. + """ + + def __init__( + self, + model: PreTrainedModel, + args: TrainingArguments, + data_collator: Optional[DataCollator] = None, + train_dataset: Optional[Dataset] = None, + eval_dataset: Optional[Dataset] = None, + *posargs, + **kwargs + ): + super().__init__(model, args, data_collator, train_dataset, eval_dataset, *posargs, **kwargs) + + self.grad_dim = None + self.train_train_kernel = None + self.train_targets = None + self.num_labels = None + + self.kernel_formula = args.kernel_formula + + def convert_to_buffer(name): + if args.exclude_embeddings: + if "embed" in name: + logger.info("Excluding {}".format(name)) + return True + + if args.exclude_head: + if "head" in name: + logger.info("Excluding {}".format(name)) + return True + + if args.only_biases: + if "bias" not in name: + logger.info("Excluding {}".format(name)) + return True + + if args.exclude_first_layers != -1: + if 'layers' in name: + layer_num = re.search('layers.(.+?).[a-z]', name).group(1) + if int(layer_num) < args.exclude_first_layers: + return True + else: + return False + elif 'embed_tokens' in name or 'embed_positions' in name: + return True + + if model.model_args.apply_lora: + if name.startswith('roberta') and "lora" not in name: + logger.info("Excluding {}".format(name)) + return True + return False + + param_to_buffer(self.model, "", convert_to_buffer) + + + def get_unshuffled_dataloader(self, dataset: Optional[Dataset] = None, sharded: bool = False, batch_size: Optional[int] = -1): + if sharded and is_torch_tpu_available(): + sampler = SequentialDistributedSampler( + dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal() + ) + elif sharded and self.args.local_rank != -1: + sampler = SequentialDistributedSampler(dataset) + else: + sampler = SequentialSampler(dataset) + + bs = self.args.per_device_eval_batch_size if batch_size == -1 else batch_size + data_loader = DataLoader( + dataset, + sampler=sampler, + batch_size=bs, + collate_fn=self.data_collator, + drop_last=self.args.dataloader_drop_last, + ) + + return data_loader + + def profile_memory(self): + import gc + for obj in gc.get_objects(): + try: + if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_tensor(obj.data)): + print(type(obj), obj.size()) + except: + pass + + def compute_kernel_inner(self, curried_fn, curried_jacobian_fn, grads_outer, dataset_inner): + + # Use per_device_eval_batch_size for outer loop (which is always the training dataset + dataloader_inner = self.get_unshuffled_dataloader(dataset_inner, sharded=False, batch_size=self.args.per_device_eval_batch_size) + kernel_blocks = [] + targets_inner = [] + + for inputs_inner in tqdm(dataloader_inner, desc="Computing kernel inner"): + + for k, v in inputs_inner.items(): + if isinstance(v, torch.Tensor): + inputs_inner[k] = v.to(self.args.device) + + def get_ntk_slice(tangents): + _, jvps = curried_fn(inputs_inner.get("input_ids"), inputs_inner.get("attention_mask"), inputs_inner.get("mask_pos"), tangents) + return jvps + + if self.args.kernel_formula == "signgd": + grads_inner = curried_jacobian_fn(inputs_inner.get("input_ids"), inputs_inner.get("attention_mask"), inputs_inner.get("mask_pos")) + block = sum(torch.einsum('olw,ikw->olik', j1.sign().flatten(2).to(torch.float64), j2.sign().flatten(2).to(torch.float64)).cpu() for j1, j2 in zip(grads_outer, grads_inner)) + else: + block = vmap(vmap(get_ntk_slice))(grads_outer).to(torch.float64).cpu() # N_outer x C_outer x N_inner x C_inner + + kernel_blocks.append(block.detach()) + label = inputs_inner.get("labels") + if self.args.binary_classification: + label = (label * 2 - 1).float() # convert from {0, 1} to {-1, 1} + targets_inner.append(label) + + # del grads_inner + del block + del inputs_inner + + torch.cuda.empty_cache() + gc.collect() + + return ( + torch.cat(kernel_blocks, dim=2) if kernel_blocks else torch.tensor([]), + torch.cat(targets_inner, dim=0) if targets_inner else torch.tensor([]) + ) + + def compute_kernel_outer(self, dataset_outer, dataset_inner): + # Use train_batch_size for outer loop (which is always the training dataset) + dataloader_outer = self.get_unshuffled_dataloader(dataset_outer, sharded=True, batch_size=self.args.per_device_train_batch_size) + + model_wrapper = LogitModelWrapper(self.model, self.args.binary_classification) + model_wrapper.eval() + for param in model_wrapper.parameters(): + param.requires_grad_(True) + + model_fn, params, buffers = make_functional_with_buffers(model_wrapper) + + jacobian_fn = jacrev(model_fn) + + def curried_jacobian_fn(input_ids, attention_mask, mask_pos): + return jacobian_fn(params, buffers, input_ids, attention_mask, mask_pos) + + def curried_fn(input_ids, attention_mask, mask_pos, tangent): + def curried_model_fn(params_): + return model_fn(params_, buffers, input_ids, attention_mask, mask_pos) + return jvp(curried_model_fn, (params,), (tangent,)) + + kernel_rows = [] + + inner_targets = None + + for inputs_outer in tqdm(dataloader_outer, desc="Computing kernel outer"): + for k, v in inputs_outer.items(): + if isinstance(v, torch.Tensor): + inputs_outer[k] = v.to(self.args.device) + + grads_outer = curried_jacobian_fn(inputs_outer.get("input_ids"), inputs_outer.get("attention_mask"), inputs_outer.get("mask_pos")) + if self.args.kernel_formula == 'asymmetric_signgd': + grads_outer = tuple(g.sign() for g in grads_outer) + + # assert len(tuple(model_wrapper.model.named_parameters())) == len(grads_outer) + + # for (name,param), grad in zip(model_wrapper.named_parameters(), grads_outer): + # print(name, grad[(grad != 0).all(-1)]) + # assert param.shape == grad.shape[2:], f"{name} {param.shape} {grad[2:].shape}" + # if (grad == 0).all(): + # print(name, param.numel()) + + if self.grad_dim is None: + self.grad_dim = sum(np.prod(x.shape[2:]) for x in grads_outer) + # assert self.grad_dim == num_params, "gradient dim not constant: {} and {}".format(self.grad_dim, num_params) + + kernel_blocks, inner_targets = ( + self.compute_kernel_inner(curried_fn, curried_jacobian_fn, grads_outer, dataset_inner)) + + kernel_rows.append(kernel_blocks) + + del grads_outer + del inputs_outer + del kernel_blocks + + torch.cuda.empty_cache() + gc.collect() + + + kernel = torch.cat(kernel_rows, dim=0) + + return ( + kernel, + inner_targets + ) + + def compute_kernel_sharded(self, dataset_outer, dataset_inner): + assert self.kernel_formula in ["sgd", "asymmetric_signgd", "signgd"], "only sgd and asymmetric_signgd are supported by torchfunc for now" + + with torch.no_grad(): + kernel, inner_targets = self.compute_kernel_outer(dataset_outer, dataset_inner) + + if self.args.local_rank != -1: + logger.info("Starting to gather kernel across GPUs") + kernel = varsize_tensor_all_gather(kernel.to(self.args.device), torch.distributed.get_world_size()) + logger.info("Finished gathering kernel across GPUs") + + return kernel, inner_targets + + def compute_model_logits_cached(self, eval_dataset): + if self.args.load_kernels is not None: + output_dir = self.args.load_kernels + else: + output_dir = self.args.output_dir + logit_file_name = f"{eval_dataset.mode}_logits_{eval_dataset.task_name}.pt" + logit_path = os.path.join(output_dir, logit_file_name) + + if os.path.exists(logit_path) and not self.args.overwrite_kernels: + logger.info(f"Starting to load logits from {logit_path}.") + logits, targets = torch.load(logit_path) + logger.info(f"Finished loading logits from {logit_path}.") + else: + logger.info(f"Starting to compute the {eval_dataset.mode} logits.") + dataloader = self.get_unshuffled_dataloader(eval_dataset) + + model_wrapper = LogitModelWrapper(self.model, self.args.binary_classification) + model_wrapper.eval() + + logits = [] + targets = [] + with torch.no_grad(): + for inputs in dataloader: + for k, v in inputs.items(): + if isinstance(v, torch.Tensor): + inputs[k] = v.to(self.args.device) + + label = inputs.get("labels") + if self.args.binary_classification: + label = (label * 2 - 1).float() # convert from {0, 1} to {-1, 1} + + preds = model_wrapper(inputs.get("input_ids"), inputs.get("attention_mask"), inputs.get("mask_pos")) + logits.append(preds.detach().cpu()) + targets.append(label.cpu()) + + logits = torch.cat(logits, dim=0) + targets = torch.cat(targets, dim=0) + + logger.info(f"Finished computing the {eval_dataset.mode} logits.") + + if self.is_world_process_zero(): + torch.save((logits, targets), logit_path) + return logits, targets + + def reshape_kernel_and_targets(self, kernel, targets): + # reshape kernel to previous format + if self.num_labels is None: + self.num_labels = kernel.shape[1] + assert self.num_labels == kernel.shape[1], "label dim not constant: {} and {}".format(self.num_labels, kernel.shape[1]) + assert self.num_labels == kernel.shape[3], "label dim not constant: {} and {}".format(self.num_labels, kernel.shape[3]) + + if self.num_labels > 1: # multi logit + targets = torch.nn.functional.one_hot(targets.squeeze(), self.num_labels) + + size1 = kernel.shape[0] * kernel.shape[1] + size2 = kernel.shape[2] * kernel.shape[3] + # kernel = kernel.transpose(0, 1).transpose(2, 3) + return kernel.reshape(1, size1, size2), targets.reshape(-1) + + def compute_kernel_cached(self, eval_dataset): + kernel_file_name = f"{eval_dataset.mode}_kernels_{eval_dataset.task_name}.pt" + kernel_path = os.path.join(self.args.output_dir, kernel_file_name) + + if os.path.exists(kernel_path) and not self.args.overwrite_kernels: + logger.info(f"Starting to load kernels from {kernel_path}.") + (train_eval_kernel, eval_targets) = torch.load(kernel_path) + logger.info(f"Finished loading kernels from {kernel_path}.") + else: + logger.info(f"Starting to compute the train-{eval_dataset.mode} kernel.") + train_eval_kernel, eval_targets = self.compute_kernel_sharded( + self.train_dataset, eval_dataset, + ) + logger.info(f"Finshed computing the train-{eval_dataset.mode} kernel.") + + train_eval_kernel = train_eval_kernel.cpu() + eval_targets = eval_targets.cpu() + + if self.args.kernel_formula == 'asymmetric_signgd': + logger.info(f"Starting to compute the flipped train-{eval_dataset.mode} kernel.") + if eval_dataset == self.train_dataset: + train_eval_kernel_flipped = train_eval_kernel + else: + train_eval_kernel_flipped, _ = self.compute_kernel_sharded( + eval_dataset, self.train_dataset, + ) + logger.info(f"Finshed computing the flipped train-{eval_dataset.mode} kernel.") + + train_eval_kernel_flipped = train_eval_kernel_flipped.cpu() + train_eval_kernel_flipped = train_eval_kernel_flipped.permute(2, 3, 0, 1) + train_eval_kernel = torch.stack([train_eval_kernel, train_eval_kernel_flipped], dim=0) + + if self.is_world_process_zero(): + torch.save((train_eval_kernel, eval_targets), kernel_path) + return train_eval_kernel, eval_targets + + + def train(self, model_path=None, dev_objective=None): + if self.args.from_linearhead and model_path is None: + super().train(model_path, dev_objective) # Train output layer using LinearHeadTrainer + + if self.args.load_kernels is None: + eval_dataset = self.train_dataset + self.train_train_kernel, self.train_targets = self.compute_kernel_cached(eval_dataset) + + return TrainOutput(0, 0.0, {}), None + + def evaluate(self, eval_dataset: Optional[Dataset] = None) -> Dict[str, float]: + if eval_dataset is None: + eval_dataset = self.eval_dataset + + if self.args.load_kernels is not None: + logger.info(f"Starting to load kernels from {self.args.load_kernels}.") + kernel_file_name = f"{eval_dataset.mode}_kernels_{eval_dataset.task_name}.pt" + load_kernel_path = os.path.join(self.args.load_kernels, kernel_file_name) + (train_eval_kernel, eval_targets) = torch.load(load_kernel_path) + + kernel_file_name = f"{self.train_dataset.mode}_kernels_{self.train_dataset.task_name}.pt" + load_kernel_path = os.path.join(self.args.load_kernels, kernel_file_name) + (self.train_train_kernel, self.train_targets) = torch.load(load_kernel_path) + logger.info(f"Finished loading kernels from {self.args.load_kernels}.") + else: + assert self.train_train_kernel is not None, "train_train_kernel is None, did you forget to call train()?" + train_eval_kernel, eval_targets = self.compute_kernel_cached(eval_dataset) + + if self.args.kernel_formula == 'asymmetric_signgd': + train_eval_kernel_flipped = train_eval_kernel[1] + train_eval_kernel_flipped, _ = self.reshape_kernel_and_targets(train_eval_kernel_flipped, eval_targets) + + train_eval_kernel = train_eval_kernel[0] + train_train_kernel = self.train_train_kernel[0] + else: + train_eval_kernel_flipped = None + train_train_kernel = self.train_train_kernel + + train_train_kernel, train_targets = self.reshape_kernel_and_targets(train_train_kernel, self.train_targets) + train_eval_kernel, eval_targets = self.reshape_kernel_and_targets(train_eval_kernel, eval_targets) + + # get train and test logits + if self.args.adjust_for_init: + train_logits, _ = self.compute_model_logits_cached(self.train_dataset) + eval_logits, _ = self.compute_model_logits_cached(eval_dataset) + train_logits = train_logits.reshape(-1, 1) + eval_logits = eval_logits.reshape(-1, 1) + else: + train_logits, eval_logits = None, None + + metrics = {} + + solver = SOLVERS[self.args.kernel_solver](self.args) + solver.fit(train_train_kernel, train_targets, train_logits) + eval_error, eval_preds = solver.predict(train_eval_kernel, eval_targets, eval_logits, eval_kernel_flipped=train_eval_kernel_flipped) + eval_preds = eval_preds.reshape(-1, self.num_labels) + if self.num_labels > 1: + eval_targets = eval_targets.reshape(-1, self.num_labels).argmax(-1) + + if self.args.binary_classification: # Make sure to compute loss before this transformation! + eval_preds = torch.cat([-eval_preds, eval_preds], dim=-1) # convert back to two logits + eval_targets = ((eval_targets + 1) / 2).long() # convert back from {-1, 1} to {0, 1} + + if self.compute_metrics is not None: + metrics = self.compute_metrics(EvalPrediction(predictions=eval_preds.numpy(), label_ids=eval_targets.numpy())) + + # Prefix all keys with eval_ + for key in list(metrics.keys()): + if not key.startswith("eval_"): + metrics[f"eval_{key}"] = metrics.pop(key) + metrics["eval_loss"] = eval_error + + metrics.update(solver.metrics()) + metrics["grad_dim"] = self.grad_dim + + output = PredictionOutput(predictions=eval_preds.numpy(), label_ids=eval_targets.numpy(), metrics=metrics) + self.log(output.metrics) + + return output diff --git a/baselines/lozo/medium_models/src/linearhead_trainer.py b/baselines/lozo/medium_models/src/linearhead_trainer.py new file mode 100644 index 0000000..45905bc --- /dev/null +++ b/baselines/lozo/medium_models/src/linearhead_trainer.py @@ -0,0 +1,232 @@ +########## The following part was originally copied from Transformers' trainer (3.4.0) and then changed heavily for linear head probing. ########## + +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +A trainer for finding linear probing solutions +""" + +import collections +from src.models import MODEL_TYPES +import torch +import torch.nn.functional as F +from typing import Any, Callable, Dict, List, Optional, Tuple, Union +from sklearn.linear_model import LinearRegression, LogisticRegression, LogisticRegressionCV + +import transformers +from torch.utils.data.dataset import Dataset +from transformers.trainer_utils import TrainOutput +from transformers.utils import logging + +logger = logging.get_logger(__name__) + + +def tensor_all_gather(tensor: torch.Tensor, distributed_world_size: int): + tensor_list = [torch.zeros_like(tensor) for _ in range(distributed_world_size)] + torch.distributed.all_gather(tensor_list=tensor_list, tensor=tensor) + return torch.cat(tensor_list, dim=0) + + +def varsize_tensor_all_gather(tensor: torch.Tensor, distributed_world_size: int): + tensor = tensor.contiguous() + + dim_tensor = torch.tensor([tensor.size(0)], dtype=torch.int64, device=tensor.device) + dim_tensor = tensor_all_gather(dim_tensor, distributed_world_size).cpu() + max_size = dim_tensor.max() + + padded = torch.empty(max_size, *tensor.shape[1:], + dtype=tensor.dtype, + device=tensor.device) + padded[:tensor.shape[0]] = tensor + + ag = tensor_all_gather(padded, distributed_world_size) + slices = [] + for i, sz in enumerate(dim_tensor): + start_idx = i * max_size + end_idx = start_idx + sz.item() + + if end_idx > start_idx: + slices.append(ag[start_idx:end_idx]) + + return torch.cat(slices, dim=0) + +def get_token_prediction_layer(model): + if isinstance(model, tuple(MODEL_TYPES.values())): + if model.label_word_list is not None: + lm_head = model.get_lm_head_fn() + if model.model_type == "roberta": + return lm_head.decoder + elif model.model_type == "bert": + return lm_head.predictions.decoder + elif model.model_type == "gpt2" or model.model_type == 'opt': + return lm_head # TODO: has no bias so linear regression with bias will fail right now + else: + return model.classifier + elif isinstance(model, transformers.RobertaForSequenceClassification): + return model.classifier.out_proj + elif isinstance(model, transformers.BertForSequenceClassification): + return model.classifier + else: + raise NotImplementedError(model.__class__) + +def extract_features(model, *args, **kwargs): + """some magic for getting features pre last layer""" + features = {} + def hook(model_, input_, output_): + features["features"] = input_[0].detach() + + get_token_prediction_layer(model).register_forward_hook(hook) + model.forward(*args, **kwargs) + return features["features"] + +def extract_features_prob(model, *args, **kwargs): + """some magic for getting all logits""" + output = model.forward(*args, **kwargs) + return F.softmax(output[1].detach(), -1) + + + +class LinearHeadTrainer(transformers.Trainer): + """ + Adding some functions based on Transformers' Trainer class. + """ + + def train(self, model_path=None, dev_objective=None): + """ + Main training entry point. + + The training logic is directly borrowed from transformers.Trainer (version 3.0.2). + Add early stopping. + """ + self.best_dir = None + self.objective = -float("inf") + + model = self.model + model.eval() + + train_dataloader = self.get_train_dataloader() + targets = [] + features = [] + + logger.info("Starting to get features for training dataset") + with torch.no_grad(): + for step, inputs in enumerate(train_dataloader): + for k, v in inputs.items(): + if isinstance(v, torch.Tensor): + inputs[k] = v.to(self.args.device) + if self.args.prob_as_feature: + features.append(extract_features_prob(model, **inputs)) + else: + features.append(extract_features(model, **inputs)) + targets.append(inputs["labels"]) + logger.info("Finished getting features for training dataset") + + features = torch.cat(features, dim=0) + targets = torch.cat(targets, dim=0) + + if self.args.local_rank != -1: + logger.info("Starting to gather features across workers") + features = varsize_tensor_all_gather(features, torch.distributed.get_world_size()) + targets = varsize_tensor_all_gather(targets, torch.distributed.get_world_size()) + logger.info("Finished gathering features across workers") + + features = features.cpu() + targets = targets.cpu() + + if model.num_labels == 1: # Regression + targets_coords = targets.squeeze().unsqueeze(-1).float() + reg = LinearRegression().fit(features.numpy(), targets_coords.numpy()) + else: + use_bias = (model.model_type != 'opt' and model.model_type != 'gpt2') or self.args.prob_as_feature + tol = 0.01 if self.args.lp_early_stopping else 1e-4 # 1e-4 is scipy default + max_iter = 1000 if self.args.lp_early_stopping else 5000 + reg = LogisticRegressionCV(max_iter=max_iter, fit_intercept=use_bias, multi_class="multinomial", random_state=0, tol=tol).fit(features.numpy(), targets.numpy()) + # targets_coords = torch.nn.functional.one_hot(targets.squeeze(), model.num_labels).float() + + logger.info("Fitting linear regression") + + logger.info("Assigning weights to model") + # print(head.out_proj.weight.shape, head.out_proj.bias.shape) + # print(reg.coef_.shape, reg.intercept_.shape) + decoder = get_token_prediction_layer(model) + coef_torch = torch.tensor(reg.coef_, device=decoder.weight.device, dtype=decoder.weight.dtype) + if use_bias: + bias_torch = torch.tensor(reg.intercept_, device=decoder.weight.device, dtype=decoder.weight.dtype) + + if model.num_labels == 2 and coef_torch.size(0) == 1: + coef_torch = torch.cat([-coef_torch / 2, coef_torch / 2], dim=0) + if use_bias: + bias_torch = torch.cat([-bias_torch / 2, bias_torch / 2], dim=0) + + if decoder.weight.shape[0] == model.num_labels: + decoder.weight.data = coef_torch + if use_bias: + decoder.bias.data = bias_torch + else: + if self.args.prob_as_feature: + model.lr_weight = coef_torch + if use_bias: + model.lr_bias = bias_torch + else: + decoder.weight.data[model.label_word_list,:] = coef_torch + if use_bias: + decoder.bias.data[model.label_word_list] = bias_torch + + if model.num_labels == 1: # Regression + logits = torch.tensor(reg.predict(features.numpy())) + train_loss = torch.nn.functional.mse_loss(logits, targets_coords, reduction="none") + else: + logits = torch.tensor(reg.predict_log_proba(features.numpy())) + train_loss = torch.nn.functional.cross_entropy(logits, targets.squeeze(), reduction="none") + + return TrainOutput(0, train_loss, {}), self.objective + + + + """ + Difference compared to original implementation: return output instead of output.metrics (so there is also the logits) + """ + def evaluate(self, eval_dataset: Optional[Dataset] = None) -> Dict[str, float]: + """ + Run evaluation and returns metrics. + + The calling script will be responsible for providing a method to compute metrics, as they are + task-dependent (pass it to the init :obj:`compute_metrics` argument). + + You can also subclass and override this method to inject custom behavior. + + Args: + eval_dataset (:obj:`Dataset`, `optional`): + Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, + columns not accepted by the ``model.forward()`` method are automatically removed. It must implement + the :obj:`__len__` method. + + Returns: + A dictionary containing the evaluation loss and the potential metrics computed from the predictions. + """ + if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): + raise ValueError("eval_dataset must implement __len__") + + eval_dataloader = self.get_eval_dataloader(eval_dataset) + + output = self.prediction_loop(eval_dataloader, description="Evaluation") + + self.log(output.metrics) + + if self.args.tpu_metrics_debug or self.args.debug: + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + + return output diff --git a/baselines/lozo/medium_models/src/modeling_opt.py b/baselines/lozo/medium_models/src/modeling_opt.py new file mode 100644 index 0000000..5fb5551 --- /dev/null +++ b/baselines/lozo/medium_models/src/modeling_opt.py @@ -0,0 +1,1385 @@ +# coding=utf-8 +# Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" PyTorch OPT model.""" +import random +from typing import List, Optional, Tuple, Union + +import torch +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +from transformers.activations import ACT2FN +from transformers.modeling_outputs import ( + BaseModelOutputWithPast, + CausalLMOutputWithPast, + QuestionAnsweringModelOutput, + SequenceClassifierOutputWithPast, +) +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import ( + add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, + logging, + replace_return_docstrings, +) +#from .configuration_opt import OPTConfig + +import loralib as lora + + +logger = logging.get_logger(__name__) + +_CHECKPOINT_FOR_DOC = "facebook/opt-350m" +_CONFIG_FOR_DOC = "OPTConfig" +_TOKENIZER_FOR_DOC = "GPT2Tokenizer" + +# Base model docstring +_EXPECTED_OUTPUT_SHAPE = [1, 8, 1024] + +# SequenceClassification docstring +_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ArthurZ/opt-350m-dummy-sc" +_SEQ_CLASS_EXPECTED_LOSS = 1.71 +_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_0'" + +OPT_PRETRAINED_MODEL_ARCHIVE_LIST = [ + "facebook/opt-125m", + "facebook/opt-350m", + "facebook/opt-1.3b", + "facebook/opt-2.7b", + "facebook/opt-6.7b", + "facebook/opt-13b", + "facebook/opt-30b", + # See all OPT models at https://huggingface.co/models?filter=opt +] + +from transformers import PretrainedConfig +class OPTConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`OPTModel`]. It is used to instantiate a OPT model + according to the specified arguments, defining the model architecture. Instantiating a configuration with the + defaults will yield a similar configuration to that of the OPT + [facebook/opt-350m](https://huggingface.co/facebook/opt-350m) architecture. + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + + Args: + vocab_size (`int`, *optional*, defaults to 50272): + Vocabulary size of the OPT model. Defines the number of different tokens that can be represented by the + `inputs_ids` passed when calling [`OPTModel`] + hidden_size (`int`, *optional*, defaults to 768): + Dimensionality of the layers and the pooler layer. + num_hidden_layers (`int`, *optional*, defaults to 12): + Number of decoder layers. + ffn_dim (`int`, *optional*, defaults to 3072): + Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. + num_attention_heads (`int`, *optional*, defaults to 12): + Number of attention heads for each attention layer in the Transformer decoder. + activation_function (`str` or `function`, *optional*, defaults to `"relu"`): + The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, + `"relu"`, `"silu"` and `"gelu_new"` are supported. + max_position_embeddings (`int`, *optional*, defaults to 2048): + The maximum sequence length that this model might ever be used with. Typically set this to something large + just in case (e.g., 512 or 1024 or 2048). + do_layer_norm_before (`bool`, *optional*, defaults to `True`): + Whether to perform layer normalization before the attention block. + word_embed_proj_dim (`int`, *optional*): + `word_embed_proj_dim` can be set to down-project word embeddings, *e.g.* `opt-350m`. Defaults to + `hidden_size`. + dropout (`float`, *optional*, defaults to 0.1): + The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. + attention_dropout (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + layerdrop: (`float`, *optional*, defaults to 0.0): + The LayerDrop probability. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more + details. + init_std (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + use_cache (`bool`, *optional*, defaults to `True`): + Whether or not the model should return the last key/values attentions (not used by all models). + + Example: + + ```python + >>> from transformers import OPTConfig, OPTModel + + >>> # Initializing a OPT facebook/opt-large style configuration + >>> configuration = OPTConfig() + + >>> # Initializing a model (with random weights) from the facebook/opt-large style configuration + >>> model = OPTModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + model_type = "opt" + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + vocab_size=50272, + hidden_size=768, + num_hidden_layers=12, + ffn_dim=3072, + max_position_embeddings=2048, + do_layer_norm_before=True, + _remove_final_layer_norm=False, + word_embed_proj_dim=None, + dropout=0.1, + attention_dropout=0.0, + num_attention_heads=12, + activation_function="relu", + layerdrop=0.0, + init_std=0.02, + use_cache=True, + pad_token_id=1, + bos_token_id=2, + eos_token_id=2, + apply_lora=False, + lora_r=None, + lora_alpha=None, + **kwargs + ): + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + **kwargs, + ) + self.vocab_size = vocab_size + self.max_position_embeddings = max_position_embeddings + self.num_attention_heads = num_attention_heads + self.word_embed_proj_dim = word_embed_proj_dim if word_embed_proj_dim is not None else hidden_size + self.ffn_dim = ffn_dim + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.dropout = dropout + self.attention_dropout = attention_dropout + self.activation_function = activation_function + self.init_std = init_std + self.layerdrop = layerdrop + self.use_cache = use_cache + self.do_layer_norm_before = do_layer_norm_before + + self.apply_lora = apply_lora + self.lora_r = lora_r + self.lora_alpha = lora_alpha + + # Note that the only purpose of `_remove_final_layer_norm` is to keep backward compatibility + # with checkpoints that have been fine-tuned before transformers v4.20.1 + # see https://github.com/facebookresearch/metaseq/pull/164 + self._remove_final_layer_norm = _remove_final_layer_norm + + + +def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0): + """ + Make causal mask used for bi-directional self-attention. + """ + bsz, tgt_len = input_ids_shape + mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min)) + mask_cond = torch.arange(mask.size(-1)) + mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) + mask = mask.to(dtype) + + if past_key_values_length > 0: + mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1) + return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) + + +def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + bsz, src_len = mask.size() + tgt_len = tgt_len if tgt_len is not None else src_len + + expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) + + inverted_mask = 1.0 - expanded_mask + + return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) + + +class OPTLearnedPositionalEmbedding(nn.Embedding): + """ + This module learns positional embeddings up to a fixed maximum size. + """ + + def __init__(self, num_embeddings: int, embedding_dim: int): + # OPT is set up so that if padding_idx is specified then offset the embedding ids by 2 + # and adjust num_embeddings appropriately. Other models don't have this hack + self.offset = 2 + super().__init__(num_embeddings + self.offset, embedding_dim) + + def forward(self, attention_mask: torch.LongTensor, past_key_values_length: int = 0): + """`input_ids_shape` is expected to be [bsz x seqlen].""" + attention_mask = attention_mask.long() + + # create positions depending on attention_mask + positions = (torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask).long() - 1 + + # cut positions if `past_key_values_length` is > 0 + positions = positions[:, past_key_values_length:] + + return super().forward(positions + self.offset) + + +class OPTAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__( + self, + embed_dim: int, + num_heads: int, + dropout: float = 0.0, + is_decoder: bool = False, + bias: bool = True, + apply_lora: bool = False, + lora_r: int = None, + lora_alpha: int = None + ): + super().__init__() + self.embed_dim = embed_dim + self.num_heads = num_heads + self.dropout = dropout + self.head_dim = embed_dim // num_heads + + if (self.head_dim * num_heads) != self.embed_dim: + raise ValueError( + f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" + f" and `num_heads`: {num_heads})." + ) + self.scaling = self.head_dim**-0.5 + self.is_decoder = is_decoder + + if apply_lora: + self.q_proj = lora.Linear(embed_dim, embed_dim, lora_r, lora_alpha=lora_alpha, bias=bias) + else: + self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + if apply_lora: + self.v_proj = lora.Linear(embed_dim, embed_dim, lora_r, lora_alpha=lora_alpha, bias=bias) + else: + self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + # original OPT code + #self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + #self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + #self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def forward( + self, + hidden_states: torch.Tensor, + key_value_states: Optional[torch.Tensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + """Input shape: Batch x Time x Channel""" + + # if key_value_states are provided this layer is used as a cross-attention layer + # for the decoder + is_cross_attention = key_value_states is not None + + bsz, tgt_len, _ = hidden_states.size() + + # get query proj + query_states = self.q_proj(hidden_states) * self.scaling + # get key, value proj + if is_cross_attention and past_key_value is not None: + # reuse k,v, cross_attentions + key_states = past_key_value[0] + value_states = past_key_value[1] + elif is_cross_attention: + # cross_attentions + key_states = self._shape(self.k_proj(key_value_states), -1, bsz) + value_states = self._shape(self.v_proj(key_value_states), -1, bsz) + elif past_key_value is not None: + # reuse k, v, self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + else: + # self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + + if self.is_decoder: + # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. + # Further calls to cross_attention layer can then reuse all cross-attention + # key/value_states (first "if" case) + # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of + # all previous decoder key/value_states. Further calls to uni-directional self-attention + # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) + # if encoder bi-directional self-attention `past_key_value` is always `None` + past_key_value = (key_states, value_states) + + proj_shape = (bsz * self.num_heads, -1, self.head_dim) + query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape) + key_states = key_states.view(*proj_shape) + value_states = value_states.view(*proj_shape) + + src_len = key_states.size(1) + attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) + + if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len): + raise ValueError( + f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, tgt_len, src_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" + ) + attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask + attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437 + if attn_weights.dtype == torch.float16: + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16) + else: + attn_weights = nn.functional.softmax(attn_weights, dim=-1) + + if layer_head_mask is not None: + if layer_head_mask.size() != (self.num_heads,): + raise ValueError( + f"Head mask for a single layer should be of size {(self.num_heads,)}, but is" + f" {layer_head_mask.size()}" + ) + attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + if output_attentions: + # this operation is a bit awkward, but it's required to + # make sure that attn_weights keeps its gradient. + # In order to do so, attn_weights have to be reshaped + # twice and have to be reused in the following + attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len) + else: + attn_weights_reshaped = None + + attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) + + attn_output = torch.bmm(attn_probs, value_states) + + if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) + attn_output = attn_output.transpose(1, 2) + + # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be + # partitioned aross GPUs when using tensor-parallelism. + attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) + + attn_output = self.out_proj(attn_output) + + return attn_output, attn_weights_reshaped, past_key_value + + +class OPTDecoderLayer(nn.Module): + def __init__(self, config: OPTConfig): + super().__init__() + self.embed_dim = config.hidden_size + self.self_attn = OPTAttention( + embed_dim=self.embed_dim, + num_heads=config.num_attention_heads, + dropout=config.attention_dropout, + is_decoder=True, + apply_lora=config.apply_lora, + lora_r=config.lora_r, + lora_alpha=config.lora_alpha + ) + self.do_layer_norm_before = config.do_layer_norm_before + self.dropout = config.dropout + self.activation_fn = ACT2FN[config.activation_function] + + self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) + self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim) + self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim) + self.final_layer_norm = nn.LayerNorm(self.embed_dim) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size + `(encoder_attention_heads,)`. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + past_key_value=past_key_value, + attention_mask=attention_mask, + layer_head_mask=layer_head_mask, + output_attentions=output_attentions, + ) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + hidden_states = residual + hidden_states + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Fully Connected + hidden_states_shape = hidden_states.shape + hidden_states = hidden_states.reshape(-1, hidden_states.size(-1)) + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + hidden_states = self.fc1(hidden_states) + hidden_states = self.activation_fn(hidden_states) + + hidden_states = self.fc2(hidden_states) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + + hidden_states = (residual + hidden_states).view(hidden_states_shape) + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +OPT_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`OPTConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTPreTrainedModel(PreTrainedModel): + + config_class = OPTConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["OPTDecoderLayer"] + _keys_to_ignore_on_load_unexpected = [r"decoder\.version"] + + def _init_weights(self, module): + std = self.config.init_std + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, (OPTDecoder)): + module.gradient_checkpointing = value + + +OPT_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`GPT2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`OPTTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape + `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape + `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +class OPTDecoder(OPTPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`] + + Args: + config: OPTConfig + """ + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.dropout = config.dropout + self.layerdrop = config.layerdrop + self.padding_idx = config.pad_token_id + self.max_target_positions = config.max_position_embeddings + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.word_embed_proj_dim, self.padding_idx) + self.embed_positions = OPTLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size) + + if config.word_embed_proj_dim != config.hidden_size: + self.project_out = nn.Linear(config.hidden_size, config.word_embed_proj_dim, bias=False) + else: + self.project_out = None + + if config.word_embed_proj_dim != config.hidden_size: + self.project_in = nn.Linear(config.word_embed_proj_dim, config.hidden_size, bias=False) + else: + self.project_in = None + + # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility + # with checkpoints that have been fine-tuned before transformers v4.20.1 + # see https://github.com/facebookresearch/metaseq/pull/164 + if config.do_layer_norm_before and not config._remove_final_layer_norm: + self.final_layer_norm = nn.LayerNorm(config.hidden_size) + else: + self.final_layer_norm = None + + self.layers = nn.ModuleList([OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)]) + + self.gradient_checkpointing = False + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask + def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): + # create causal mask + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + combined_attention_mask = None + if input_shape[-1] > 1: + combined_attention_mask = _make_causal_mask( + input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length + ).to(inputs_embeds.device) + + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( + inputs_embeds.device + ) + combined_attention_mask = ( + expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask + ) + + return combined_attention_mask + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`OPTTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + """ + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + # embed positions + if attention_mask is None: + attention_mask = torch.ones(inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device) + pos_embeds = self.embed_positions(attention_mask, past_key_values_length) + + attention_mask = self._prepare_decoder_attention_mask( + attention_mask, input_shape, inputs_embeds, past_key_values_length + ) + + if self.project_in is not None: + inputs_embeds = self.project_in(inputs_embeds) + + hidden_states = inputs_embeds + pos_embeds + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + # check if head_mask has a correct number of layers specified if desired + for attn_mask, mask_name in zip([head_mask], ["head_mask"]): + if attn_mask is not None: + if attn_mask.size()[0] != (len(self.layers)): + raise ValueError( + f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" + f" {head_mask.size()[0]}." + ) + + for idx, decoder_layer in enumerate(self.layers): + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + if use_cache: + logger.warning( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + if self.final_layer_norm is not None: + hidden_states = self.final_layer_norm(hidden_states) + + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTModel(OPTPreTrainedModel): + def __init__(self, config: OPTConfig): + super().__init__(config) + self.decoder = OPTDecoder(config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.decoder.embed_tokens = value + + def get_decoder(self): + return self.decoder + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + processor_class=_TOKENIZER_FOR_DOC, + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=BaseModelOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_EXPECTED_OUTPUT_SHAPE, + ) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn) + decoder_outputs = self.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + if not return_dict: + return decoder_outputs + + return BaseModelOutputWithPast( + last_hidden_state=decoder_outputs.last_hidden_state, + past_key_values=decoder_outputs.past_key_values, + hidden_states=decoder_outputs.hidden_states, + attentions=decoder_outputs.attentions, + ) + + +class OPTForCausalLM(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = OPTModel(config) + + # the lm_head weight is automatically tied to the embed tokens weight + self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model.decoder = decoder + + def get_decoder(self): + return self.model.decoder + + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`OPTTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional + tensors are only required when the model is used as a decoder in a Sequence to Sequence model. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + + Returns: + + Example: + + ```python + >>> from transformers import GPT2Tokenizer, OPTForCausalLM + + >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m") + >>> tokenizer = GPT2Tokenizer.from_pretrained("facebook/opt-350m") + + >>> prompt = "Hey, are you consciours? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + outputs = self.model.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + logits = self.lm_head(outputs[0]).contiguous() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, use_cache=None, **kwargs): + # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly + if attention_mask is None: + attention_mask = input_ids.new_ones(input_ids.shape) + + if past: + input_ids = input_ids[:, -1:] + # first step, decoder_cached_states are empty + return { + "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed + "attention_mask": attention_mask, + "past_key_values": past, + "use_cache": use_cache, + } + + @staticmethod + def _reorder_cache(past, beam_idx): + reordered_past = () + for layer_past in past: + reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) + return reordered_past + + +@add_start_docstrings( + """ + The OPT Model transformer with a sequence classification head on top (linear layer). + + [`OPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + OPT_START_DOCSTRING, +) +class OPTForSequenceClassification(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.num_labels = config.num_labels + self.model = OPTModel(config) + self.score = nn.Linear(config.word_embed_proj_dim, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + processor_class=_TOKENIZER_FOR_DOC, + checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION, + output_type=SequenceClassifierOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_SEQ_CLASS_EXPECTED_OUTPUT, + expected_loss=_SEQ_CLASS_EXPECTED_LOSS, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size, sequence_length = input_ids.shape[:2] + else: + batch_size, sequence_length = inputs_embeds.shape[:2] + + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1 + else: + sequence_lengths = -1 + logger.warning( + f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " + "unexpected if using padding tokens in conjunction with `inputs_embeds.`" + ) + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + +@add_start_docstrings( + """ + The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD + (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + """, + OPT_START_DOCSTRING, +) +class OPTForQuestionAnswering(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.model = OPTModel(config) + self.qa_outputs = nn.Linear(config.word_embed_proj_dim, 2) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + start_positions: Optional[torch.LongTensor] = None, + end_positions: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, QuestionAnsweringModelOutput]: + r""" + start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + + Returns: + + Example: + + ```python + >>> from transformers import GPT2Tokenizer, OPTForQuestionAnswering + >>> import torch + + >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT + >>> tokenizer = GPT2Tokenizer.from_pretrained("facebook/opt-350m") + + >>> # note: we are loading a OPTForQuestionAnswering from the hub here, + >>> # so the head will be randomly initialized, hence the predictions will be random + >>> model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m") + + >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" + + >>> inputs = tokenizer(question, text, return_tensors="pt") + >>> with torch.no_grad(): + ... outputs = model(**inputs) + + >>> answer_start_index = outputs.start_logits.argmax() + >>> answer_end_index = outputs.end_logits.argmax() + + >>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] + >>> predicted = tokenizer.decode(predict_answer_tokens) + >>> predicted + ' Henson?' + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + + logits = self.qa_outputs(hidden_states) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + transformer_outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value diff --git a/baselines/lozo/medium_models/src/modeling_roberta.py b/baselines/lozo/medium_models/src/modeling_roberta.py new file mode 100644 index 0000000..ed8ef85 --- /dev/null +++ b/baselines/lozo/medium_models/src/modeling_roberta.py @@ -0,0 +1,1620 @@ +# coding=utf-8 +# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. +# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch RoBERTa model.""" + +import math +from typing import List, Optional, Tuple, Union + +import torch +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +from transformers.activations import ACT2FN, gelu +from transformers.modeling_outputs import ( + BaseModelOutputWithPastAndCrossAttentions, + BaseModelOutputWithPoolingAndCrossAttentions, + CausalLMOutputWithCrossAttentions, + MaskedLMOutput, + MultipleChoiceModelOutput, + QuestionAnsweringModelOutput, + SequenceClassifierOutput, + TokenClassifierOutput, +) +from transformers.modeling_utils import PreTrainedModel +from transformers.pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer +from transformers.utils import ( + add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, + logging, + replace_return_docstrings, +) +# from transformers.models.roberta.configuration_roberta import RobertaConfig + +import loralib as lora + +logger = logging.get_logger(__name__) + +_CHECKPOINT_FOR_DOC = "roberta-base" +_CONFIG_FOR_DOC = "RobertaConfig" + +ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST = [ + "roberta-base", + "roberta-large", + "roberta-large-mnli", + "distilroberta-base", + "roberta-base-openai-detector", + "roberta-large-openai-detector", + # See all RoBERTa models at https://huggingface.co/models?filter=roberta +] + +from transformers import BertConfig +class RobertaConfig(BertConfig): + r""" + This is the configuration class to store the configuration of a :class:`~transformers.RobertaModel` or a + :class:`~transformers.TFRobertaModel`. It is used to instantiate a RoBERTa model according to the specified + arguments, defining the model architecture. + Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used to control the model + outputs. Read the documentation from :class:`~transformers.PretrainedConfig` for more information. + The :class:`~transformers.RobertaConfig` class directly inherits :class:`~transformers.BertConfig`. It reuses the + same defaults. Please check the parent class for more information. + Examples:: + >>> from transformers import RobertaConfig, RobertaModel + >>> # Initializing a RoBERTa configuration + >>> configuration = RobertaConfig() + >>> # Initializing a model from the configuration + >>> model = RobertaModel(configuration) + >>> # Accessing the model configuration + >>> configuration = model.config + """ + model_type = "roberta" + + def __init__(self, pad_token_id=1, bos_token_id=0, eos_token_id=2, apply_lora=False, lora_r=None, lora_alpha=None, **kwargs): + """Constructs RobertaConfig.""" + super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs) + + self.apply_lora = apply_lora + self.lora_r = lora_r + self.lora_alpha = lora_alpha + +class RobertaEmbeddings(nn.Module): + """ + Same as BertEmbeddings with a tiny tweak for positional embeddings indexing. + """ + + # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__ + def __init__(self, config): + super().__init__() + self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) + self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) + self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) + + # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load + # any TensorFlow checkpoint file + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + # position_ids (1, len position emb) is contiguous in memory and exported when serialized + self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") + self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) + self.register_buffer( + "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False + ) + + # End copy + self.padding_idx = config.pad_token_id + self.position_embeddings = nn.Embedding( + config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx + ) + + def forward( + self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0 + ): + if position_ids is None: + if input_ids is not None: + # Create the position ids from the input token ids. Any padded tokens remain padded. + position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length) + else: + position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds) + + if input_ids is not None: + input_shape = input_ids.size() + else: + input_shape = inputs_embeds.size()[:-1] + + seq_length = input_shape[1] + + # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs + # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves + # issue #5664 + if token_type_ids is None: + if hasattr(self, "token_type_ids"): + buffered_token_type_ids = self.token_type_ids[:, :seq_length] + buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length) + token_type_ids = buffered_token_type_ids_expanded + else: + token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) + + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + token_type_embeddings = self.token_type_embeddings(token_type_ids) + + embeddings = inputs_embeds + token_type_embeddings + if self.position_embedding_type == "absolute": + position_embeddings = self.position_embeddings(position_ids) + embeddings += position_embeddings + embeddings = self.LayerNorm(embeddings) + embeddings = self.dropout(embeddings) + return embeddings + + def create_position_ids_from_inputs_embeds(self, inputs_embeds): + """ + We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids. + + Args: + inputs_embeds: torch.Tensor + + Returns: torch.Tensor + """ + input_shape = inputs_embeds.size()[:-1] + sequence_length = input_shape[1] + + position_ids = torch.arange( + self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device + ) + return position_ids.unsqueeze(0).expand(input_shape) + + +# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Roberta +class RobertaSelfAttention(nn.Module): + def __init__(self, config, position_embedding_type=None): + super().__init__() + if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): + raise ValueError( + f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " + f"heads ({config.num_attention_heads})" + ) + + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + if getattr(config, "apply_lora", False): + self.query = lora.Linear(config.hidden_size, self.all_head_size, config.lora_r, lora_alpha=config.lora_alpha) + else: + self.query = nn.Linear(config.hidden_size, self.all_head_size) + + self.key = nn.Linear(config.hidden_size, self.all_head_size) + + if getattr(config, "apply_lora", False): + self.value = lora.Linear(config.hidden_size, self.all_head_size, config.lora_r, lora_alpha=config.lora_alpha) + else: + self.value = nn.Linear(config.hidden_size, self.all_head_size) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.position_embedding_type = position_embedding_type or getattr( + config, "position_embedding_type", "absolute" + ) + if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": + self.max_position_embeddings = config.max_position_embeddings + self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) + + self.is_decoder = config.is_decoder + + def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor: + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + x = x.view(new_x_shape) + return x.permute(0, 2, 1, 3) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + output_attentions: Optional[bool] = False, + output_key_value: Optional[bool] = False, + ) -> Tuple[torch.Tensor]: + mixed_query_layer = self.query(hidden_states) + + # If this is instantiated as a cross-attention module, the keys + # and values come from an encoder; the attention mask needs to be + # such that the encoder's padding tokens are not attended to. + is_cross_attention = encoder_hidden_states is not None + if is_cross_attention and past_key_value is not None: + # reuse k,v, cross_attentions + key_layer = past_key_value[0] + value_layer = past_key_value[1] + attention_mask = encoder_attention_mask + elif is_cross_attention: + key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) + value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) + attention_mask = encoder_attention_mask + elif past_key_value is not None: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + key_layer = torch.cat([past_key_value[0], key_layer], dim=2) + value_layer = torch.cat([past_key_value[1], value_layer], dim=2) + else: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + + query_layer = self.transpose_for_scores(mixed_query_layer) + + use_cache = past_key_value is not None + if self.is_decoder or output_key_value: + # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. + # Further calls to cross_attention layer can then reuse all cross-attention + # key/value_states (first "if" case) + # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of + # all previous decoder key/value_states. Further calls to uni-directional self-attention + # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) + # if encoder bi-directional self-attention `past_key_value` is always `None` + past_key_value = (key_layer, value_layer) + + # Take the dot product between "query" and "key" to get the raw attention scores. + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + + if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": + query_length, key_length = query_layer.shape[2], key_layer.shape[2] + if use_cache: + position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view( + -1, 1 + ) + else: + position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) + position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1) + distance = position_ids_l - position_ids_r + + positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) + positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility + + if self.position_embedding_type == "relative_key": + relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) + attention_scores = attention_scores + relative_position_scores + elif self.position_embedding_type == "relative_key_query": + relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) + relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) + attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key + + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + if attention_mask is not None: + # Apply the attention mask is (precomputed for all layers in RobertaModel forward() function) + attention_scores = attention_scores + attention_mask + + # Normalize the attention scores to probabilities. + attention_probs = nn.functional.softmax(attention_scores, dim=-1) + + # This is actually dropping out entire tokens to attend to, which might + # seem a bit unusual, but is taken from the original Transformer paper. + attention_probs = self.dropout(attention_probs) + + # Mask heads if we want to + if head_mask is not None: + attention_probs = attention_probs * head_mask + + context_layer = torch.matmul(attention_probs, value_layer) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) + + if self.is_decoder or output_key_value: + outputs = outputs + (past_key_value,) + return outputs + + +# Copied from transformers.models.bert.modeling_bert.BertSelfOutput +class RobertaSelfOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Roberta +class RobertaAttention(nn.Module): + def __init__(self, config, position_embedding_type=None): + super().__init__() + self.self = RobertaSelfAttention(config, position_embedding_type=position_embedding_type) + self.output = RobertaSelfOutput(config) + self.pruned_heads = set() + + def prune_heads(self, heads): + if len(heads) == 0: + return + heads, index = find_pruneable_heads_and_indices( + heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads + ) + + # Prune linear layers + self.self.query = prune_linear_layer(self.self.query, index) + self.self.key = prune_linear_layer(self.self.key, index) + self.self.value = prune_linear_layer(self.self.value, index) + self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) + + # Update hyper params and store pruned heads + self.self.num_attention_heads = self.self.num_attention_heads - len(heads) + self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads + self.pruned_heads = self.pruned_heads.union(heads) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + output_attentions: Optional[bool] = False, + output_key_value: Optional[bool] = False, + ) -> Tuple[torch.Tensor]: + self_outputs = self.self( + hidden_states, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + output_key_value=output_key_value + ) + attention_output = self.output(self_outputs[0], hidden_states) + outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them + return outputs + + +# Copied from transformers.models.bert.modeling_bert.BertIntermediate +class RobertaIntermediate(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertOutput +class RobertaOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Roberta +class RobertaLayer(nn.Module): + def __init__(self, config): + super().__init__() + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = RobertaAttention(config) + self.is_decoder = config.is_decoder + self.add_cross_attention = config.add_cross_attention + if self.add_cross_attention: + if not self.is_decoder: + raise ValueError(f"{self} should be used as a decoder model if cross attention is added") + self.crossattention = RobertaAttention(config, position_embedding_type="absolute") + self.intermediate = RobertaIntermediate(config) + self.output = RobertaOutput(config) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + output_attentions: Optional[bool] = False, + output_key_value: Optional[bool] = False, + ) -> Tuple[torch.Tensor]: + # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 + self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None + self_attention_outputs = self.attention( + hidden_states, + attention_mask, + head_mask, + output_attentions=output_attentions, + past_key_value=self_attn_past_key_value, + output_key_value=output_key_value + ) + attention_output = self_attention_outputs[0] + + # if decoder, the last output is tuple of self-attn cache + if self.is_decoder or output_key_value: + outputs = self_attention_outputs[1:-1] + present_key_value = self_attention_outputs[-1] + else: + outputs = self_attention_outputs[1:] # add self attentions if we output attention weights + + cross_attn_present_key_value = None + if self.is_decoder and encoder_hidden_states is not None: + if not hasattr(self, "crossattention"): + raise ValueError( + f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers" + " by setting `config.add_cross_attention=True`" + ) + + # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple + cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None + cross_attention_outputs = self.crossattention( + attention_output, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + cross_attn_past_key_value, + output_attentions, + ) + attention_output = cross_attention_outputs[0] + outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights + + # add cross-attn cache to positions 3,4 of present_key_value tuple + cross_attn_present_key_value = cross_attention_outputs[-1] + present_key_value = present_key_value + cross_attn_present_key_value + + layer_output = apply_chunking_to_forward( + self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output + ) + outputs = (layer_output,) + outputs + + # if decoder, return the attn key/values as the last output + if self.is_decoder or output_key_value: + outputs = outputs + (present_key_value,) + + return outputs + + def feed_forward_chunk(self, attention_output): + intermediate_output = self.intermediate(attention_output) + layer_output = self.output(intermediate_output, attention_output) + return layer_output + + +# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Roberta +class RobertaEncoder(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.layer = nn.ModuleList([RobertaLayer(config) for _ in range(config.num_hidden_layers)]) + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = False, + output_hidden_states: Optional[bool] = False, + return_dict: Optional[bool] = True, + ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]: + all_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + next_decoder_cache = () if use_cache else None + for i, layer_module in enumerate(self.layer): + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + layer_head_mask = head_mask[i] if head_mask is not None else None + past_key_value = past_key_values[i] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs, past_key_value, output_attentions) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(layer_module), + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + ) + else: + layer_outputs = layer_module( + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + output_key_value=use_cache + ) + + hidden_states = layer_outputs[0] + if use_cache: + next_decoder_cache += (layer_outputs[-1],) + if output_attentions: + all_self_attentions = all_self_attentions + (layer_outputs[1],) + if self.config.add_cross_attention: + all_cross_attentions = all_cross_attentions + (layer_outputs[2],) + + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + if not return_dict: + return tuple( + v + for v in [ + hidden_states, + next_decoder_cache, + all_hidden_states, + all_self_attentions, + all_cross_attentions, + ] + if v is not None + ) + return BaseModelOutputWithPastAndCrossAttentions( + last_hidden_state=hidden_states, + past_key_values=next_decoder_cache, + hidden_states=all_hidden_states, + attentions=all_self_attentions, + cross_attentions=all_cross_attentions, + ) + + +# Copied from transformers.models.bert.modeling_bert.BertPooler +class RobertaPooler(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.activation = nn.Tanh() + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + # We "pool" the model by simply taking the hidden state corresponding + # to the first token. + first_token_tensor = hidden_states[:, 0] + pooled_output = self.dense(first_token_tensor) + pooled_output = self.activation(pooled_output) + return pooled_output + + +class RobertaPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = RobertaConfig + base_model_prefix = "roberta" + supports_gradient_checkpointing = True + _no_split_modules = [] + + # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights + def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, nn.Linear): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, RobertaEncoder): + module.gradient_checkpointing = value + + def update_keys_to_ignore(self, config, del_keys_to_ignore): + """Remove some keys from ignore list""" + if not config.tie_word_embeddings: + # must make a new list, or the class variable gets modified! + self._keys_to_ignore_on_save = [k for k in self._keys_to_ignore_on_save if k not in del_keys_to_ignore] + self._keys_to_ignore_on_load_missing = [ + k for k in self._keys_to_ignore_on_load_missing if k not in del_keys_to_ignore + ] + + +ROBERTA_START_DOCSTRING = r""" + + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`RobertaConfig`]): Model configuration class with all the parameters of the + model. Initializing with a config file does not load the weights associated with the model, only the + configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + +ROBERTA_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `({0})`): + Indices of input sequence tokens in the vocabulary. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*): + Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`: + + - 0 corresponds to a *sentence A* token, + - 1 corresponds to a *sentence B* token. + This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value + >= 2. All the value in this tensor should be always < type_vocab_size. + + [What are token type IDs?](../glossary#token-type-ids) + position_ids (`torch.LongTensor` of shape `({0})`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.max_position_embeddings - 1]`. + + [What are position IDs?](../glossary#position-ids) + head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): + Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +@add_start_docstrings( + "The bare RoBERTa Model transformer outputting raw hidden-states without any specific head on top.", + ROBERTA_START_DOCSTRING, +) +class RobertaModel(RobertaPreTrainedModel): + """ + + The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of + cross-attention is added between the self-attention layers, following the architecture described in *Attention is + all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz + Kaiser and Illia Polosukhin. + + To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set + to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and + `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass. + + .. _*Attention is all you need*: https://arxiv.org/abs/1706.03762 + + """ + + _keys_to_ignore_on_load_missing = [r"position_ids"] + + # Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with Bert->Roberta + def __init__(self, config, add_pooling_layer=True): + super().__init__(config) + self.config = config + + self.embeddings = RobertaEmbeddings(config) + self.encoder = RobertaEncoder(config) + + self.pooler = RobertaPooler(config) if add_pooling_layer else None + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embeddings.word_embeddings + + def set_input_embeddings(self, value): + self.embeddings.word_embeddings = value + + def _prune_heads(self, heads_to_prune): + """ + Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base + class PreTrainedModel + """ + for layer, heads in heads_to_prune.items(): + self.encoder.layer[layer].attention.prune_heads(heads) + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=BaseModelOutputWithPoolingAndCrossAttentions, + config_class=_CONFIG_FOR_DOC, + ) + # Copied from transformers.models.bert.modeling_bert.BertModel.forward + def forward( + self, + input_ids: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + token_type_ids: Optional[torch.Tensor] = None, + position_ids: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + inputs_embeds: Optional[torch.Tensor] = None, + encoder_hidden_states: Optional[torch.Tensor] = None, + encoder_attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]: + r""" + encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + """ + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # if self.config.is_decoder: + # use_cache = use_cache if use_cache is not None else self.config.use_cache + # else: + # use_cache = False + + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + batch_size, seq_length = input_shape + device = input_ids.device if input_ids is not None else inputs_embeds.device + + # past_key_values_length + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + + if attention_mask is None: + attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) + + if token_type_ids is None: + if hasattr(self.embeddings, "token_type_ids"): + buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length] + buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length) + token_type_ids = buffered_token_type_ids_expanded + else: + token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) + + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape) + + # If a 2D or 3D attention mask is provided for the cross-attention + # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] + if self.config.is_decoder and encoder_hidden_states is not None: + encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() + encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) + if encoder_attention_mask is None: + encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) + encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) + else: + encoder_extended_attention_mask = None + + # Prepare head mask if needed + # 1.0 in head_mask indicate we keep the head + # attention_probs has shape bsz x n_heads x N x N + # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] + # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] + head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) + + embedding_output = self.embeddings( + input_ids=input_ids, + position_ids=position_ids, + token_type_ids=token_type_ids, + inputs_embeds=inputs_embeds, + past_key_values_length=past_key_values_length, + ) + encoder_outputs = self.encoder( + embedding_output, + attention_mask=extended_attention_mask, + head_mask=head_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_extended_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + sequence_output = encoder_outputs[0] + pooled_output = self.pooler(sequence_output) if self.pooler is not None else None + + if not return_dict: + return (sequence_output, pooled_output) + encoder_outputs[1:] + + return BaseModelOutputWithPoolingAndCrossAttentions( + last_hidden_state=sequence_output, + pooler_output=pooled_output, + past_key_values=encoder_outputs.past_key_values, + hidden_states=encoder_outputs.hidden_states, + attentions=encoder_outputs.attentions, + cross_attentions=encoder_outputs.cross_attentions, + ) + + +@add_start_docstrings( + """RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.""", ROBERTA_START_DOCSTRING +) +class RobertaForCausalLM(RobertaPreTrainedModel): + _keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_unexpected = [r"pooler"] + + def __init__(self, config): + super().__init__(config) + + if not config.is_decoder: + logger.warning("If you want to use `RobertaLMHeadModel` as a standalone, add `is_decoder=True.`") + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.lm_head = RobertaLMHead(config) + + # The LM head weights require special treatment only when they are tied with the word embeddings + self.update_keys_to_ignore(config, ["lm_head.decoder.weight"]) + + # Initialize weights and apply final processing + self.post_init() + + def get_output_embeddings(self): + return self.lm_head.decoder + + def set_output_embeddings(self, new_embeddings): + self.lm_head.decoder = new_embeddings + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + past_key_values: Tuple[Tuple[torch.FloatTensor]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]: + r""" + encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in + `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are + ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` + past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, RobertaForCausalLM, AutoConfig + >>> import torch + + >>> tokenizer = AutoTokenizer.from_pretrained("roberta-base") + >>> config = AutoConfig.from_pretrained("roberta-base") + >>> config.is_decoder = True + >>> model = RobertaForCausalLM.from_pretrained("roberta-base", config=config) + + >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + >>> outputs = model(**inputs) + + >>> prediction_logits = outputs.logits + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + if labels is not None: + use_cache = False + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + sequence_output = outputs[0] + prediction_scores = self.lm_head(sequence_output) + + lm_loss = None + if labels is not None: + # we are doing next-token prediction; shift prediction scores and input ids by one + shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous() + labels = labels[:, 1:].contiguous() + loss_fct = CrossEntropyLoss() + lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) + + if not return_dict: + output = (prediction_scores,) + outputs[2:] + return ((lm_loss,) + output) if lm_loss is not None else output + + return CausalLMOutputWithCrossAttentions( + loss=lm_loss, + logits=prediction_scores, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + cross_attentions=outputs.cross_attentions, + ) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs): + input_shape = input_ids.shape + # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly + if attention_mask is None: + attention_mask = input_ids.new_ones(input_shape) + + # cut decoder_input_ids if past is used + if past_key_values is not None: + input_ids = input_ids[:, -1:] + + return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values} + + def _reorder_cache(self, past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) + return reordered_past + + +@add_start_docstrings("""RoBERTa Model with a `language modeling` head on top.""", ROBERTA_START_DOCSTRING) +class RobertaForMaskedLM(RobertaPreTrainedModel): + _keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_unexpected = [r"pooler"] + + def __init__(self, config): + super().__init__(config) + + if config.is_decoder: + logger.warning( + "If you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for " + "bi-directional self-attention." + ) + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.lm_head = RobertaLMHead(config) + + # The LM head weights require special treatment only when they are tied with the word embeddings + self.update_keys_to_ignore(config, ["lm_head.decoder.weight"]) + + # Initialize weights and apply final processing + self.post_init() + + def get_output_embeddings(self): + return self.lm_head.decoder + + def set_output_embeddings(self, new_embeddings): + self.lm_head.decoder = new_embeddings + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=MaskedLMOutput, + config_class=_CONFIG_FOR_DOC, + mask="", + expected_output="' Paris'", + expected_loss=0.1, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., + config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the + loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` + kwargs (`Dict[str, any]`, optional, defaults to *{}*): + Used to hide legacy arguments that have been deprecated. + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + sequence_output = outputs[0] + prediction_scores = self.lm_head(sequence_output) + + masked_lm_loss = None + if labels is not None: + loss_fct = CrossEntropyLoss() + masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) + + if not return_dict: + output = (prediction_scores,) + outputs[2:] + return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output + + return MaskedLMOutput( + loss=masked_lm_loss, + logits=prediction_scores, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class RobertaLMHead(nn.Module): + """Roberta Head for masked language modeling.""" + + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + self.decoder = nn.Linear(config.hidden_size, config.vocab_size) + self.bias = nn.Parameter(torch.zeros(config.vocab_size)) + self.decoder.bias = self.bias + + def forward(self, features, **kwargs): + x = self.dense(features) + x = gelu(x) + x = self.layer_norm(x) + + # project back to size of vocabulary with bias + x = self.decoder(x) + + return x + + def _tie_weights(self): + # To tie those two weights if they get disconnected (on TPU or when the bias is resized) + # For accelerate compatibility and to not break backward compatibility + if self.decoder.bias.device.type == "meta": + self.decoder.bias = self.bias + else: + self.bias = self.decoder.bias + + +@add_start_docstrings( + """ + RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the + pooled output) e.g. for GLUE tasks. + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForSequenceClassification(RobertaPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + self.config = config + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.classifier = RobertaClassificationHead(config) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint="cardiffnlp/twitter-roberta-base-emotion", + output_type=SequenceClassifierOutput, + config_class=_CONFIG_FOR_DOC, + expected_output="'optimism'", + expected_loss=0.08, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + sequence_output = outputs[0] + logits = self.classifier(sequence_output) + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(logits, labels) + + if not return_dict: + output = (logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +@add_start_docstrings( + """ + Roberta Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a + softmax) e.g. for RocStories/SWAG tasks. + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForMultipleChoice(RobertaPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + + self.roberta = RobertaModel(config) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + self.classifier = nn.Linear(config.hidden_size, 1) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=MultipleChoiceModelOutput, + config_class=_CONFIG_FOR_DOC, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., + num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See + `input_ids` above) + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1] + + flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None + flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None + flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None + flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None + flat_inputs_embeds = ( + inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1)) + if inputs_embeds is not None + else None + ) + + outputs = self.roberta( + flat_input_ids, + position_ids=flat_position_ids, + token_type_ids=flat_token_type_ids, + attention_mask=flat_attention_mask, + head_mask=head_mask, + inputs_embeds=flat_inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + pooled_output = outputs[1] + + pooled_output = self.dropout(pooled_output) + logits = self.classifier(pooled_output) + reshaped_logits = logits.view(-1, num_choices) + + loss = None + if labels is not None: + loss_fct = CrossEntropyLoss() + loss = loss_fct(reshaped_logits, labels) + + if not return_dict: + output = (reshaped_logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return MultipleChoiceModelOutput( + loss=loss, + logits=reshaped_logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +@add_start_docstrings( + """ + Roberta Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for + Named-Entity-Recognition (NER) tasks. + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForTokenClassification(RobertaPreTrainedModel): + _keys_to_ignore_on_load_unexpected = [r"pooler"] + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + + self.roberta = RobertaModel(config, add_pooling_layer=False) + classifier_dropout = ( + config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob + ) + self.dropout = nn.Dropout(classifier_dropout) + self.classifier = nn.Linear(config.hidden_size, config.num_labels) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint="Jean-Baptiste/roberta-large-ner-english", + output_type=TokenClassifierOutput, + config_class=_CONFIG_FOR_DOC, + expected_output="['O', 'ORG', 'ORG', 'O', 'O', 'O', 'O', 'O', 'LOC', 'O', 'LOC', 'LOC']", + expected_loss=0.01, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + sequence_output = outputs[0] + + sequence_output = self.dropout(sequence_output) + logits = self.classifier(sequence_output) + + loss = None + if labels is not None: + loss_fct = CrossEntropyLoss() + loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return TokenClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class RobertaClassificationHead(nn.Module): + """Head for sentence-level classification tasks.""" + + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + classifier_dropout = ( + config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob + ) + self.dropout = nn.Dropout(classifier_dropout) + self.out_proj = nn.Linear(config.hidden_size, config.num_labels) + + def forward(self, features, **kwargs): + x = features[:, 0, :] # take token (equiv. to [CLS]) + x = self.dropout(x) + x = self.dense(x) + x = torch.tanh(x) + x = self.dropout(x) + x = self.out_proj(x) + return x + + +@add_start_docstrings( + """ + Roberta Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear + layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForQuestionAnswering(RobertaPreTrainedModel): + _keys_to_ignore_on_load_unexpected = [r"pooler"] + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint="deepset/roberta-base-squad2", + output_type=QuestionAnsweringModelOutput, + config_class=_CONFIG_FOR_DOC, + expected_output="' puppet'", + expected_loss=0.86, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + start_positions: Optional[torch.LongTensor] = None, + end_positions: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]: + r""" + start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + sequence_output = outputs[0] + + logits = self.qa_outputs(sequence_output) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0): + """ + Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols + are ignored. This is modified from fairseq's `utils.make_positions`. + + Args: + x: torch.Tensor x: + + Returns: torch.Tensor + """ + # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA. + mask = input_ids.ne(padding_idx).int() + incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask + return incremental_indices.long() + padding_idx diff --git a/baselines/lozo/medium_models/src/models.py b/baselines/lozo/medium_models/src/models.py new file mode 100644 index 0000000..af9a3c6 --- /dev/null +++ b/baselines/lozo/medium_models/src/models.py @@ -0,0 +1,482 @@ +"""Custom models for few-shot learning specific operations.""" + +from socket import ntohl +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers.models.bert.modeling_bert import BertPreTrainedModel, BertModel, BertOnlyMLMHead +# from transformers.models.roberta.modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead +from .modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead +# from transformers.models.opt.modeling_opt import OPTPreTrainedModel, OPTModel, OPTDecoder +from .modeling_opt import OPTPreTrainedModel, OPTModel, OPTDecoder, OPTForCausalLM +from transformers.models.gpt2.modeling_gpt2 import GPT2PreTrainedModel, GPT2Model, GPT2LMHeadModel +from transformers.modeling_outputs import BaseModelOutputWithPast +from typing import Callable, Dict, Optional, Union, List, Tuple +import random + + +import logging +logger = logging.getLogger(__name__) + + +def resize_token_type_embeddings(model, new_num_types: int, random_segment: bool): + """ + Resize the segment (token type) embeddings for BERT + """ + if hasattr(model, 'bert'): + old_token_type_embeddings = model.bert.embeddings.token_type_embeddings + else: + raise NotImplementedError + new_token_type_embeddings = nn.Embedding(new_num_types, old_token_type_embeddings.weight.size(1)) + if not random_segment: + new_token_type_embeddings.weight.data[:old_token_type_embeddings.weight.size(0)] = old_token_type_embeddings.weight.data + + model.config.type_vocab_size = new_num_types + if hasattr(model, 'bert'): + model.bert.embeddings.token_type_embeddings = new_token_type_embeddings + else: + raise NotImplementedError + +def model_for_prompting_forward( + model, + input_ids=None, + attention_mask=None, + token_type_ids=None, + mask_pos=None, + labels=None, + sfc_input_ids=None, + sfc_attention_mask=None, + sfc_mask_pos=None +): + if sfc_input_ids is not None: + with torch.no_grad(): + logits = model_for_prompting_forward(model, input_ids=sfc_input_ids, attention_mask=sfc_attention_mask, mask_pos=sfc_mask_pos)[0] + icl_sfc_bias = F.log_softmax(logits.detach().squeeze(0)) + + if mask_pos is not None: + mask_pos = mask_pos.squeeze() + + model_fn = model.get_model_fn() + # Encode everything + if token_type_ids is not None: + outputs = model_fn( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids + ) + else: + outputs = model_fn( + input_ids, + attention_mask=attention_mask, + ) + + + # Get token representation + sequence_output = outputs[0] + if mask_pos is not None: + sequence_mask_output = sequence_output[torch.arange(sequence_output.size(0)), mask_pos] + else: + sequence_mask_output = sequence_output[:,0] # representation + # sequence_mask_output = sequence_output.mean(dim=1) # average representation + + if model.label_word_list is not None: + # Logits over vocabulary tokens + head_fn = model.get_lm_head_fn() + prediction_mask_scores = head_fn(sequence_mask_output) + + # Exit early and only return mask logits. + if model.return_full_softmax: + if labels is not None: + return torch.zeros(1, out=prediction_mask_scores.new()), prediction_mask_scores + return prediction_mask_scores + + # Return logits for each label + logits = [] + # use MLM logit + if model.model_args.use_task_word: + vocab_logits = model.lm_head(sequence_mask_output) + for _id in model.label_word_list: + logits.append(vocab_logits[:, _id].unsqueeze(-1)) + # use learned linear head logit on top of task word representation (standard LM-BFF) + else: + for label_id in range(len(model.label_word_list)): + logits.append(prediction_mask_scores[:, model.label_word_list[label_id]].unsqueeze(-1)) + logits = torch.cat(logits, -1) + + # Regression task + if model.config.num_labels == 1: + logsoftmax = nn.LogSoftmax(-1) + logits = logsoftmax(logits) # Log prob of right polarity + else: + logits = model.classifier(sequence_mask_output) + + + loss = None + if labels is not None: + if model.config.num_labels == 1: + # Regression task + if model.label_word_list is not None: + labels = torch.stack([1 - (labels.view(-1) - model.lb) / (model.ub - model.lb), (labels.view(-1) - model.lb) / (model.ub - model.lb)], -1) + loss = nn.KLDivLoss(log_target=True)(logits.view(-1, 2), labels) + else: + labels = (labels.float().view(-1) - model.lb) / (model.ub - model.lb) + loss = nn.MSELoss()(logits.view(-1), labels) + else: + if model.model_args.l2_loss: + coords = torch.nn.functional.one_hot(labels.squeeze(), model.config.num_labels).float() + loss = nn.MSELoss()(logits.view(-1, logits.size(-1)), coords) + else: + loss = nn.CrossEntropyLoss()(logits.view(-1, logits.size(-1)), labels.view(-1)) + + + if hasattr(model, "lr_weight"): + # Linear head + logits = torch.matmul(F.softmax(logits, -1), model.lr_weight) + if hasattr(model, "lr_bias"): + logits += model.lr_bias.unsqueeze(0) + + if model.model_args.sfc and hasattr(model, "sfc_bias"): + logits = F.log_softmax(logits, -1) - model.sfc_bias + if sfc_input_ids is not None: + logits = F.log_softmax(logits, -1) - icl_sfc_bias + + output = (logits,) + + + if model.model_args.use_task_word and model.num_labels == 1: + # Regression output + output = (torch.exp(logits[..., 1].unsqueeze(-1)) * (model.ub - model.lb) + model.lb,) + return ((loss,) + output) if loss is not None else output + +def convert_opt_model(model: OPTModel, config, num_exclude_layers): + model.model.decoder = EfficientOPTDecoder(config, num_exclude_layers) + return model + +class BertModelForPromptFinetuning(BertPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + self.bert = BertModel(config) + self.cls = BertOnlyMLMHead(config) + self.classifier = nn.Linear(config.hidden_size, self.num_labels) + + self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def get_model_fn(self): + return self.bert + + def get_lm_head_fn(self): + return self.cls + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels) + +class RobertaModelForPromptFinetuning(RobertaPreTrainedModel): + def __init__(self, config): + super().__init__(config) + logger.warn("By default for RoBERTa models the input embeddings and the output embeddings are NOT tied!!!!") + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + self.roberta = RobertaModel(config) + self.lm_head = RobertaLMHead(config) + self.classifier = nn.Linear(config.hidden_size, self.num_labels) + + self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def tie_emb(self): + output_embeddings = self.lm_head.decoder + self._tie_or_clone_weights(output_embeddings, self.roberta.get_input_embeddings()) + + def get_model_fn(self): + return self.roberta + + def get_lm_head_fn(self): + return self.lm_head + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels) + +class OPTModelForPromptFinetuning(OPTForCausalLM): + def __init__(self, config): + super().__init__(config) + logger.warn("By default for OPT models the input embeddings and the output embeddings are tied!!!!") + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + # self.model = OPTModel(config) + # self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False) + # self.classifier = nn.Linear(config.hidden_size, self.num_labels) + # self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def get_model_fn(self): + return self.model + + def get_lm_head_fn(self): + return self.lm_head + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None, sfc_input_ids=None, sfc_attention_mask=None, sfc_mask_pos=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels, sfc_input_ids=sfc_input_ids, sfc_attention_mask=sfc_attention_mask, sfc_mask_pos=sfc_mask_pos) + +class GPT2ModelForPromptFinetuning(GPT2LMHeadModel): + + def __init__(self, config): + super().__init__(config) + raise NotImplementedError("Need to check if the lm head is properly loaded and whether it is tied.") + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + # self.transformer = GPT2Model(config) + # self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) + self.classifier = nn.Linear(config.hidden_size, self.num_labels) + + self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def get_model_fn(self): + return self.transformer + + def get_lm_head_fn(self): + return self.lm_head + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels) + +class EfficientOPTDecoder(OPTDecoder): + def __init__(self, config, num_exclude): + super().__init__(config) + self.num_exclude = num_exclude # number of initial layers to operate with torch.no_grad + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + # embed positions + if attention_mask is None: + attention_mask = torch.ones(inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device) + pos_embeds = self.embed_positions(attention_mask, past_key_values_length) + + attention_mask = self._prepare_decoder_attention_mask( + attention_mask, input_shape, inputs_embeds, past_key_values_length + ) + + if self.project_in is not None: + inputs_embeds = self.project_in(inputs_embeds) + + hidden_states = inputs_embeds + pos_embeds + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + # check if head_mask has a correct number of layers specified if desired + for attn_mask, mask_name in zip([head_mask], ["head_mask"]): + if attn_mask is not None: + if attn_mask.size()[0] != (len(self.layers)): + raise ValueError( + f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" + f" {head_mask.size()[0]}." + ) + + #### run first few layers without grad + with torch.no_grad(): + for idx, decoder_layer in enumerate(self.layers[:self.num_exclude]): + + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + #### rest of the layers with grad + for idx, decoder_layer in enumerate(self.layers[self.num_exclude:]): + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + if self.final_layer_norm is not None: + hidden_states = self.final_layer_norm(hidden_states) + + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +MODEL_TYPES = { + "bert": BertModelForPromptFinetuning, + "roberta": RobertaModelForPromptFinetuning, + "opt": OPTModelForPromptFinetuning, + "gpt2": GPT2ModelForPromptFinetuning, +} diff --git a/baselines/lozo/medium_models/src/prefix.py b/baselines/lozo/medium_models/src/prefix.py new file mode 100644 index 0000000..91d06a2 --- /dev/null +++ b/baselines/lozo/medium_models/src/prefix.py @@ -0,0 +1,162 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import torch +from torch import nn + +def find_module(root_module: nn.Module, key: str): + """From OpenDelta""" + sub_keys = key.split(".") + parent_module = root_module + for sub_key in sub_keys[:-1]: + parent_module = getattr(parent_module, sub_key) + module = getattr(parent_module, sub_keys[-1]) + return parent_module, sub_keys[-1], module + + +def attn_forward_hook(self, *args, **kwargs): + + def _expand_bsz(x, bsz): + x = x.reshape(x.size(0), self.num_heads, -1).transpose(0,1) # (num_prefix, hidden) -> (num_head, num_prefix, hidden/num_head) + x = x.unsqueeze(0).expand(bsz, *x.shape) # -> (bsz, num_head, num_prefix, hidden/num_head) + return x + + if "hidden_states" in kwargs: + hidden_states = kwargs["hidden_states"] + else: + hidden_states = args[0] + bsz = hidden_states.size(0) + if 'past_key_value' not in kwargs or kwargs['past_key_value'] is None: + if self.reparam: + prefix_keys = self.prefix_mlp_keys(self.prefix_input_embeds) + prefix_values = self.prefix_mlp_values(self.prefix_input_embeds) + else: + prefix_keys, prefix_values = self.prefix_keys, self.prefix_values + kwargs['past_key_value'] = (_expand_bsz(prefix_keys, bsz), _expand_bsz(prefix_values, bsz)) + + if 'attention_mask' in kwargs and kwargs['attention_mask'] is not None: + am = kwargs['attention_mask'] + kwargs['attention_mask'] = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1) + elif len(args) > 1: # attention mask is passed via positional argument + am = args[1] + am = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1) + args = (args[0], am) + args[2:] + + return self.original_forward(*args, **kwargs) + + +class PrefixTuning: + + def __init__(self, model, num_prefix, reparam=True, embed_dim=512, mid_dim=512, float16=False, init_by_real_act=False): + + self.model = model + self.num_prefix = num_prefix + self.hidden_dim = model.config.hidden_size + self.float16 = float16 + + # Reparameterization + self.reparam = reparam + self.embed_dim = embed_dim + self.mid_dim = mid_dim + + input_embeds = None # For reparameterization + if model.config.model_type == "opt": + attention_name = "attn" + first_layer_name = "layers.0" + layer_name = "layers." + elif model.config.model_type == "roberta": + attention_name = "attention" + first_layer_name = "layer.0" + layer_name = "layer." + else: + raise NotImplementedError + + if init_by_real_act: + # Initialize prefix with real words' activations + assert not reparam + + # Move the model to GPU first? + model = model.cuda() + input_tokens = torch.randint(low=0, high=model.config.vocab_size, size=(1, num_prefix), dtype=torch.long).cuda() + if model.config.model_type == "roberta": + with torch.no_grad(): + # real_key_values = model(input_ids=input_tokens, use_cache=True).past_key_values + real_key_values = model.roberta(input_ids=input_tokens, use_cache=True).past_key_values + elif model.config.model_type == "opt": + with torch.no_grad(): + real_key_values = model.model(input_ids=input_tokens, use_cache=True).past_key_values + else: + raise NotImplementedError + + for key, _ in model.named_modules(): + if key[-len(attention_name):] == attention_name: + layer_id = int(key.split(layer_name)[1].split(".")[0]) + logger.info(f"Inject prefix to: {key}") + _, _, attn = find_module(model, key) + attn.original_forward = attn.forward + attn.forward = attn_forward_hook.__get__(attn, type(attn)) + if not hasattr(attn, "num_heads"): + attn.num_heads = model.config.num_attention_heads + first = first_layer_name in key + self.add_prefix(attn, first=first, input_embeds=input_embeds) + if first and self.reparam: + input_embeds = attn.prefix_input_embeds + if init_by_real_act: + logger.info(f"Reinitialize with actual activation: {key} (layer {layer_id})") + keys = real_key_values[layer_id][0].squeeze(0).transpose(0, 1).reshape(num_prefix, -1) + values = real_key_values[layer_id][1].squeeze(0).transpose(0, 1).reshape(num_prefix, -1) + attn.prefix_keys.data = keys + attn.prefix_values.data = values + + for n, p in model.named_parameters(): + if "prefix" not in n: + # logger.info(f"Freeze {n}") + p.requires_grad = False + + def add_prefix(self, module, first, input_embeds=None): + module.num_prefix = self.num_prefix + module.reparam = self.reparam + if self.reparam: + if first: + logger.info("For prefix+reparameterization, inject the embeddings in the first layer.") + module.prefix_input_embeds = nn.Parameter(torch.randn(self.num_prefix, self.embed_dim, device=self.model.device, dtype=self.model.dtype), requires_grad=True) + else: + assert input_embeds is not None + module.prefix_input_embeds = input_embeds + module.prefix_mlp_keys = nn.Sequential( + nn.Linear(self.embed_dim, self.mid_dim), + nn.Tanh(), + nn.Linear(self.mid_dim, self.hidden_dim) + ).to(self.model.device) + module.prefix_mlp_values = nn.Sequential( + nn.Linear(self.embed_dim, self.mid_dim), + nn.Tanh(), + nn.Linear(self.mid_dim, self.hidden_dim) + ).to(self.model.device) + if self.float16: + module.prefix_mlp_keys = module.prefix_mlp_keys.half() + module.prefix_mlp_values = module.prefix_mlp_values.half() + else: + module.prefix_keys = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=self.model.device, dtype=self.model.dtype), requires_grad=True) + module.prefix_values = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=self.model.device, dtype=self.model.dtype), requires_grad=True) + + +def test(): + from transformers import AutoTokenizer + from modeling_roberta import RobertaModel + model = RobertaModel.from_pretrained("roberta-base") + tokenizer = AutoTokenizer.from_pretrained("roberta-base") + model.cuda() + + PrefixTuning(model, num_prefix=5, reparam=False, init_by_real_act=True) + + inputs = tokenizer("Hello, my dog is", return_tensors="pt").to(model.device) + o = model(**inputs) + # print(o) + + +if __name__ == "__main__": + test() \ No newline at end of file diff --git a/baselines/lozo/medium_models/src/processors.py b/baselines/lozo/medium_models/src/processors.py new file mode 100644 index 0000000..41ffa8b --- /dev/null +++ b/baselines/lozo/medium_models/src/processors.py @@ -0,0 +1,611 @@ +"""Dataset utils for different data settings for GLUE.""" + +import os +import logging +from transformers import DataProcessor, InputExample +from transformers.data.processors.glue import * +from transformers.data.metrics import glue_compute_metrics +import pandas as pd +import logging + +logger = logging.getLogger(__name__) + +class MrpcProcessor(DataProcessor): + """Processor for the MRPC data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence1"].numpy().decode("utf-8"), + tensor_dict["sentence2"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + logger.info("LOOKING AT {}".format(os.path.join(data_dir, "train.tsv"))) + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["0", "1"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, i) + text_a = line[3] + text_b = line[4] + label = line[0] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class MnliProcessor(DataProcessor): + """Processor for the MultiNLI data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["premise"].numpy().decode("utf-8"), + tensor_dict["hypothesis"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev_matched") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test_matched") + + def get_labels(self): + """See base class.""" + return ["contradiction", "entailment", "neutral"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[8] + text_b = line[9] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class MnliMismatchedProcessor(MnliProcessor): + """Processor for the MultiNLI Mismatched data set (GLUE version).""" + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev_mismatched.tsv")), "dev_mismatched") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test_mismatched.tsv")), "test_mismatched") + + +class SnliProcessor(DataProcessor): + """Processor for the MultiNLI data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["premise"].numpy().decode("utf-8"), + tensor_dict["hypothesis"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["contradiction", "entailment", "neutral"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[7] + text_b = line[8] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class ColaProcessor(DataProcessor): + """Processor for the CoLA data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence"].numpy().decode("utf-8"), + None, + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["0", "1"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + test_mode = set_type == "test" + text_index = 3 + examples = [] + for (i, line) in enumerate(lines): + guid = "%s-%s" % (set_type, i) + text_a = line[text_index] + label = line[1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label)) + return examples + + +class Sst2Processor(DataProcessor): + """Processor for the SST-2 data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence"].numpy().decode("utf-8"), + None, + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["0", "1"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + text_index = 0 + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, i) + text_a = line[text_index] + label = line[1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label)) + return examples + + +class StsbProcessor(DataProcessor): + """Processor for the STS-B data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence1"].numpy().decode("utf-8"), + tensor_dict["sentence2"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return [None] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[7] + text_b = line[8] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class QqpProcessor(DataProcessor): + """Processor for the QQP data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["question1"].numpy().decode("utf-8"), + tensor_dict["question2"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["0", "1"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + test_mode = set_type == "test" + q1_index = 3 + q2_index = 4 + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + try: + text_a = line[q1_index] + text_b = line[q2_index] + label = line[5] + except IndexError: + continue + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class QnliProcessor(DataProcessor): + """Processor for the QNLI data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["question"].numpy().decode("utf-8"), + tensor_dict["sentence"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["entailment", "not_entailment"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[1] + text_b = line[2] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class RteProcessor(DataProcessor): + """Processor for the RTE data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence1"].numpy().decode("utf-8"), + tensor_dict["sentence2"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["entailment", "not_entailment"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[1] + text_b = line[2] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class WnliProcessor(DataProcessor): + """Processor for the WNLI data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence1"].numpy().decode("utf-8"), + tensor_dict["sentence2"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["0", "1"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[1] + text_b = line[2] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + +class TextClassificationProcessor(DataProcessor): + """ + Data processor for text classification datasets (mr, sst-5, subj, trec, cr, mpqa). + """ + + def __init__(self, task_name): + self.task_name = task_name + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence"].numpy().decode("utf-8"), + None, + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(pd.read_csv(os.path.join(data_dir, "train.csv"), header=None).values.tolist(), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(pd.read_csv(os.path.join(data_dir, "dev.csv"), header=None).values.tolist(), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(pd.read_csv(os.path.join(data_dir, "test.csv"), header=None).values.tolist(), "test") + + def get_labels(self): + """See base class.""" + if self.task_name == "mr": + return list(range(2)) + elif self.task_name == "sst-5": + return list(range(5)) + elif self.task_name == "subj": + return list(range(2)) + elif self.task_name == "trec": + return list(range(6)) + elif self.task_name == "cr": + return list(range(2)) + elif self.task_name == "mpqa": + return list(range(2)) + else: + raise Exception("task_name not supported.") + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + guid = "%s-%s" % (set_type, i) + if self.task_name == "ag_news": + examples.append(InputExample(guid=guid, text_a=line[1] + '. ' + line[2], short_text=line[1] + ".", label=line[0])) + elif self.task_name == "yelp_review_full": + examples.append(InputExample(guid=guid, text_a=line[1], short_text=line[1], label=line[0])) + elif self.task_name == "yahoo_answers": + text = line[1] + if not pd.isna(line[2]): + text += ' ' + line[2] + if not pd.isna(line[3]): + text += ' ' + line[3] + examples.append(InputExample(guid=guid, text_a=text, short_text=line[1], label=line[0])) + elif self.task_name in ['mr', 'sst-5', 'subj', 'trec', 'cr', 'mpqa']: + examples.append(InputExample(guid=guid, text_a=line[1], label=line[0])) + else: + raise Exception("Task_name not supported.") + + return examples + +def text_classification_metrics(task_name, preds, labels): + return {"acc": (preds == labels).mean()} + +# Add your task to the following mappings + +processors_mapping = { + "cola": ColaProcessor(), + "mnli": MnliProcessor(), + "mnli-mm": MnliMismatchedProcessor(), + "mrpc": MrpcProcessor(), + "sst-2": Sst2Processor(), + "sts-b": StsbProcessor(), + "qqp": QqpProcessor(), + "qnli": QnliProcessor(), + "rte": RteProcessor(), + "wnli": WnliProcessor(), + "snli": SnliProcessor(), + "mr": TextClassificationProcessor("mr"), + "sst-5": TextClassificationProcessor("sst-5"), + "subj": TextClassificationProcessor("subj"), + "trec": TextClassificationProcessor("trec"), + "cr": TextClassificationProcessor("cr"), + "mpqa": TextClassificationProcessor("mpqa") +} + +num_labels_mapping = { + "cola": 2, + "mnli": 3, + "mrpc": 2, + "sst-2": 2, + "sts-b": 1, + "qqp": 2, + "qnli": 2, + "rte": 2, + "wnli": 2, + "snli": 3, + "mr": 2, + "sst-5": 5, + "subj": 2, + "trec": 6, + "cr": 2, + "mpqa": 2 +} + +output_modes_mapping = { + "cola": "classification", + "mnli": "classification", + "mnli-mm": "classification", + "mrpc": "classification", + "sst-2": "classification", + "sts-b": "regression", + "qqp": "classification", + "qnli": "classification", + "rte": "classification", + "wnli": "classification", + "snli": "classification", + "mr": "classification", + "sst-5": "classification", + "subj": "classification", + "trec": "classification", + "cr": "classification", + "mpqa": "classification" +} + +# Return a function that takes (task_name, preds, labels) as inputs +compute_metrics_mapping = { + "cola": glue_compute_metrics, + "mnli": glue_compute_metrics, + "mnli-mm": glue_compute_metrics, + "mrpc": glue_compute_metrics, + "sst-2": glue_compute_metrics, + "sts-b": glue_compute_metrics, + "qqp": glue_compute_metrics, + "qnli": glue_compute_metrics, + "rte": glue_compute_metrics, + "wnli": glue_compute_metrics, + "snli": text_classification_metrics, + "mr": text_classification_metrics, + "sst-5": text_classification_metrics, + "subj": text_classification_metrics, + "trec": text_classification_metrics, + "cr": text_classification_metrics, + "mpqa": text_classification_metrics, +} + +# For regression task only: median +median_mapping = { + "sts-b": 2.5 +} + +bound_mapping = { + "sts-b": (0, 5) +} diff --git a/baselines/lozo/medium_models/src/trainer.py b/baselines/lozo/medium_models/src/trainer.py new file mode 100644 index 0000000..f54016f --- /dev/null +++ b/baselines/lozo/medium_models/src/trainer.py @@ -0,0 +1,867 @@ +########## The following part is copied from Transformers' trainer (3.4.0) and later ported to be compatible with v4.4.2 and to support initialization from linear head probing. ########## + +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. +""" + +import collections +import inspect +import math +import os +import re +import shutil +import warnings +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import numpy as np +import torch +from packaging import version +from torch import nn +from torch.utils.data.dataloader import DataLoader +from torch.utils.data.dataset import Dataset +from torch.utils.data.distributed import DistributedSampler +from torch.utils.data.sampler import RandomSampler, SequentialSampler +from torch.optim.lr_scheduler import LambdaLR +import math +import time + +import transformers +from transformers.file_utils import is_datasets_available, is_in_notebook, is_torch_tpu_available +from transformers.integrations import ( + is_comet_available, + is_optuna_available, + is_ray_available, + is_tensorboard_available, + is_wandb_available, +) +from transformers.optimization import AdamW, get_linear_schedule_with_warmup, get_scheduler + +from transformers.trainer_callback import ( + DefaultFlowCallback, + ProgressCallback, +) +from transformers.trainer_utils import ( + default_compute_objective, +) +from transformers.training_args import TrainingArguments +from transformers.utils import logging +from transformers.trainer_utils import TrainOutput + +from tqdm import tqdm, trange +from torch.optim import SGD +import torch.nn.functional as F + +from src.linearhead_trainer import LinearHeadTrainer +from transformers.trainer_callback import TrainerState + +import copy + +_use_native_amp = False +_use_apex = False + +DEFAULT_CALLBACKS = [DefaultFlowCallback] +DEFAULT_PROGRESS_CALLBACK = ProgressCallback + +if is_in_notebook(): + from transformers.utils.notebook import NotebookProgressCallback + + DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback + +# Check if Pytorch version >= 1.6 to switch between Native AMP and Apex +if version.parse(torch.__version__) < version.parse("1.6"): + from transformers.file_utils import is_apex_available + + if is_apex_available(): + from apex import amp + _use_apex = True +else: + _use_native_amp = True + from torch.cuda.amp import autocast + +if version.parse(torch.__version__) < version.parse("1.2"): + _use_ddp_no_sync = False +else: + _use_ddp_no_sync = True + +if is_datasets_available(): + import datasets + +if is_torch_tpu_available(): + import torch_xla.core.xla_model as xm + import torch_xla.debug.metrics as met + import torch_xla.distributed.parallel_loader as pl + +if is_tensorboard_available(): + from transformers.integrations import TensorBoardCallback + + DEFAULT_CALLBACKS.append(TensorBoardCallback) + + +if is_wandb_available(): + from transformers.integrations import WandbCallback + + DEFAULT_CALLBACKS.append(WandbCallback) + +if is_comet_available(): + from transformers.integrations import CometCallback + + DEFAULT_CALLBACKS.append(CometCallback) + +if is_optuna_available(): + import optuna + +if is_ray_available(): + from ray import tune + +logger = logging.get_logger(__name__) +logger.setLevel(logging.INFO) + +########## The above part is copied from Transformers' trainer (3.4.0) ########## + +def default_dev_objective(metrics): + """ + Objective used for picking the best model on development sets + """ + if "eval_mnli/acc" in metrics: + return metrics["eval_mnli/acc"] + elif "eval_mnli-mm/acc" in metrics: + return metrics["eval_mnli-mm/acc"] + elif "eval_f1" in metrics: + return metrics["eval_f1"] + elif "eval_mcc" in metrics: + return metrics["eval_mcc"] + elif "eval_pearson" in metrics: + return metrics["eval_pearson"] + elif "eval_acc" in metrics: + return metrics["eval_acc"] + + raise Exception("No metric founded for {}".format(metrics)) + +class Trainer(LinearHeadTrainer): + """ + Adding some functions based on Transformers' Trainer class. + """ + + def create_optimizer_and_scheduler(self, num_training_steps: int): + """ + Based on Transformers' default one, we add fixing layer option where the bottom n layers' parameters + are fixed and only the top layers are further fine-tuned. + """ + if self.args.hf_inference_model: + return + + if self.optimizer is None: + params = {} + for n, p in self.model.named_parameters(): + if self.args.fix_layers > 0: + if 'encoder.layer' in n: + try: + layer_num = int(n[n.find('encoder.layer') + 14:].split('.')[0]) + except: + print(n) + raise Exception("") + if layer_num >= self.args.fix_layers: + print('yes', n) + params[n] = p + else: + print('no ', n) + elif 'embeddings' in n: + print('no ', n) + else: + print('yes', n) + params[n] = p + else: + params[n] = p + no_decay = ["bias", "LayerNorm.weight"] + optimizer_grouped_parameters = [ + { + "params": [p for n, p in params.items() if not any(nd in n for nd in no_decay)], + "weight_decay": self.args.weight_decay, + }, + { + "params": [p for n, p in params.items() if any(nd in n for nd in no_decay)], + "weight_decay": 0.0, + }, + ] + if self.args.optimizer == 'adam': + self.optimizer = AdamW( + optimizer_grouped_parameters, + lr=self.args.learning_rate, + betas=(self.args.adam_beta1, self.args.adam_beta2), + eps=self.args.adam_epsilon, + ) + elif self.args.optimizer == 'sgd': + self.optimizer = SGD( + optimizer_grouped_parameters, + lr=self.args.learning_rate + ) + else: + raise NotImplementedError + if self.lr_scheduler is None: + self.lr_scheduler = get_scheduler( + self.args.lr_scheduler_type, + optimizer=self.optimizer, + num_warmup_steps=self.args.get_warmup_steps(num_training_steps), + num_training_steps=num_training_steps, + ) + + def should_optim(self, name, param): + return (not self.args.layer_wise_optim or f".{self.state.global_step % self.model.config.num_hidden_layers}." in name) and param.requires_grad + + def zo_forward(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: + model.eval() + inputs = self._prepare_inputs(inputs) + if self.args.optimize_acc: + loss, logits = model(**inputs) + preds = F.softmax(logits, dim=-1) + acc = torch.sum(torch.argmax(preds, 1) == inputs['labels']) / len(preds) + loss = -acc + else: + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + self.state.zo_forward_step += 1 + return loss.detach() + + def efficient_perturb_parameters(self, model: nn.Module, random_seed: int, scaling_factor=1): + torch.manual_seed(random_seed) + for name, param in self.named_parameters_to_optim: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * self.args.zero_order_eps + return model + + def norm_perturb_parameters(self, model: nn.Module, random_vector=None, scaling_factor=1): + if random_vector is None: + random_vector = {} + + for name, param in self.named_parameters_to_optim: + if name in random_vector: + z = random_vector[name] + else: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + random_vector[name] = z + + cname = self.retrieve_c(name) + if cname in self.cs: + z = z / self.cs[cname] + + param.data = param.data + scaling_factor * z * self.args.zero_order_eps + + return model, random_vector + + def perturb_parameters(self, model: nn.Module, random_vector=None, scaling_factor=1): + if random_vector is None: + random_vector = {} + + for name, param in self.named_parameters_to_optim: + if name in random_vector: + z = random_vector[name] + else: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + random_vector[name] = z + param.data = param.data + scaling_factor * z * self.args.zero_order_eps + + return model, random_vector + + def perturb_single_layer(self, model, layer_name, random_vector=None, scaling_factor=1): + if random_vector is None: + random_vector = {} + + for name, param in self.named_parameters_to_optim: + cname = self.retrieve_c(name) + if cname == layer_name: + if name in random_vector: + z = random_vector[name] + else: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + random_vector[name] = z + param.data = param.data + scaling_factor * z * self.args.zero_order_eps + + return model, random_vector + + def initialize_c(self, model, inputs): + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if self.should_optim(name, param): + self.named_parameters_to_optim.append((name, param)) + + self.cs = {'embed': 0.0, 'lm_head': 0.0} + # OPT: embed_tokens; embed_positions + # RoBERTa: embeddings + self.num_params = copy.deepcopy(self.cs) + self.num_model_layers = model.config.num_hidden_layers + layer_name = "layers" if model.config.model_type == "opt" else "layer" + for i in range(self.num_model_layers): + self.cs[f'{layer_name}.{i}.'] = 0.0 + self.num_params[f'{layer_name}.{i}.'] = 0 + + # ZO estimation of c's + if self.args.zo_variant != 'param_norm' and self.args.use_zo_grad_est: + for layer in self.cs.keys(): + with torch.no_grad(): + model, z = self.perturb_single_layer(model, layer_name=layer) + loss1 = self.zo_forward(model, inputs) + model, z = self.perturb_single_layer(model, layer_name=layer, random_vector=z, scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + + projected_grad = (loss1 - loss2) / (2 * self.args.zero_order_eps) + self.cs[layer] = torch.abs(projected_grad) + + model, z = self.perturb_single_layer(model, layer_name=layer, random_vector=z) + + # no need to run backprop if we are using parameter norm variant, can just measure them + elif self.args.zo_variant == 'param_norm': + for name, param in self.named_parameters_to_optim: + print(name) + ckey = self.retrieve_c(name) + if ckey in self.cs: + self.cs[ckey] += torch.sum(param.data ** 2) + self.num_params[ckey] += param.data.numel() + + # take sqrt to get norm + for ckey in self.cs: + self.cs[ckey] = torch.sqrt(self.cs[ckey]) + if self.args.scale_norm_by_num_params: + self.cs[ckey] /= torch.sqrt(self.cs[ckey]) + + for ckey in self.cs: + if self.cs[ckey] != 0: + self.cs[ckey] = self.cs[ckey].detach().item() + + # backpropagation estimation fo ZO c's + # this is mostly for debugging purposes to disentangle the variance from using ZO to estimate c + # from the effectiveness of the preconditioners + else: + model.eval() + inputs = self._prepare_inputs(inputs) + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + loss.backward() + for name, param in self.named_parameters_to_optim: + if param.grad is None: + print(name) + else: + ckey = self.retrieve_c(name) + if ckey in self.cs: + self.cs[ckey] += torch.sum(param.grad ** 2) + self.num_params[ckey] += param.grad.numel() + + # take sqrt to get norm + for ckey in self.cs: + self.cs[ckey] = torch.sqrt(self.cs[ckey]) + if self.args.scale_norm_by_num_params: + self.cs[ckey] /= torch.sqrt(self.num_params[ckey]) + + for ckey in self.cs: + if self.cs[ckey] != 0: + self.cs[ckey] = self.cs[ckey].detach().item() + + self.layer_names = list(self.cs.keys()) + model.zero_grad() + + def retrieve_c(self, param_name): + for c_name in self.cs.keys(): + if c_name in param_name: + return c_name + + return '' # these parameters are likely not being used in the forward pass + + def get_num_samples(self): + if self.args.zero_order_sample_scheduler is None: + noise_sample_time = 1 + elif self.args.zero_order_sample_scheduler == "linear": + noise_sample_time = max(1, int(self.state.global_step / self.args.max_steps * self.args.zero_order_sample)) + elif self.args.zero_order_sample_scheduler == "constant": + noise_sample_time = int(self.args.zero_order_sample) + else: + raise NotImplementedError + # print("Sample %d zs" % (noise_sample_time)) + + return noise_sample_time + + def train(self, model_path=None, dev_objective=None): + """ + Main training entry point. + + The training logic is directly borrowed from transformers.Trainer (version 3.0.2). + Add early stopping. + """ + if self.args.from_linearhead and model_path is None: + super().train(model_path, dev_objective) # Train output layer using LinearHeadTrainer + + self.best_dir = None + self.objective = -float("inf") + self.dev_objective = dev_objective if dev_objective is not None else default_dev_objective + + # Data loading. + train_dataloader = self.get_train_dataloader() + num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps + if num_update_steps_per_epoch == 0: + num_update_steps_per_epoch = 1 + if self.args.max_steps > 0: + t_total = self.args.max_steps + num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int( + self.args.max_steps % num_update_steps_per_epoch > 0 + ) + else: + t_total = int(len(train_dataloader) // self.args.gradient_accumulation_steps * self.args.num_train_epochs) + num_train_epochs = self.args.num_train_epochs + + self.create_optimizer_and_scheduler(num_training_steps=t_total) + optimizer = self.optimizer + scheduler = self.lr_scheduler + + # Check if saved optimizer or scheduler states exist + if ( + model_path is not None + and os.path.isfile(os.path.join(model_path, "optimizer.pt")) + and os.path.isfile(os.path.join(model_path, "scheduler.pt")) + ): + # Load in optimizer and scheduler states + optimizer.load_state_dict( + torch.load(os.path.join(model_path, "optimizer.pt"), map_location=self.args.device) + ) + scheduler.load_state_dict(torch.load(os.path.join(model_path, "scheduler.pt"))) + + model = self.model + + if self.args.fp16 and _use_apex: + if not transformers.is_apex_available(): + raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") + model, optimizer = amp.initialize(model, optimizer, opt_level=self.args.fp16_opt_level) + + # Multi-gpu training (should be after apex fp16 initialization) + if self.args.n_gpu > 1: + model = torch.nn.DataParallel(model) + + # Distributed training (should be after apex fp16 initialization) + if self.args.local_rank != -1: + model = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.args.local_rank], + output_device=self.args.local_rank, + find_unused_parameters=True, + ) + + # Train + if transformers.is_torch_tpu_available(): + total_train_batch_size = self.args.train_batch_size * xm.xrt_world_size() + else: + total_train_batch_size = ( + self.args.train_batch_size + * self.args.gradient_accumulation_steps + * (torch.distributed.get_world_size() if self.args.local_rank != -1 else 1) + ) + logger.info("***** Running training *****") + logger.info(" Num examples = %d", self.num_examples(train_dataloader)) + logger.info(" Num Epochs = %d", num_train_epochs) + logger.info(" Instantaneous batch size per device = %d", self.args.per_device_train_batch_size) + logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d", total_train_batch_size) + logger.info(" Gradient Accumulation steps = %d", self.args.gradient_accumulation_steps) + logger.info(" Total optimization steps = %d", t_total) + + self.state = TrainerState() + self.state.global_step = 0 + start_time = time.time() + self.state.zo_forward_step = 0 + self.epoch = 0 + epochs_trained = 0 + steps_trained_in_current_epoch = 0 + + if self.args.gradient_checkpointing: + model.gradient_checkpointing_enable() + + # Check if continuing training from a checkpoint + if model_path is not None: + # set global_step to global_step of last saved checkpoint from model path + try: + self.state.global_step = int(model_path.split("-")[-1].split("/")[0]) + epochs_trained = self.state.global_step // (len(train_dataloader) // self.args.gradient_accumulation_steps) + steps_trained_in_current_epoch = self.state.global_step % ( + len(train_dataloader) // self.args.gradient_accumulation_steps + ) + + logger.info(" Continuing training from checkpoint, will skip to saved global_step") + logger.info(" Continuing training from epoch %d", epochs_trained) + logger.info(" Continuing training from global step %d", self.state.global_step) + logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch) + except ValueError: + self.state.global_step = 0 + logger.info(" Starting fine-tuning.") + + tr_loss = torch.tensor(0.0).to(self.args.device) + logging_loss_scalar = 0.0 + model.zero_grad() + metrics = None + for epoch in range(epochs_trained, int(num_train_epochs)): + if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): + train_dataloader.sampler.set_epoch(epoch) + + if transformers.is_torch_tpu_available(): + parallel_loader = pl.ParallelLoader(train_dataloader, [self.args.device]).per_device_loader( + self.args.device + ) + epoch_iterator = tqdm(parallel_loader, desc="Iteration", disable=not self.is_local_process_zero()) + else: + epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=True) + + # Reset the past mems state at the beginning of each epoch if necessary. + if self.args.past_index >= 0: + self._past = None + + for step, inputs in enumerate(epoch_iterator): + if self.args.sync_embedding_layers: + assert model.module.model_type == 'opt', 'did not implement embedding layer synchronization for non-OPT models' + model.module.model.decoder.embed_tokens.weight = model.module.lm_head.weight + + # estimate c's (param or grad norm) on epoch 0 + if epoch == 0 and step == 0 and self.args.zo_variant is not None: + self.initialize_c(model, inputs) + elif step == 0 and self.args.zo_variant is not None and self.args.recompute_norms: + self.initialize_c(model, inputs) + + # Skip past any already trained steps if resuming training + if steps_trained_in_current_epoch > 0: + steps_trained_in_current_epoch -= 1 + continue + + if self.args.zero_order_optim: + # Get parameters that should be optimized (for layer-wise optimization and prefix-tuning) + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if self.should_optim(name, param): + self.named_parameters_to_optim.append((name, param)) + + if self.args.zo_by_layer: + assert not self.args.efficient_zero_order, 'did not implement preconditioned ZO for efficient ZO yet' + assert self.args.zero_order_use_trainer_optim, 'preconditioned ZO requires using the trainer optimizer' + num_zs = self.get_num_samples() + layers = [np.random.choice(self.layer_names)] if self.args.pc_rnd_layer else self.layer_names + + # for each layer: perturb only that layer and store the gradient estimates in the grad buffer + for layer in self.layer_names: + for _ in range(num_zs): + c_i = self.cs[layer] + with torch.no_grad(): + c_i = 1.0 if c_i == 0 else c_i # if the scaling is 0, just reset it to 1 so that there can eventually be some gradient to those layers + model, random_vector = self.perturb_single_layer(model, layer, scaling_factor=1.0/c_i) + loss1 = self.zo_forward(model, inputs) + model, random_vector = self.perturb_single_layer(model, layer, random_vector=random_vector, scaling_factor=-2.0/c_i) + loss2 = self.zo_forward(model, inputs) + model, random_vector = self.perturb_single_layer(model, layer, random_vector=random_vector, scaling_factor=1.0/c_i) + + projected_grad = (loss1 - loss2) / (2 * self.args.zero_order_eps) + # scale grad according to number of zs sampled + if not self.args.scale_lr_with_samples: + projected_grad = projected_grad / float(num_zs) + + for name, param in self.named_parameters_to_optim: + if self.retrieve_c(name) == layer: + z_tilde = random_vector[name] * c_i + + if param.grad is None: + param.grad = projected_grad * z_tilde + else: + param.grad += projected_grad * z_tilde + + # note that | E_z [ ] | is equal to norm of grad for that layer for gaussian z + # leverages this fact to update the grad norms + if self.args.zo_variant == 'grad_norm' and self.args.norm_running_update: + self.cs[layer] = torch.abs(projected_grad) + else: + # get number of zs to sample + num_zs = self.get_num_samples() + if num_zs > 1: + assert self.args.zero_order_use_trainer_optim, 'cannot sample multiple zs without storing intermediate gradient. use trainer.' + + for _ in range(num_zs): + # prepare for sampling new zs + random_vector = None + if self.args.efficient_zero_order: + random_seed = np.random.randint(1000000000) + + with torch.no_grad(): + # first function evaluation + if self.args.efficient_zero_order: + model = self.efficient_perturb_parameters(model, random_seed) + elif self.args.zo_variant is not None: + model, random_vector = self.norm_perturb_parameters(model) + else: + model, random_vector = self.perturb_parameters(model) + loss1 = self.zo_forward(model, inputs) + + # second function evaluation + if self.args.efficient_zero_order: + model = self.efficient_perturb_parameters(model, random_seed, scaling_factor=-2) + elif self.args.zo_variant is not None: + model, random_vector = self.norm_perturb_parameters(model, random_vector, scaling_factor=-2) + else: + model, random_vector = self.perturb_parameters(model, random_vector, scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + + projected_grad = (loss1 - loss2) / (2 * self.args.zero_order_eps) + + # scale grad according to accumulation + if self.args.gradient_accumulation_steps > 1: + assert self.args.zero_order_use_trainer_optim, 'grad accumulation not implemented for non-trainer ZO yet' + projected_grad = projected_grad / self.args.gradient_accumulation_steps + + # scale grad according to number of zs sampled + if not self.args.scale_lr_with_samples: + projected_grad = projected_grad / float(num_zs) + + # store gradient in parameter buffer if using trainer + # o/w, the loop will exit after one round and the update will be applied directly (see below) + if self.args.zero_order_use_trainer_optim: + if self.args.efficient_zero_order: + # print(random_seed) + torch.manual_seed(random_seed) + + for name, param in self.named_parameters_to_optim: + # recover noise used in perturbations + if self.args.efficient_zero_order: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + else: + z = random_vector[name] + + if self.args.zo_variant is not None and not self.args.change_grad_estimate: + cname = self.retrieve_c(name) + if cname in self.cs: + z = z * self.cs[cname] + + if param.grad is None: + param.grad = projected_grad * z + else: + param.grad += projected_grad * z + + # reset model back to its parameters at start of step + if self.args.efficient_zero_order: + model = self.efficient_perturb_parameters(model, random_seed) + elif self.args.zo_variant is not None: + model, random_vector = self.norm_perturb_parameters(model, random_vector) + else: + model, random_vector = self.perturb_parameters(model, random_vector) + + # apply gradient updates + # if using trainer, follow trainer logic to clip grad and check if parameters should be updated + if self.args.zero_order_use_trainer_optim: + if (step + 1) % self.args.gradient_accumulation_steps == 0 or ( + # last step in epoch but step is always smaller than gradient_accumulation_steps + len(epoch_iterator) <= self.args.gradient_accumulation_steps + and (step + 1) == len(epoch_iterator) + ): + # Gradient norm clipping + if self.args.zero_order_clip_grad: + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm) + + # Update the parameters and step scheduler + optimizer.step() + scheduler.step() + + # logging + if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or ( + self.state.global_step == 1 and self.args.logging_first_step + ): + logs = {} + logs["loss"] = loss1.item() + if not self.args.zero_order_clip_grad: + norm = 0.0 + for _, p in model.named_parameters(): + if p.grad is not None: + norm += torch.sum(p.grad ** 2) + norm = torch.sqrt(norm) + logs["grad_norm"] = norm.item() + logs["learning_rate"] = ( + scheduler.get_last_lr()[0] + if version.parse(torch.__version__) >= version.parse("1.4") + else scheduler.get_lr()[0] + ) + logs["num_zs"] = num_zs + logs["global_step"] = self.state.global_step + logs["zo_forward_step"] = self.state.zo_forward_step + logs["max_steps"] = self.args.max_steps + logs["max_zo_forward_steps"] = self.args.max_zo_forward_steps + logs["time"] = int(time.time() - start_time) + self.log(logs) + logger.info(str(logs)) + + model.zero_grad() + self.state.global_step += 1 + self.epoch = epoch + (step + 1) / len(epoch_iterator) + # if not using the trainer, the updates are resampled and directly applied to the parameters + else: + # Efficient mode + # WARNING: no gradient accumulation when not storing the grad + assert self.args.gradient_accumulation_steps == 1, 'gradient accumulation is not supported for zero-order optimization' + assert self.args.zero_order_sample_scheduler is None + assert not self.args.zero_order_clip_grad, 'gradient clipping not implemented yet for non-trainer ZO' + + if self.args.efficient_zero_order: + torch.manual_seed(random_seed) + for name, param in self.named_parameters_to_optim: + if self.args.efficient_zero_order: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + else: + z = random_vector[name] + param.data = param.data - self.args.learning_rate * (projected_grad * z + self.args.weight_decay * param.data) + + if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or ( + self.state.global_step == 1 and self.args.logging_first_step + ): + logs = {} + logs["loss"] = loss1.item() + logs["learning_rate"] = self.args.learning_rate + logs["global_step"] = self.state.global_step + logs["zo_forward_step"] = self.state.zo_forward_step + logs["max_steps"] = self.args.max_steps + logs["max_zo_forward_steps"] = self.args.max_zo_forward_steps + logs["time"] = int(time.time() - start_time) + self.log(logs) + logger.info(str(logs)) + + + self.state.global_step += 1 + self.epoch = epoch + (step + 1) / len(epoch_iterator) + + # Debug information + # print("%.5f, %.5f" % (loss1.item(), loss2.item())) + # print("Loss: %.10f, projected_grad: %.5f" % (loss1, projected_grad)) + + # standard, non-ZO optimization + else: + tr_loss += self.training_step(model, inputs) + + if (step + 1) % self.args.gradient_accumulation_steps == 0 or ( + # last step in epoch but step is always smaller than gradient_accumulation_steps + len(epoch_iterator) <= self.args.gradient_accumulation_steps + and (step + 1) == len(epoch_iterator) + ): + if self.args.fp16 and _use_native_amp: + self.scaler.unscale_(optimizer) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm) + elif self.args.fp16: + norm = torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), self.args.max_grad_norm) + else: + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm) + + if self.args.optimizer_variant == 'signgd': + for n,p in model.named_parameters(): + if p.grad is not None: + p.grad = torch.sign(p.grad) + + if transformers.is_torch_tpu_available(): + xm.optimizer_step(optimizer) + elif self.args.fp16 and _use_native_amp: + self.scaler.step(optimizer) + self.scaler.update() + else: + optimizer.step() + + scheduler.step() + model.zero_grad() + self.state.global_step += 1 + self.epoch = epoch + (step + 1) / len(epoch_iterator) + + if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or ( + self.state.global_step == 1 and self.args.logging_first_step + ): + logs = {} + tr_loss_scalar = tr_loss.item() + logs["loss"] = (tr_loss_scalar - logging_loss_scalar) / self.args.logging_steps + logs["norm"] = norm.item() + # backward compatibility for pytorch schedulers + logs["learning_rate"] = ( + scheduler.get_last_lr()[0] + if version.parse(torch.__version__) >= version.parse("1.4") + else scheduler.get_lr()[0] + ) + logging_loss_scalar = tr_loss_scalar + + self.log(logs) + logger.info(str(logs)) + + if self.args.max_steps > 0 and self.state.global_step > self.args.max_steps or (self.args.max_zo_forward_steps > 0 and self.state.zo_forward_step > self.args.max_zo_forward_steps): + epoch_iterator.close() + break + + if self.args.evaluate_during_training and self.state.global_step % self.args.eval_steps == 0: + output = self.evaluate() + metrics = output.metrics + objective = self.dev_objective(metrics) + if objective > self.objective: + logger.info("Best dev result: {}".format(objective)) + self.objective = objective + # self.save_model(self.args.output_dir) + + # Now we save this to (CPU) memory instead of disk <-- much faster + self.best_model_ckpt = {k: v.detach().cpu() for k, v in model.state_dict().items()} + + if self.args.max_steps > 0 and self.state.global_step > self.args.max_steps or (self.args.max_zo_forward_steps > 0 and self.state.zo_forward_step > self.args.max_zo_forward_steps): + # train_iterator.close() + break + if self.args.tpu_metrics_debug or self.args.debug: + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + + if self.args.past_index and hasattr(self, "_past"): + # Clean the state at the end of training + delattr(self, "_past") + + logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") + return TrainOutput(self.state.global_step, tr_loss / self.state.global_step, metrics), self.objective + + + """ + Difference compared to original implementation: return output instead of output.metrics (so there is also the logits) + """ + def evaluate(self, eval_dataset: Optional[Dataset] = None) -> Dict[str, float]: + """ + Run evaluation and returns metrics. + + The calling script will be responsible for providing a method to compute metrics, as they are + task-dependent (pass it to the init :obj:`compute_metrics` argument). + + You can also subclass and override this method to inject custom behavior. + + Args: + eval_dataset (:obj:`Dataset`, `optional`): + Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, + columns not accepted by the ``model.forward()`` method are automatically removed. It must implement + the :obj:`__len__` method. + + Returns: + A dictionary containing the evaluation loss and the potential metrics computed from the predictions. + """ + if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): + raise ValueError("eval_dataset must implement __len__") + + eval_dataloader = self.get_eval_dataloader(eval_dataset) + + output = self.prediction_loop(eval_dataloader, description="Evaluation") + + self.log(output.metrics) + logger.info(output.metrics) + + if self.args.tpu_metrics_debug or self.args.debug: + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + + return output diff --git a/baselines/lozo/medium_models/tools/gather_result.py b/baselines/lozo/medium_models/tools/gather_result.py new file mode 100644 index 0000000..708bcc9 --- /dev/null +++ b/baselines/lozo/medium_models/tools/gather_result.py @@ -0,0 +1,259 @@ +import argparse +import json +import numpy as np +import torch +from torch import device +import itertools + +from transformers.optimization import get_scheduler + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--condition", type=str, help="A dictionary contains conditions that the experiment results need to fulfill (e.g., tag, task_name, few_shot_type)") + parser.add_argument("--args_to_care", default=None, type=str, help="A list of args to care about. If provided, outputs which configs were not tested in your grid search") + + # These options should be kept as their default values + parser.add_argument("--log", type=str, default="log", help="Log path.") + parser.add_argument("--key", type=str, default='', help="Validation metric name") + parser.add_argument("--test_key", type=str, default="", help="Test metric name") + parser.add_argument("--test_key2", type=str, default="", help="Second test metric name") + + args = parser.parse_args() + + condition = eval(args.condition) + if args.args_to_care is not None: + args_to_care = eval(args.args_to_care) + + if len(args.key) == 0: + if condition['task_name'] == 'cola': + args.key = 'cola_dev_eval_mcc' + args.test_key = 'cola_test_eval_mcc' + elif condition['task_name'] == 'mrpc/acc': + args.key = 'mrpc_dev_eval_acc' + args.test_key = 'mrpc_test_eval_acc' + args.test_key2 = 'mrpc_test_eval_f1' + condition['task_name'] = 'mrpc' + elif condition['task_name'] == 'mrpc/f1': + args.key = 'mrpc_dev_eval_f1' + args.test_key2 = 'mrpc_test_eval_acc' + args.test_key = 'mrpc_test_eval_f1' + condition['task_name'] = 'mrpc' + elif condition['task_name'] == 'qqp/acc': + args.key = 'qqp_dev_eval_acc' + args.test_key = 'qqp_test_eval_acc' + args.test_key2 = 'qqp_test_eval_f1' + condition['task_name'] = 'qqp' + elif condition['task_name'] == 'qqp/f1': + args.key = 'qqp_dev_eval_f1' + args.test_key2 = 'qqp_test_eval_acc' + args.test_key = 'qqp_test_eval_f1' + condition['task_name'] = 'qqp' + elif condition['task_name'] == 'sts-b/pearson': + args.key = 'sts-b_dev_eval_pearson' + args.test_key = 'sts-b_test_eval_pearson' + args.test_key2 = 'sts-b_test_eval_spearmanr' + condition['task_name'] = 'sts-b' + elif condition['task_name'] == 'sts-b/spearmanr': + args.key = 'sts-b_dev_eval_spearmanr' + args.test_key2 = 'sts-b_test_eval_pearson' + args.test_key = 'sts-b_test_eval_spearmanr' + condition['task_name'] = 'sts-b' + elif condition['task_name'] == 'qnli': + args.key = 'qnli_dev_eval_acc' + args.test_key = 'qnli_test_eval_acc' + elif condition['task_name'] == 'sst-2': + args.key = 'sst-2_dev_eval_acc' + args.test_key = 'sst-2_test_eval_acc' + elif condition['task_name'] == 'snli': + args.key = 'snli_dev_eval_acc' + args.test_key = 'snli_test_eval_acc' + elif condition['task_name'] == 'mnli': + args.key = 'mnli_dev_eval_mnli/acc' + args.test_key = 'mnli_test_eval_mnli/acc' + elif condition['task_name'] == 'mnli-mm': + condition['task_name'] = 'mnli' + args.key = 'mnli_dev_eval_mnli/acc' + args.test_key = 'mnli-mm_test_eval_mnli-mm/acc' + elif condition['task_name'] == 'rte': + args.key = 'rte_dev_eval_acc' + args.test_key = 'rte_test_eval_acc' + elif condition['task_name'] == 'ag_news': + args.key = 'ag_news_dev_eval_acc' + args.test_key = 'ag_news_test_eval_acc' + elif condition['task_name'] == 'yahoo_answers': + args.key = 'yahoo_answers_dev_eval_acc' + args.test_key = 'yahoo_answers_test_eval_acc' + elif condition['task_name'] == 'yelp_review_full': + args.key = 'yelp_review_full_dev_eval_acc' + args.test_key = 'yelp_review_full_test_eval_acc' + elif condition['task_name'] == 'mr': + args.key = 'mr_dev_eval_acc' + args.test_key = 'mr_test_eval_acc' + elif condition['task_name'] == 'sst-5': + args.key = 'sst-5_dev_eval_acc' + args.test_key = 'sst-5_test_eval_acc' + elif condition['task_name'] == 'subj': + args.key = 'subj_dev_eval_acc' + args.test_key = 'subj_test_eval_acc' + elif condition['task_name'] == 'trec': + args.key = 'trec_dev_eval_acc' + args.test_key = 'trec_test_eval_acc' + elif condition['task_name'] == 'cr': + args.key = 'cr_dev_eval_acc' + args.test_key = 'cr_test_eval_acc' + elif condition['task_name'] == 'mpqa': + args.key = 'mpqa_dev_eval_acc' + args.test_key = 'mpqa_test_eval_acc' + else: + raise NotImplementedError + + with open(args.log) as f: + result_list = [] + for line in f: + line = line.replace("<", "\"") + line = line.replace(">", "\"") + line = line.replace(" inf,", "float('inf'),") + line = line.replace(" nan,", "float('nan'),") + result_list.append(eval(line)) + + seed_result = {} + + for item in result_list: + ok = True + for cond in condition: + if isinstance(condition[cond], list): + if cond not in item or (item[cond] not in condition[cond]): + ok = False + break + else: + if cond not in item or (item[cond] != condition[cond]): + ok = False + break + if ok and args.test_key in item and args.key in item: + seed = item['data_dir'].split('-')[-1] + '-' + str(item['seed']) + if seed not in seed_result: + seed_result[seed] = [item] + else: + seed_result[seed].append(item) + + all_seed_result = seed_result + all_tags = sorted(set(x['tag'] for x in sum(all_seed_result.values(), []))) + all_k = sorted(set(x['num_k'] for x in sum(all_seed_result.values(), []))) + + for tag in all_tags: + for k in all_k: + print("Tag: {}, K: {}".format(tag, k)) + seed_result_with_duplicates = { + s: list(x for x in v if x['tag'] == tag and x['num_k'] == k) + for s, v in all_seed_result.items() + } + seed_result = { + s: list({x['output_dir']: x for x in v}.values()) + for s, v in seed_result_with_duplicates.items() + } + seed_best = { + k: max(sorted(v, key=lambda x: x['output_dir']), key=lambda x: x[args.key]) + for k, v in seed_result.items() if v + } + + ### check if all possible configs were run or not + if args.args_to_care is not None: + unique_arg_values = {} + for _arg in args_to_care: + unique_arg_values[_arg] = [] + + # collect all desired configs and all that were run + arg_configs = {} # all configs that were run + for seed in seed_result.keys(): + seed_configs = [] + for config in seed_result[seed]: + if config['tag'] == tag and config['num_k'] == k: + _config = [] + for _arg in args_to_care: + _value = config[_arg] + if _value not in unique_arg_values[_arg]: + unique_arg_values[_arg].append(_value) + _config.append(_value) + seed_configs.append(tuple(_config)) + arg_configs[seed] = seed_configs + + # compare to all possible configs + missing_configs = {'seeds': []} + for arg in args_to_care: + missing_configs[f'{arg}s'] = [] + + num_missing = 0 + for seed in seed_result.keys(): + all_possible_configs = itertools.product(*list(unique_arg_values.values())) + print(f'Missing configs for seed {seed}') + for config in all_possible_configs: + if config not in arg_configs[seed]: + missing_configs['seeds'].append(seed.split('-')[-1]) + print(f'\t', end='') + for _arg, _val in zip(args_to_care, config): + print(f'{_arg}: {_val}', end=' ') + missing_configs[f'{_arg}s'].append(str(_val)) + print() + num_missing += 1 + + print(f'Rerun {num_missing} configs') + for key, missed in missing_configs.items(): + missed_str = ' '.join(missed) + print(f'{key}=({missed_str})') + + final_result_dev = np.zeros((len(seed_best))) + final_result_test = np.zeros((len(seed_best))) + final_result_test2 = np.zeros((len(seed_best))) + final_result_loss = np.zeros((len(seed_best))) + num_results = np.zeros((len(seed_best))) + for i, seed in enumerate(seed_best): + # for res in seed_result[seed]: + # print(res) + + final_result_dev[i] = seed_best[seed][args.key] + final_result_test[i] = seed_best[seed][args.test_key] + test_loss_key = args.test_key.split("_eval")[0] + "_eval_loss" + dev_loss_key = test_loss_key.replace("test", "dev") + final_result_loss[i] = seed_best[seed][test_loss_key] + num_results[i] = len(seed_result[seed]) + if len(args.test_key2) > 0: + final_result_test2[i] = seed_best[seed][args.test_key2] + print("%s: best dev (%.5f, loss=%.4f) test (%.5f, loss=%.4f) %s | total trials: %d (ignored %d)" % ( + seed, + seed_best[seed][args.key], + seed_best[seed][dev_loss_key], + seed_best[seed][args.test_key], + seed_best[seed][test_loss_key], + "test2 (%.5f)" % (seed_best[seed][args.test_key2]) if len(args.test_key2) > 0 else "", + len(seed_result[seed]), + len(seed_result_with_duplicates[seed]) - len(seed_result[seed]) + )) + s = '' + if args.args_to_care is None: + hp_to_care_about = [ + 'per_device_train_batch_size', + 'gradient_accumulation_steps', + 'learning_rate', + 'zero_order_eps', + 'zero_order_sample', + 'zero_order_sample_scheduler', + 'scale_lr_with_samples', + 'lr_scheduler_type', + 'weight_decay', + ] + else: + hp_to_care_about = args_to_care + for k in hp_to_care_about: + s += '| {}: {} '.format(k, seed_best[seed].get(k, "")) + print(' ' + s) + s = "mean +- std: " + if len(final_result_test) > 0: + s += "%.1f (%.1f) (#seeds %s) (#runs %s) (median %.1f)" % (final_result_test.mean() * 100, final_result_test.std() * 100, len(final_result_test), num_results.sum(), np.median(final_result_test) * 100,) + if len(args.test_key2) > 0: + s += " | second metric: %.1f (%.1f) (median %.1f)" % (final_result_test2.mean() * 100, final_result_test2.std() * 100, np.median(final_result_test2) * 100) + s += " | loss: %.4f (%.4f)" % (final_result_loss.mean(), final_result_loss.std()) + print(s) + print("") + +if __name__ == '__main__': + main() diff --git a/baselines/lozo/medium_models/tools/generate_k_shot_data.py b/baselines/lozo/medium_models/tools/generate_k_shot_data.py new file mode 100644 index 0000000..8196809 --- /dev/null +++ b/baselines/lozo/medium_models/tools/generate_k_shot_data.py @@ -0,0 +1,192 @@ +"""This script samples K examples randomly without replacement from the original data.""" + +import argparse +import os +import numpy as np +import pandas as pd +from pandas import DataFrame + +def get_label(task, line): + if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]: + # GLUE style + line = line.strip().split('\t') + if task == 'CoLA': + return line[1] + elif task == 'MNLI': + return line[-1] + elif task == 'MRPC': + return line[0] + elif task == 'QNLI': + return line[-1] + elif task == 'QQP': + return line[-1] + elif task == 'RTE': + return line[-1] + elif task == 'SNLI': + return line[-1] + elif task == 'SST-2': + return line[-1] + elif task == 'STS-B': + return 0 if float(line[-1]) < 2.5 else 1 + elif task == 'WNLI': + return line[-1] + else: + raise NotImplementedError + else: + return line[0] + +def load_datasets(data_dir, tasks): + datasets = {} + for task in tasks: + if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]: + # GLUE style (tsv) + dataset = {} + dirname = os.path.join(data_dir, task) + if task == "MNLI": + splits = ["train", "dev_matched", "dev_mismatched"] + else: + splits = ["train", "dev"] + for split in splits: + filename = os.path.join(dirname, f"{split}.tsv") + with open(filename, "r") as f: + lines = f.readlines() + dataset[split] = lines + datasets[task] = dataset + else: + # Other datasets (csv) + dataset = {} + dirname = os.path.join(data_dir, task) + splits = ["train", "test"] + for split in splits: + filename = os.path.join(dirname, f"{split}.csv") + dataset[split] = pd.read_csv(filename, header=None) + datasets[task] = dataset + return datasets + +def split_header(task, lines): + """ + Returns if the task file has a header or not. Only for GLUE tasks. + """ + if task in ["CoLA"]: + return [], lines + elif task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI"]: + return lines[0:1], lines[1:] + else: + raise ValueError("Unknown GLUE task.") + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--k", type=int, default=16, + help="Training examples for each class.") + parser.add_argument("--task", type=str, nargs="+", + default=['SST-2', 'sst-5', 'mr', 'cr', 'mpqa', 'subj', 'trec', 'CoLA', 'MRPC', 'QQP', 'STS-B', 'MNLI', 'SNLI', 'QNLI', 'RTE'], + help="Task names") + parser.add_argument("--seed", type=int, nargs="+", + default=[100, 13, 21, 42, 87], + help="Random seeds") + + parser.add_argument("--data_dir", type=str, default="data/original", help="Path to original data") + parser.add_argument("--output_dir", type=str, default="data", help="Output path") + parser.add_argument("--mode", type=str, default='k-shot', choices=['k-shot', 'k-shot-10x', 'k-shot-1k-test'], help="k-shot or k-shot-10x (10x dev set)") + + args = parser.parse_args() + args.output_dir = os.path.join(args.output_dir, args.mode) + + k = args.k + print("K =", k) + datasets = load_datasets(args.data_dir, args.task) + + for seed in args.seed: + print("Seed = %d" % (seed)) + for task, dataset in datasets.items(): + # Set random seed + np.random.seed(seed) + + # Shuffle the training set + print("| Task = %s" % (task)) + if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]: + # GLUE style + train_header, train_lines = split_header(task, dataset["train"]) + np.random.shuffle(train_lines) + else: + # Other datasets + train_lines = dataset['train'].values.tolist() + np.random.shuffle(train_lines) + + # Set up dir + task_dir = os.path.join(args.output_dir, task) + setting_dir = os.path.join(task_dir, f"{k}-{seed}") + os.makedirs(setting_dir, exist_ok=True) + + # Write test splits + if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]: + # GLUE style + # Use the original development set as the test set (the original test sets are not publicly available) + for split, lines in dataset.items(): + if split.startswith("train"): + continue + split = split.replace('dev', 'test') + + test_header, test_lines = split_header(task, lines) + if '1k-test' in args.mode and len(test_lines) > 1000: + np.random.seed(42) + np.random.shuffle(test_lines) + test_lines = test_lines[:1000] + with open(os.path.join(setting_dir, f"{split}.tsv"), "w") as f: + for line in test_header: + f.write(line) + for line in test_lines: + f.write(line) + else: + # Other datasets + # Use the original test sets + test_dataset = dataset['test'] + if '1k-test' in args.mode and len(test_dataset.index) > 1000: + test_dataset = test_dataset.sample(n=1000, random_state=42) + test_dataset.to_csv(os.path.join(setting_dir, 'test.csv'), header=False, index=False) + + # Get label list for balanced sampling + label_list = {} + for line in train_lines: + label = get_label(task, line) + if label not in label_list: + label_list[label] = [line] + else: + label_list[label].append(line) + + if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]: + with open(os.path.join(setting_dir, "train.tsv"), "w") as f: + for line in train_header: + f.write(line) + for label in label_list: + for line in label_list[label][:k]: + f.write(line) + name = "dev.tsv" + if task == 'MNLI': + name = "dev_matched.tsv" + with open(os.path.join(setting_dir, name), "w") as f: + for line in train_header: + f.write(line) + for label in label_list: + dev_rate = 11 if '10x' in args.mode else 2 + for line in label_list[label][k:k*dev_rate]: + f.write(line) + else: + new_train = [] + for label in label_list: + for line in label_list[label][:k]: + new_train.append(line) + new_train = DataFrame(new_train) + new_train.to_csv(os.path.join(setting_dir, 'train.csv'), header=False, index=False) + + new_dev = [] + for label in label_list: + dev_rate = 11 if '10x' in args.mode else 2 + for line in label_list[label][k:k*dev_rate]: + new_dev.append(line) + new_dev = DataFrame(new_dev) + new_dev.to_csv(os.path.join(setting_dir, 'dev.csv'), header=False, index=False) + + +if __name__ == "__main__": + main() diff --git a/baselines/lozo/native.py b/baselines/lozo/native.py new file mode 100644 index 0000000..89c3939 --- /dev/null +++ b/baselines/lozo/native.py @@ -0,0 +1,71 @@ +"""Run the original entry point with shared local assets. No optimizer rewrite.""" +import argparse +from datetime import datetime,timezone +import json +import os +from pathlib import Path +import runpy +import sys + +HERE=Path(__file__).resolve().parent +ROOT=HERE.parents[1] +sys.path.insert(0,str(ROOT/'src')) +from experiments_codebase.paths import paths,model_path,save + +def main(): + p=argparse.ArgumentParser(description=__doc__,add_help=False) + p.add_argument('--asset-model',default='facebook/opt-1.3b') + p.add_argument('--asset-task',choices=['sst2','drop'],default='sst2') + p.add_argument('--asset-out',type=Path) + args,rest=p.parse_known_args();method=HERE.name + roots=paths();os.environ.setdefault('WANDB_MODE','disabled');os.environ['WANDB_DIR']=str(roots['results']/'wandb') + out=(args.asset_out or roots['results']/f'native_{method}_{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}').resolve() + if not out.is_relative_to(roots['results'].resolve()):raise ValueError('Output must be under shared results') + # Both local datasets are supplied through the HF Dataset API expected by authors. + import datasets + original=datasets.load_dataset + def local_dataset(name,*pos,**kw): + config=pos[0] if pos else kw.get('name') + alias='sst2' if (name in ('glue','nyu-mll/glue') and config=='sst2') or name=='sst2' else ('drop' if name in ('drop','ucinlp/drop') else None) + if alias: + ds=datasets.load_from_disk(str(roots['data']/alias)) + split=kw.get('split');return ds[split] if split else ds + return original(name,*pos,**kw) + datasets.load_dataset=local_dataset + model=str(model_path(args.asset_model)) + if method=='loren': + if args.asset_task=='drop':raise ValueError('Official LOREN has no DROP task; use run_compatible.py with the modern group for a labeled task extension') + if 'Qwen' in args.asset_model:raise ValueError('Official LOREN has no Qwen model branch; use the modern compatibility entry') + entry=HERE/'main.py' + defaults=['--model_name',model,'--task',args.asset_task,'--algorithm','LOREN','--results',str(out),'--full_parameter'] + else: + work=HERE/('zo-bench' if method=='agzo' else 'large_models') + entry=work/('run_lozo.py' if method=='lozo' else 'run.py') + task='SST2' if args.asset_task=='sst2' else 'DROP' + defaults=['--model_name',model,'--task_name',task,'--output_dir',str(out),'--trainer',{'mezo':'zo','lozo':'LOZO','agzo':'agzo'}[method], + '--report_to','none','--train_set_seed','42','--train_as_classification',str(task=='SST2'),'--lr_scheduler_type','constant'] + defaults+=['--result_file',str(out/'result.json')] + # User's original HF/author flags appear last and override wrapper defaults. + if '--help' not in rest: + out.mkdir(parents=True,exist_ok=False) + save(out/'launch.json',dict(method=method,entry=str(entry),argv=defaults+rest,executable=sys.executable,adapter='Local assets and paths only; original Trainer/optimizer',pid=os.getpid())) + sys.path.insert(0,str(entry.parent));os.chdir(out if out.exists() else HERE) + sys.argv=[str(entry),*defaults,*rest] + if method=='agzo': + import torch + if torch.cuda.is_available() and not hasattr(torch,'npu'): + # The author's NPU helper has incomplete CUDA branches. Only device + # plumbing is adapted; trainer.py and AGZO numerical methods are intact. + import npu_compat as devices + devices.device_count=torch.cuda.device_count + devices.mem_get_info=torch.cuda.mem_get_info + devices.get_active_device_info=lambda:('cuda',torch.cuda.current_device(),torch.cuda.get_device_properties(0).total_memory/2**30,torch.cuda.get_device_name()) + devices.safe_set_device=lambda index:(torch.cuda.set_device(int(index or 0)) or int(index or 0),torch.cuda.device_count()) + devices.to_device=lambda tensor:tensor.cuda() + source=entry.read_text().replace('torch.npu.manual_seed_all(seed)','torch.cuda.manual_seed_all(seed)').replace('torch.npu.device_count()','torch.cuda.device_count()') + if out.exists():save(out/'compatibility_changes.json',{'scope':'CUDA device plumbing only','source_modified_on_disk':False,'numerical_optimizer_modified':False,'changes':['NPU seed -> CUDA seed','NPU device count -> CUDA count','device helper memory/info/count/set/to_device CUDA callbacks']}) + exec(compile(source,str(entry),'exec'),dict(__name__='__main__',__file__=str(entry))) + return + runpy.run_path(str(entry),run_name='__main__') + +if __name__=='__main__':main() diff --git a/baselines/lozo/pyproject.toml b/baselines/lozo/pyproject.toml new file mode 100644 index 0000000..77500f3 --- /dev/null +++ b/baselines/lozo/pyproject.toml @@ -0,0 +1,14 @@ +[project] +name = "official-lozo-experiment" +version = "0.1.0" +requires-python = ">=3.11,<3.12" +dependencies = ["torch==2.13.0", "setuptools==80.9.0", "numpy==1.26.4", "matplotlib==3.10.7", "psutil==7.1.3", "scikit-learn==1.7.2", "sentencepiece==0.2.1", "wandb==0.23.1", "rouge==1.0.1", "nltk==3.9.2", "einops==0.8.1"] + +[dependency-groups] +native = ["transformers==4.28.1", "datasets==2.14.7", "pyarrow==17.0.0", "accelerate==0.20.3", "huggingface-hub==0.36.0"] +modern = ["transformers==4.57.1", "datasets==3.6.0", "pyarrow==20.0.0", "accelerate==1.12.0", "huggingface-hub==0.36.0"] + +[tool.uv] +package = false +default-groups = ["native"] +conflicts = [[{group="native"}, {group="modern"}]] diff --git a/baselines/lozo/run_compatible.py b/baselines/lozo/run_compatible.py new file mode 100644 index 0000000..801ed52 --- /dev/null +++ b/baselines/lozo/run_compatible.py @@ -0,0 +1,7 @@ +"""Modern task adapter calling pinned official numerical methods; not the original Trainer.""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'src')) +from experiments_codebase.runner import main +if __name__ == '__main__': + main(forced_method='lozo') diff --git a/baselines/lozo/uv.lock b/baselines/lozo/uv.lock new file mode 100644 index 0000000..bf092ea --- /dev/null +++ b/baselines/lozo/uv.lock @@ -0,0 +1,1711 @@ +version = 1 +revision = 3 +requires-python = "==3.11.*" +resolution-markers = [ + "sys_platform == 'linux' and extra != 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native'", + "sys_platform == 'win32' and extra != 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native'", + "sys_platform == 'emscripten' and extra != 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32' and extra != 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native'", + "sys_platform == 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra != 'group-24-official-lozo-experiment-native'", + "sys_platform == 'win32' and extra == 'group-24-official-lozo-experiment-modern' and extra != 'group-24-official-lozo-experiment-native'", + "sys_platform == 'emscripten' and extra == 'group-24-official-lozo-experiment-modern' and extra != 'group-24-official-lozo-experiment-native'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32' and extra == 'group-24-official-lozo-experiment-modern' and extra != 'group-24-official-lozo-experiment-native'", + "sys_platform == 'linux' and extra != 'group-24-official-lozo-experiment-modern' and extra != 'group-24-official-lozo-experiment-native'", + "sys_platform != 'linux' and extra != 'group-24-official-lozo-experiment-modern' and extra != 'group-24-official-lozo-experiment-native'", +] +conflicts = [[ + { package = "official-lozo-experiment", group = "modern" }, + { package = "official-lozo-experiment", group = "native" }, +]] + +[[package]] +name = "accelerate" +version = "0.20.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyyaml" }, + { name = "torch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1a/fe/5a4a583065c410f5a3dcb9b4f202e6b9191d3e965f007c63c85ea135cd46/accelerate-0.20.3.tar.gz", hash = "sha256:79a896978c20dac270083d42bf033f4c9a80dcdd6b946f1ca92d8d6d0f0f5ba9", size = 213044, upload-time = "2023-06-08T16:16:36.887Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/d3/5382aa337d3e67214003a17b06bfc07cf0334356b4e8aaf3b12b0d38c83f/accelerate-0.20.3-py3-none-any.whl", hash = "sha256:147183e7a2215f7bd45a7af3b986a963daa8a61fa58b0912b9473049e011ad15", size = 227580, upload-time = "2023-06-08T16:16:34.728Z" }, +] + +[[package]] +name = "accelerate" +version = "1.12.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyyaml" }, + { name = "safetensors" }, + { name = "torch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4a/8e/ac2a9566747a93f8be36ee08532eb0160558b07630a081a6056a9f89bf1d/accelerate-1.12.0.tar.gz", hash = "sha256:70988c352feb481887077d2ab845125024b2a137a5090d6d7a32b57d03a45df6", size = 398399, upload-time = "2025-11-21T11:27:46.973Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/d2/c581486aa6c4fbd7394c23c47b83fa1a919d34194e16944241daf9e762dd/accelerate-1.12.0-py3-none-any.whl", hash = "sha256:3e2091cd341423207e2f084a6654b1efcd250dc326f2a37d6dde446e07cabb11", size = 380935, upload-time = "2025-11-21T11:27:44.522Z" }, +] + +[[package]] +name = "aiohappyeyeballs" +version = "2.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/f4/eec0465c2f67b2664688d0240b3212d5196fd89e741df67ddb81f8d35658/aiohappyeyeballs-2.7.1.tar.gz", hash = "sha256:065665c041c42a5938ed220bdcd7230f22527fbec085e1853d2402c8a3615d9d", size = 24757, upload-time = "2026-07-01T17:11:55.501Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/43/1947f06babed6b3f1d7f38b0c767f52df66bfb2bc10b468c4a7de9eceff2/aiohappyeyeballs-2.7.1-py3-none-any.whl", hash = "sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472", size = 15038, upload-time = "2026-07-01T17:11:54.055Z" }, +] + +[[package]] +name = "aiohttp" +version = "3.14.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohappyeyeballs" }, + { name = "aiosignal" }, + { name = "attrs" }, + { name = "frozenlist" }, + { name = "multidict" }, + { name = "propcache" }, + { name = "typing-extensions" }, + { name = "yarl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6c/4c/bdccd81e9ee225b69c60e7766c9a5b05364f118f4d383713b89a682d772d/aiohttp-3.14.5.tar.gz", hash = "sha256:5558a7f5a05af9ecf744af91e5baefc436f93c9333e656c27ec253f9a6bbe178", size = 8078052, upload-time = "2026-10-11T01:05:12.408Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d8/f3/8997f18890a92c79f77fcfbb4f78ca17c2d4ab109e9eb6d31b4e9de194a0/aiohttp-3.14.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d51db97c96384fbfcaf8f4c65922183a68b94f891c3c10c862ef5f6df2adbb1f", size = 832358, upload-time = "2026-10-11T00:59:42.195Z" }, + { url = "https://files.pythonhosted.org/packages/8e/42/084651e9efb5cadb99265f786df60f2a7b353cead7bfd2c87003cb4867ad/aiohttp-3.14.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ae53924aa853a7a2ca20ed4142c7c6b56338e4d4cd999e2980075b9efc2e257a", size = 559636, upload-time = "2026-10-11T00:59:43.677Z" }, + { url = "https://files.pythonhosted.org/packages/3d/fe/92838944e601f0fe195fd3f3ada37e29fbee3d19bfd323fe15937ec79d36/aiohttp-3.14.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a2c473a355f9239efcb72c92d5abfd8fcdb0cc78c8e9af607e72ca12dbb36593", size = 552588, upload-time = "2026-10-11T00:59:45.592Z" }, + { url = "https://files.pythonhosted.org/packages/8f/b8/dd9b95c5c20ceae1b47738e656bd79e9883e3117a9cc8b143901eb604e9a/aiohttp-3.14.5-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:32e8fa6644e541fcd7e02430588c7fc93b602c1778ea0bc345505db76b61cfb4", size = 1928224, upload-time = "2026-10-11T00:59:47.294Z" }, + { url = "https://files.pythonhosted.org/packages/c6/47/70010cd2ba8746968d53d433ff328c33f06a66c99da5f3de759c64a6b2eb/aiohttp-3.14.5-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:579f97d5120f2971876d2ddca2968135f6944d00c44c3a6590ad7d86ca9b403f", size = 1877674, upload-time = "2026-10-11T00:59:49.472Z" }, + { url = "https://files.pythonhosted.org/packages/c5/a1/b026f071dbd87f0bdba86b92d47e46f3899e3ad7143b6e0fe7e7887090b4/aiohttp-3.14.5-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:24409db442e2fb6e766bc7f3943851a8381dec3098140e43bb2e843b79e31b12", size = 1985850, upload-time = "2026-10-11T00:59:51.296Z" }, + { url = "https://files.pythonhosted.org/packages/36/d1/f7b6f6f8c3cb5a71b53baeddc2e70c224c28b12a23a55c42994c504019b7/aiohttp-3.14.5-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5e8f97c0488ffda3082766ac0f2c8150a9a58c4d05788330e479cfd449b37939", size = 2105471, upload-time = "2026-10-11T00:59:53.191Z" }, + { url = "https://files.pythonhosted.org/packages/42/74/2a2b22953de15c6c8a80debf26db3047e4e8a5a5db6dd7c2c6c01eec0605/aiohttp-3.14.5-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50a195903119008fe9cc68710535eb37f556ffffd6a7759afe70a2c145587045", size = 1929915, upload-time = "2026-10-11T00:59:55.609Z" }, + { url = "https://files.pythonhosted.org/packages/33/ad/f80e8d33933d0eacd0217efa3b7fb32c9f48ed480ed0db53cf9948bf474f/aiohttp-3.14.5-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0133c3c3b54a0bf1e71fa5c1ad95c93f07fd54e24ef1fe182f5122e1573d2bf1", size = 1773832, upload-time = "2026-10-11T00:59:57.611Z" }, + { url = "https://files.pythonhosted.org/packages/04/a4/0273d239f3e3bb69438f209c64c82e1f98dc60d5db264795e41f7dd05dcb/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c172db893e516e1358e65a95ee20b7ce7173963eefe318b6ab2a2220688b999e", size = 1901001, upload-time = "2026-10-11T01:00:00.605Z" }, + { url = "https://files.pythonhosted.org/packages/16/ed/7dd439d26c654645bc34ca3c9a822fc11c1c51801fed1cefdfe1cc41c1f6/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:f2a7966bda23dd85051f1661ce0ace38d6890e05ec6c357ecae9d2479cba377e", size = 1907218, upload-time = "2026-10-11T01:00:02.699Z" }, + { url = "https://files.pythonhosted.org/packages/32/dd/86249c3b8248562a17fd3e22ee0c164378d65766f01aceef62cf52783710/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:4887d130a7bbfed3a85493bb5a25e5b5b558d40c1d986dd16970d2bb26d63793", size = 1958650, upload-time = "2026-10-11T01:00:04.851Z" }, + { url = "https://files.pythonhosted.org/packages/bc/0b/ca4d53d68f683ce195807fd0aeb063bf6d1c6b39343fff234c9524e8d5a9/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:225c579c23b68b343cccea27a7e06e3bd8ec23a09c30b427eb3f1e4ca6239b20", size = 1760057, upload-time = "2026-10-11T01:00:06.978Z" }, + { url = "https://files.pythonhosted.org/packages/6b/42/005437ffd7fa56c2ce3347add40404b654a32754ce91f2e2a14b9e5ab2bc/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:ab52d8f1fc1b64821c1fbad64a647ed6203627004059a6d1ed4f0858a1499703", size = 1978081, upload-time = "2026-10-11T01:00:08.868Z" }, + { url = "https://files.pythonhosted.org/packages/03/71/3a5b66fe1b7b23d3c6524350817ed55de5feb7fbb4cccba7cbe044d118dd/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:cb131d775a1573c1aee66656bd78b023577bbdb6cb8349a07773bd4f73e68a6e", size = 1922954, upload-time = "2026-10-11T01:00:11.035Z" }, + { url = "https://files.pythonhosted.org/packages/69/84/d08a554f281d42fd7c6b2b6dd7738f3e3a7a9f657ddd87e11ca2091cdfe3/aiohttp-3.14.5-cp311-cp311-win32.whl", hash = "sha256:e87046c8ff77a8decdb6a41d8ab25824b47531b2da933aeab0c1e21c7acff329", size = 488101, upload-time = "2026-10-11T01:00:12.933Z" }, + { url = "https://files.pythonhosted.org/packages/0f/15/52b5e65f02b33686ae49f1518548ae4f5a7adaf31d9d3c54fa12a143137b/aiohttp-3.14.5-cp311-cp311-win_amd64.whl", hash = "sha256:6f275c11d1aa6d4c458e05a68be084efe3c55a113d99e3f46a318098e52948fc", size = 512575, upload-time = "2026-10-11T01:00:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/b0/b9/bb75012635f3defb0f7cbb7c4ae391e36bb9cb3fbdca3b9944e2ebebf743/aiohttp-3.14.5-cp311-cp311-win_arm64.whl", hash = "sha256:b032a0023eb41d768ce77d83210ab2a3c389bc0b09313273c7e1eca48c10a755", size = 493179, upload-time = "2026-10-11T01:00:16.961Z" }, + { url = "https://files.pythonhosted.org/packages/68/30/173960c42b05a6c59f7558e4b12a4b0d9ba376cf6aa9bde7f9e08a30ca8d/aiohttp-3.14.5-py3-none-any.whl", hash = "sha256:efc21a454892828368b11c2c780de0ff8bc991f73f6b99c6b66e56205470929b", size = 279517, upload-time = "2026-10-11T01:05:08.523Z" }, +] + +[[package]] +name = "aiosignal" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "frozenlist" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, +] + +[[package]] +name = "annotated-types" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "certifi" +version = "2026.10.23" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/67/6a0b94a7960d5e1b5eacd2fb529f3fccc47db4644f7f0a7cfdcfc3be578a/charset_normalizer-3.5.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6", size = 370642, upload-time = "2026-09-30T04:35:06.91Z" }, + { url = "https://files.pythonhosted.org/packages/fb/94/01009e13b94041599004edf32e56e382c24e570f60f79bab8efe45cfe1eb/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5", size = 259280, upload-time = "2026-09-30T04:35:08.448Z" }, + { url = "https://files.pythonhosted.org/packages/66/85/3b5358f60a13210f0b67d3755c168ef758701b021e655d88d4da28554467/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74", size = 245335, upload-time = "2026-09-30T04:35:10.104Z" }, + { url = "https://files.pythonhosted.org/packages/74/75/77c1c479b09ecd751d1e767b251ea5c14d4d50ff757bf404afab2692f600/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab", size = 291707, upload-time = "2026-09-30T04:35:11.575Z" }, + { url = "https://files.pythonhosted.org/packages/0b/0d/363f78cacb70f58f15f4b083961bbd9d292f335d3f5c66fc4f1cfe69cb90/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c", size = 286747, upload-time = "2026-09-30T04:35:13.022Z" }, + { url = "https://files.pythonhosted.org/packages/e4/ed/cf505d3011ffceb12c2067a7a5d3cfe92b875d4d44bb0ff0d69375e2c184/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f", size = 269972, upload-time = "2026-09-30T04:35:14.606Z" }, + { url = "https://files.pythonhosted.org/packages/15/d8/f0a93a431d170e7ca681d4f6650fee3de934d18560e474e7267eb4b0f987/charset_normalizer-3.5.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288", size = 269339, upload-time = "2026-09-30T04:35:16.087Z" }, + { url = "https://files.pythonhosted.org/packages/86/bd/9b2bd1c5b7af02462c9752d33994834ff972a96b4c483eefde9e594488e2/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400", size = 261683, upload-time = "2026-09-30T04:35:17.488Z" }, + { url = "https://files.pythonhosted.org/packages/76/a5/cac540ab0fd61f3fec88ad3dbb64509e71424593d73cfdfff5ab3e4db279/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd", size = 248143, upload-time = "2026-09-30T04:35:18.849Z" }, + { url = "https://files.pythonhosted.org/packages/71/7a/ff467301deef2089fad87f72df9e000a26a78fec7acbb18e1999371b8369/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37", size = 292358, upload-time = "2026-09-30T04:35:20.326Z" }, + { url = "https://files.pythonhosted.org/packages/ad/77/22d7e785d1e210afc2e2f58600dd1799d17a35665faf84383f002826c5f8/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac", size = 268766, upload-time = "2026-09-30T04:35:21.72Z" }, + { url = "https://files.pythonhosted.org/packages/ae/91/e8e946267f1c2d9e2bd651726e2fbd2addf02c4d36cea5069e32ca9d7bb5/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a", size = 287432, upload-time = "2026-09-30T04:35:23.273Z" }, + { url = "https://files.pythonhosted.org/packages/4e/88/7561d8a88d555e7df6623abe7c0070b4baf47549b9408783a2ae0a1a6cf7/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640", size = 272470, upload-time = "2026-09-30T04:35:24.655Z" }, + { url = "https://files.pythonhosted.org/packages/35/7e/578c702301ec036f01455f30744a08d2b42f6ab35b9b2d4bf8cae0ef2a80/charset_normalizer-3.5.2-cp311-cp311-win32.whl", hash = "sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d", size = 186688, upload-time = "2026-09-30T04:35:26.225Z" }, + { url = "https://files.pythonhosted.org/packages/e8/fc/fdf8cf52ff21cd5bf158f20978991cf985325842f74283eb6df26c8a39d8/charset_normalizer-3.5.2-cp311-cp311-win_amd64.whl", hash = "sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96", size = 214932, upload-time = "2026-09-30T04:35:27.796Z" }, + { url = "https://files.pythonhosted.org/packages/97/66/3e45a506d8110b632541faf9a9470185aa9878f1ed44020f31346c1c5e5b/charset_normalizer-3.5.2-cp311-cp311-win_arm64.whl", hash = "sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1", size = 202828, upload-time = "2026-09-30T04:35:29.259Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" }, + { url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" }, + { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" }, + { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" }, + { url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" }, +] + +[[package]] +name = "click" +version = "8.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, +] + +[[package]] +name = "cloudpickle" +version = "3.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/27/fb/576f067976d320f5f0114a8d9fa1215425441bb35627b1993e5afd8111e5/cloudpickle-3.1.2.tar.gz", hash = "sha256:7fda9eb655c9c230dab534f1983763de5835249750e85fbcef43aaa30a9a2414", size = 22330, upload-time = "2025-11-03T09:25:26.604Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/39/799be3f2f0f38cc727ee3b4f1445fe6d5e4133064ec2e4115069418a5bb6/cloudpickle-3.1.2-py3-none-any.whl", hash = "sha256:9acb47f6afd73f60dc1df93bb801b472f05ff42fa6c84167d25cb206be1fbf4a", size = 22228, upload-time = "2025-11-03T09:25:25.534Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "contourpy" +version = "1.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/91/2e/c4390a31919d8a78b90e8ecf87cd4b4c4f05a5b48d05ec17db8e5404c6f4/contourpy-1.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:709a48ef9a690e1343202916450bc48b9e51c049b089c7f79a267b46cffcdaa1", size = 288773, upload-time = "2025-07-26T12:01:02.277Z" }, + { url = "https://files.pythonhosted.org/packages/0d/44/c4b0b6095fef4dc9c420e041799591e3b63e9619e3044f7f4f6c21c0ab24/contourpy-1.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:23416f38bfd74d5d28ab8429cc4d63fa67d5068bd711a85edb1c3fb0c3e2f381", size = 270149, upload-time = "2025-07-26T12:01:04.072Z" }, + { url = "https://files.pythonhosted.org/packages/30/2e/dd4ced42fefac8470661d7cb7e264808425e6c5d56d175291e93890cce09/contourpy-1.3.3-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:929ddf8c4c7f348e4c0a5a3a714b5c8542ffaa8c22954862a46ca1813b667ee7", size = 329222, upload-time = "2025-07-26T12:01:05.688Z" }, + { url = "https://files.pythonhosted.org/packages/f2/74/cc6ec2548e3d276c71389ea4802a774b7aa3558223b7bade3f25787fafc2/contourpy-1.3.3-cp311-cp311-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e999574eddae35f1312c2b4b717b7885d4edd6cb46700e04f7f02db454e67c1", size = 377234, upload-time = "2025-07-26T12:01:07.054Z" }, + { url = "https://files.pythonhosted.org/packages/03/b3/64ef723029f917410f75c09da54254c5f9ea90ef89b143ccadb09df14c15/contourpy-1.3.3-cp311-cp311-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0bf67e0e3f482cb69779dd3061b534eb35ac9b17f163d851e2a547d56dba0a3a", size = 380555, upload-time = "2025-07-26T12:01:08.801Z" }, + { url = "https://files.pythonhosted.org/packages/5f/4b/6157f24ca425b89fe2eb7e7be642375711ab671135be21e6faa100f7448c/contourpy-1.3.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e79c1f7470158e838808d4a996fa9bac72c498e93d8ebe5119bc1e6becb0db", size = 355238, upload-time = "2025-07-26T12:01:10.319Z" }, + { url = "https://files.pythonhosted.org/packages/98/56/f914f0dd678480708a04cfd2206e7c382533249bc5001eb9f58aa693e200/contourpy-1.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:598c3aaece21c503615fd59c92a3598b428b2f01bfb4b8ca9c4edeecc2438620", size = 1326218, upload-time = "2025-07-26T12:01:12.659Z" }, + { url = "https://files.pythonhosted.org/packages/fb/d7/4a972334a0c971acd5172389671113ae82aa7527073980c38d5868ff1161/contourpy-1.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:322ab1c99b008dad206d406bb61d014cf0174df491ae9d9d0fac6a6fda4f977f", size = 1392867, upload-time = "2025-07-26T12:01:15.533Z" }, + { url = "https://files.pythonhosted.org/packages/75/3e/f2cc6cd56dc8cff46b1a56232eabc6feea52720083ea71ab15523daab796/contourpy-1.3.3-cp311-cp311-win32.whl", hash = "sha256:fd907ae12cd483cd83e414b12941c632a969171bf90fc937d0c9f268a31cafff", size = 183677, upload-time = "2025-07-26T12:01:17.088Z" }, + { url = "https://files.pythonhosted.org/packages/98/4b/9bd370b004b5c9d8045c6c33cf65bae018b27aca550a3f657cdc99acdbd8/contourpy-1.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:3519428f6be58431c56581f1694ba8e50626f2dd550af225f82fb5f5814d2a42", size = 225234, upload-time = "2025-07-26T12:01:18.256Z" }, + { url = "https://files.pythonhosted.org/packages/d9/b6/71771e02c2e004450c12b1120a5f488cad2e4d5b590b1af8bad060360fe4/contourpy-1.3.3-cp311-cp311-win_arm64.whl", hash = "sha256:15ff10bfada4bf92ec8b31c62bf7c1834c244019b4a33095a68000d7075df470", size = 193123, upload-time = "2025-07-26T12:01:19.848Z" }, + { url = "https://files.pythonhosted.org/packages/a5/29/8dcfe16f0107943fa92388c23f6e05cff0ba58058c4c95b00280d4c75a14/contourpy-1.3.3-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:cd5dfcaeb10f7b7f9dc8941717c6c2ade08f587be2226222c12b25f0483ed497", size = 278809, upload-time = "2025-07-26T12:02:52.74Z" }, + { url = "https://files.pythonhosted.org/packages/85/a9/8b37ef4f7dafeb335daee3c8254645ef5725be4d9c6aa70b50ec46ef2f7e/contourpy-1.3.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:0c1fc238306b35f246d61a1d416a627348b5cf0648648a031e14bb8705fcdfe8", size = 261593, upload-time = "2025-07-26T12:02:54.037Z" }, + { url = "https://files.pythonhosted.org/packages/0a/59/ebfb8c677c75605cc27f7122c90313fd2f375ff3c8d19a1694bda74aaa63/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f9aad7de812d6541d29d2bbf8feb22ff7e1c299523db288004e3157ff4674e", size = 302202, upload-time = "2025-07-26T12:02:55.947Z" }, + { url = "https://files.pythonhosted.org/packages/3c/37/21972a15834d90bfbfb009b9d004779bd5a07a0ec0234e5ba8f64d5736f4/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5ed3657edf08512fc3fe81b510e35c2012fbd3081d2e26160f27ca28affec989", size = 329207, upload-time = "2025-07-26T12:02:57.468Z" }, + { url = "https://files.pythonhosted.org/packages/0c/58/bd257695f39d05594ca4ad60df5bcb7e32247f9951fd09a9b8edb82d1daa/contourpy-1.3.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:3d1a3799d62d45c18bafd41c5fa05120b96a28079f2393af559b843d1a966a77", size = 225315, upload-time = "2025-07-26T12:02:58.801Z" }, +] + +[[package]] +name = "cuda-bindings" +version = "13.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-pathfinder", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/09/74e159fbe67b081cca842871addce6d2b493f9bb48ce85124f023eb5f1c9/cuda_bindings-13.5.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71c15ed97099a8ef416515d80ddd10770e0f6339234e16855a526d2896516631", size = 7434875, upload-time = "2026-11-05T12:05:50.666Z" }, + { url = "https://files.pythonhosted.org/packages/f6/0d/ca24317a31118b90fd60126aec5c0a92a191a7fdd39524032d43328b49b5/cuda_bindings-13.5.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:08b7e8d674c3266facb00453a7e34ea7d3ea965c2f594bb728f269f45f39fbe2", size = 8390178, upload-time = "2026-11-05T12:05:52.653Z" }, + { url = "https://files.pythonhosted.org/packages/a6/7b/455b204f07dcbac810bc48b558d3febff8adb81b6036efac315bd5a4aa33/cuda_bindings-13.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:0d7a5d92be00b2a618fd7c62482f6c69584fd5ac498193b236600810d7ebaf74", size = 8097474, upload-time = "2026-11-05T12:05:59.207Z" }, + { url = "https://files.pythonhosted.org/packages/a0/70/9ab184a434f47dacedd47a49901c0be1a81080e8b57d1d3f0e5445bb1277/cuda_bindings-13.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:4d850299e6ba1ca9caec78b3d87b6b7590ed1d6c9a404272798f40b1e19e3f24", size = 7010633, upload-time = "2026-11-05T12:06:00.913Z" }, +] + +[[package]] +name = "cuda-pathfinder" +version = "1.8.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/9e/08555797c979322def080814686417ea93f66d38f5c48ebab6867a85a21e/cuda_pathfinder-1.8.6-py3-none-any.whl", hash = "sha256:bf6b3b06323cf95a11d671818392da5da23ddbbb4dfc4b77ca10622783c25980", size = 62603, upload-time = "2026-11-05T21:22:51.229Z" }, +] + +[[package]] +name = "cuda-toolkit" +version = "13.0.3.0" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/c7/a79086a62c98befcdb8349656c6f114e2db3b8b2422f6e25c97a7f2a9a3c/cuda_toolkit-13.0.3.0-py2.py3-none-any.whl", hash = "sha256:d693caaa261214ddd7dbb60d68e71cbed884e68c2be7509778f3051da0b91c3f", size = 2512, upload-time = "2026-04-14T00:50:08.173Z" }, +] + +[package.optional-dependencies] +cublas = [ + { name = "nvidia-cublas", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +cudart = [ + { name = "nvidia-cuda-runtime", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +cufft = [ + { name = "nvidia-cufft", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +cufile = [ + { name = "nvidia-cufile", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +cupti = [ + { name = "nvidia-cuda-cupti", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +curand = [ + { name = "nvidia-curand", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +cusolver = [ + { name = "nvidia-cublas", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-cusolver", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-cusparse", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +cusparse = [ + { name = "nvidia-cusparse", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +nvjitlink = [ + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +nvrtc = [ + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +nvtx = [ + { name = "nvidia-nvtx", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] + +[[package]] +name = "cycler" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, +] + +[[package]] +name = "datasets" +version = "2.14.7" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "aiohttp" }, + { name = "dill" }, + { name = "fsspec", extra = ["http"], marker = "extra == 'group-24-official-lozo-experiment-native'" }, + { name = "huggingface-hub" }, + { name = "multiprocess" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pyarrow", version = "17.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyarrow-hotfix" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "xxhash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/95/59/69ac07a49eeb587641f8a24eab5b5e406e308ed276e2a6de39d07a7cb6c3/datasets-2.14.7.tar.gz", hash = "sha256:394cf9b4ec0694b25945977b16ad5d18d5c15fb0e94141713eb8ead7452caf9e", size = 2181591, upload-time = "2023-11-15T08:12:38.218Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/00/23/80a2147a547cb2fd59eb92a13787c849b3efaefcea02a5c963dfc93f7c56/datasets-2.14.7-py3-none-any.whl", hash = "sha256:1a64041a7da4f4130f736fc371c1f528b8ddd208cebe156400f65719bdbba79d", size = 520442, upload-time = "2023-11-15T08:12:33.787Z" }, +] + +[[package]] +name = "datasets" +version = "3.6.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "dill" }, + { name = "filelock" }, + { name = "fsspec", extra = ["http"], marker = "extra == 'group-24-official-lozo-experiment-modern'" }, + { name = "huggingface-hub" }, + { name = "multiprocess" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pyarrow", version = "20.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "xxhash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1a/89/d3d6fef58a488f8569c82fd293ab7cbd4250244d67f425dcae64c63800ea/datasets-3.6.0.tar.gz", hash = "sha256:1b2bf43b19776e2787e181cfd329cb0ca1a358ea014780c3581e0f276375e041", size = 569336, upload-time = "2025-05-07T15:15:02.659Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/34/a08b0ee99715eaba118cbe19a71f7b5e2425c2718ef96007c325944a1152/datasets-3.6.0-py3-none-any.whl", hash = "sha256:25000c4a2c0873a710df127d08a202a06eab7bf42441a6bc278b499c2f72cd1b", size = 491546, upload-time = "2025-05-07T15:14:59.742Z" }, +] + +[[package]] +name = "dill" +version = "0.3.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c4/31/54dd222e02311c2dbc9e680d37cbd50f4494ce1ee9b04c69980e4ec26f38/dill-0.3.7.tar.gz", hash = "sha256:cc1c8b182eb3013e24bd475ff2e9295af86c1a38eb1aff128dac8962a9ce3c03", size = 183355, upload-time = "2023-07-22T22:18:46.449Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f5/3a/74a29b11cf2cdfcd6ba89c0cecd70b37cd1ba7b77978ce611eb7a146a832/dill-0.3.7-py3-none-any.whl", hash = "sha256:76b122c08ef4ce2eedcd4d1abd8e641114bfc6c2867f49f3c41facf65bf19f5e", size = 115254, upload-time = "2023-07-22T22:18:44.511Z" }, +] + +[[package]] +name = "einops" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e5/81/df4fbe24dff8ba3934af99044188e20a98ed441ad17a274539b74e82e126/einops-0.8.1.tar.gz", hash = "sha256:de5d960a7a761225532e0f1959e5315ebeafc0cd43394732f103ca44b9837e84", size = 54805, upload-time = "2025-02-09T03:17:00.434Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/62/9773de14fe6c45c23649e98b83231fffd7b9892b6cf863251dc2afa73643/einops-0.8.1-py3-none-any.whl", hash = "sha256:919387eb55330f5757c6bea9165c5ff5cfe63a642682ea788a6d472576d81737", size = 64359, upload-time = "2025-02-09T03:17:01.998Z" }, +] + +[[package]] +name = "filelock" +version = "4.2.10" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/cf/05bcdacabdc0aec7dc8e19d76281bd82325df62dae3b6430e9ba57397689/filelock-4.2.10.tar.gz", hash = "sha256:fcc3c0cb8bfe7f4b3bb0e231c04b15dbad068cb3c2515f343d8fde4dce93bd5d", size = 670595, upload-time = "2026-11-09T18:58:00.54Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/90/5d0096a325aa0f83ba7a3968bfb485b67e32c947bdf9cd0fcb4b485be718/filelock-4.2.10-py3-none-any.whl", hash = "sha256:9479aaeb4db20b5a53e3da28493edd24720b66b8a0b84030aa56ccdf243d6857", size = 218040, upload-time = "2026-11-09T18:57:59.088Z" }, +] + +[[package]] +name = "fonttools" +version = "4.68.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0c/b5/672312ae80ce8b8eb9779c56052a24c8f36652aa7293a1a420553bcf03e5/fonttools-4.68.0.tar.gz", hash = "sha256:73294e233070f71e2b3653b6bd8564af676d57f26d075761fb06d1ab2e4a7a5d", size = 3848583, upload-time = "2026-10-27T16:30:26.451Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/21/51/7c725115425be01aa0fac87eb38f8e8c8c04de80d49a99b08a74898b25ee/fonttools-4.68.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:362443ab355701d6fd26b10d022cd6c8456e1e248f80103c44cbe5ef0228f87f", size = 3135538, upload-time = "2026-10-27T16:28:02.169Z" }, + { url = "https://files.pythonhosted.org/packages/2e/d5/0a04cbde3e3e997d7bda216f77566bea2eb79018e4ca2adb13ce3c9a7206/fonttools-4.68.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:664dfa7a4869b3c827dfc2c38dbbb7a58d53e97933d1bd51ee6729792ee73d50", size = 2632853, upload-time = "2026-10-27T16:28:04.962Z" }, + { url = "https://files.pythonhosted.org/packages/d8/8c/aa4c7b38f4814d6bcb3378276bff802c9610a1227f1d24965a9f23f0a48c/fonttools-4.68.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:53f2387d7e3816763f30e08d14263be18e28ead53d4dc20a82f9280d0c99d88a", size = 5530571, upload-time = "2026-10-27T16:28:06.952Z" }, + { url = "https://files.pythonhosted.org/packages/00/01/e0f5b3d648ddd2eae35c4bcddcc2cffc059279e9d2cdb325bed10458f606/fonttools-4.68.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4b9c89b5876f1a74b1341632dfaf4c4c2be565d76c060445df401ebe7a4ceefa", size = 5493829, upload-time = "2026-10-27T16:28:09.127Z" }, + { url = "https://files.pythonhosted.org/packages/ea/bb/9c5568659275c86e6eebb060d98e8ea77c56fb78ee77ea5654a057f72bde/fonttools-4.68.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:054a4d5de7e1f973ab9789e9ae3f20238774783ca9bf7ee0359aebae4de9400c", size = 5496373, upload-time = "2026-10-27T16:28:11.378Z" }, + { url = "https://files.pythonhosted.org/packages/b0/32/0a35ffd35bfc1b0a754563a45500e87d651e0f336cf006a25e0bc460ba2f/fonttools-4.68.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b5a015b322275d3d745b06d5e69cf74ef4b1ce2dae02afbe4826cb186d8527a3", size = 5634196, upload-time = "2026-10-27T16:28:13.783Z" }, + { url = "https://files.pythonhosted.org/packages/93/76/3454e20f07dbe4b308b7bc99117292109bb7775a1b595ead768110144553/fonttools-4.68.0-cp311-cp311-win32.whl", hash = "sha256:bd5b047ed8f16b83d0344fef053668712ab9c88e2e46d8612ec41df83c5222e1", size = 1624232, upload-time = "2026-10-27T16:28:16.001Z" }, + { url = "https://files.pythonhosted.org/packages/46/87/4ba592099172764aa56e66919b0c3ddaf944c775433e806e36e165062095/fonttools-4.68.0-cp311-cp311-win_amd64.whl", hash = "sha256:35425bba603cf9d72c9f3c173ea6c98632164f3bdfb1ce1a3dcc928979c6ec6d", size = 1681821, upload-time = "2026-10-27T16:28:17.757Z" }, + { url = "https://files.pythonhosted.org/packages/e1/54/004f12709b21a56bb944fdca6d165b0d90cf9366143675dbc7bb46784ddd/fonttools-4.68.0-cp311-cp311-win_arm64.whl", hash = "sha256:04365b897c9ee29a048b6d4db74c75c38b70aa6d1074726fbdd7ea1a23aa8ed2", size = 1649151, upload-time = "2026-10-27T16:28:19.502Z" }, + { url = "https://files.pythonhosted.org/packages/35/74/4ea331ecc65ba05a58b1e4e8ccd604c8a15565f876dfbf93fc2a2ea2e22b/fonttools-4.68.0-py3-none-any.whl", hash = "sha256:d76f8fdcb6936f5e1045a0c9dd721a4bf11112e60d1e243bfa1d39f06a8b3104", size = 1248357, upload-time = "2026-10-27T16:30:24.389Z" }, +] + +[[package]] +name = "frozenlist" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/03/077f869d540370db12165c0aa51640a873fb661d8b315d1d4d67b284d7ac/frozenlist-1.8.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:09474e9831bc2b2199fad6da3c14c7b0fbdd377cce9d3d77131be28906cb7d84", size = 86912, upload-time = "2025-10-06T05:35:45.98Z" }, + { url = "https://files.pythonhosted.org/packages/df/b5/7610b6bd13e4ae77b96ba85abea1c8cb249683217ef09ac9e0ae93f25a91/frozenlist-1.8.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:17c883ab0ab67200b5f964d2b9ed6b00971917d5d8a92df149dc2c9779208ee9", size = 50046, upload-time = "2025-10-06T05:35:47.009Z" }, + { url = "https://files.pythonhosted.org/packages/6e/ef/0e8f1fe32f8a53dd26bdd1f9347efe0778b0fddf62789ea683f4cc7d787d/frozenlist-1.8.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:fa47e444b8ba08fffd1c18e8cdb9a75db1b6a27f17507522834ad13ed5922b93", size = 50119, upload-time = "2025-10-06T05:35:48.38Z" }, + { url = "https://files.pythonhosted.org/packages/11/b1/71a477adc7c36e5fb628245dfbdea2166feae310757dea848d02bd0689fd/frozenlist-1.8.0-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2552f44204b744fba866e573be4c1f9048d6a324dfe14475103fd51613eb1d1f", size = 231067, upload-time = "2025-10-06T05:35:49.97Z" }, + { url = "https://files.pythonhosted.org/packages/45/7e/afe40eca3a2dc19b9904c0f5d7edfe82b5304cb831391edec0ac04af94c2/frozenlist-1.8.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:957e7c38f250991e48a9a73e6423db1bb9dd14e722a10f6b8bb8e16a0f55f695", size = 233160, upload-time = "2025-10-06T05:35:51.729Z" }, + { url = "https://files.pythonhosted.org/packages/a6/aa/7416eac95603ce428679d273255ffc7c998d4132cfae200103f164b108aa/frozenlist-1.8.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8585e3bb2cdea02fc88ffa245069c36555557ad3609e83be0ec71f54fd4abb52", size = 228544, upload-time = "2025-10-06T05:35:53.246Z" }, + { url = "https://files.pythonhosted.org/packages/8b/3d/2a2d1f683d55ac7e3875e4263d28410063e738384d3adc294f5ff3d7105e/frozenlist-1.8.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:edee74874ce20a373d62dc28b0b18b93f645633c2943fd90ee9d898550770581", size = 243797, upload-time = "2025-10-06T05:35:54.497Z" }, + { url = "https://files.pythonhosted.org/packages/78/1e/2d5565b589e580c296d3bb54da08d206e797d941a83a6fdea42af23be79c/frozenlist-1.8.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c9a63152fe95756b85f31186bddf42e4c02c6321207fd6601a1c89ebac4fe567", size = 247923, upload-time = "2025-10-06T05:35:55.861Z" }, + { url = "https://files.pythonhosted.org/packages/aa/c3/65872fcf1d326a7f101ad4d86285c403c87be7d832b7470b77f6d2ed5ddc/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b6db2185db9be0a04fecf2f241c70b63b1a242e2805be291855078f2b404dd6b", size = 230886, upload-time = "2025-10-06T05:35:57.399Z" }, + { url = "https://files.pythonhosted.org/packages/a0/76/ac9ced601d62f6956f03cc794f9e04c81719509f85255abf96e2510f4265/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:f4be2e3d8bc8aabd566f8d5b8ba7ecc09249d74ba3c9ed52e54dc23a293f0b92", size = 245731, upload-time = "2025-10-06T05:35:58.563Z" }, + { url = "https://files.pythonhosted.org/packages/b9/49/ecccb5f2598daf0b4a1415497eba4c33c1e8ce07495eb07d2860c731b8d5/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:c8d1634419f39ea6f5c427ea2f90ca85126b54b50837f31497f3bf38266e853d", size = 241544, upload-time = "2025-10-06T05:35:59.719Z" }, + { url = "https://files.pythonhosted.org/packages/53/4b/ddf24113323c0bbcc54cb38c8b8916f1da7165e07b8e24a717b4a12cbf10/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:1a7fa382a4a223773ed64242dbe1c9c326ec09457e6b8428efb4118c685c3dfd", size = 241806, upload-time = "2025-10-06T05:36:00.959Z" }, + { url = "https://files.pythonhosted.org/packages/a7/fb/9b9a084d73c67175484ba2789a59f8eebebd0827d186a8102005ce41e1ba/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:11847b53d722050808926e785df837353bd4d75f1d494377e59b23594d834967", size = 229382, upload-time = "2025-10-06T05:36:02.22Z" }, + { url = "https://files.pythonhosted.org/packages/95/a3/c8fb25aac55bf5e12dae5c5aa6a98f85d436c1dc658f21c3ac73f9fa95e5/frozenlist-1.8.0-cp311-cp311-win32.whl", hash = "sha256:27c6e8077956cf73eadd514be8fb04d77fc946a7fe9f7fe167648b0b9085cc25", size = 39647, upload-time = "2025-10-06T05:36:03.409Z" }, + { url = "https://files.pythonhosted.org/packages/0a/f5/603d0d6a02cfd4c8f2a095a54672b3cf967ad688a60fb9faf04fc4887f65/frozenlist-1.8.0-cp311-cp311-win_amd64.whl", hash = "sha256:ac913f8403b36a2c8610bbfd25b8013488533e71e62b4b4adce9c86c8cea905b", size = 44064, upload-time = "2025-10-06T05:36:04.368Z" }, + { url = "https://files.pythonhosted.org/packages/5d/16/c2c9ab44e181f043a86f9a8f84d5124b62dbcb3a02c0977ec72b9ac1d3e0/frozenlist-1.8.0-cp311-cp311-win_arm64.whl", hash = "sha256:d4d3214a0f8394edfa3e303136d0575eece0745ff2b47bd2cb2e66dd92d4351a", size = 39937, upload-time = "2025-10-06T05:36:05.669Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, +] + +[[package]] +name = "fsspec" +version = "2023.10.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a4/f7/16ec1f92523165d10301cfa8cb83df0356dbe615d4ca5ed611a16f53e09a/fsspec-2023.10.0.tar.gz", hash = "sha256:330c66757591df346ad3091a53bd907e15348c2ba17d63fd54f5c39c4457d2a5", size = 165452, upload-time = "2023-10-21T17:37:04.636Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e8/f6/3eccfb530aac90ad1301c582da228e4763f19e719ac8200752a4841b0b2d/fsspec-2023.10.0-py3-none-any.whl", hash = "sha256:346a8f024efeb749d2a5fca7ba8854474b1ff9af7c3faaf636a4548781136529", size = 166384, upload-time = "2023-10-21T17:37:02.632Z" }, +] + +[package.optional-dependencies] +http = [ + { name = "aiohttp" }, + { name = "requests" }, +] + +[[package]] +name = "gitdb" +version = "4.0.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "smmap" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/94/63b0fc47eb32792c7ba1fe1b694daec9a63620db1e313033d18140c2320a/gitdb-4.0.12.tar.gz", hash = "sha256:5ef71f855d191a3326fcfbc0d5da835f26b13fbcba60c32c21091c349ffdb571", size = 394684, upload-time = "2025-01-02T07:20:46.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/61/5c78b91c3143ed5c14207f463aecfc8f9dbb5092fb2869baf37c273b2705/gitdb-4.0.12-py3-none-any.whl", hash = "sha256:67073e15955400952c6565cc3e707c554a4eea2e428946f7a4c162fab9bd9bcf", size = 62794, upload-time = "2025-01-02T07:20:43.624Z" }, +] + +[[package]] +name = "gitpython" +version = "3.2.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "gitdb" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/ff/fee293f1ec3e1b64db6eb270e00964f29c086d769201474cedb8d1608930/gitpython-3.2.1.tar.gz", hash = "sha256:0f1229ec5c057bdabdeeda8bda4f17bda679ab33dbccc00f24e6a480553c8613", size = 241688, upload-time = "2026-10-14T12:20:20.589Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6b/50/2a923c4dc02522ff9567f07c67ed1deca6d5fa9474f4708168b8088dfa37/gitpython-3.2.1-py3-none-any.whl", hash = "sha256:d66b0832aa8755c1a84892937282df0befb16c97e5a64aeebd68be9c5e323f53", size = 231548, upload-time = "2026-10-14T12:20:18.844Z" }, +] + +[[package]] +name = "hf-xet" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" }, + { url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" }, + { url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" }, + { url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" }, + { url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" }, +] + +[[package]] +name = "huggingface-hub" +version = "0.36.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "filelock" }, + { name = "fsspec" }, + { name = "hf-xet", marker = "platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/63/4910c5fa9128fdadf6a9c5ac138e8b1b6cee4ca44bf7915bbfbce4e355ee/huggingface_hub-0.36.0.tar.gz", hash = "sha256:47b3f0e2539c39bf5cde015d63b72ec49baff67b6931c3d97f3f84532e2b8d25", size = 463358, upload-time = "2025-10-23T12:12:01.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/bd/1a875e0d592d447cbc02805fd3fe0f497714d6a2583f59d14fa9ebad96eb/huggingface_hub-0.36.0-py3-none-any.whl", hash = "sha256:7bcc9ad17d5b3f07b57c78e79d527102d08313caa278a641993acddcb894548d", size = 566094, upload-time = "2025-10-23T12:11:59.557Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "joblib" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cloudpickle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d5/1d/537ab090f302b838943a1b56497dd53059b9a9b46a074936470173a2e207/joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03", size = 327903, upload-time = "2026-08-31T09:39:04.122Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115, upload-time = "2026-08-31T09:39:02.298Z" }, +] + +[[package]] +name = "kiwisolver" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea041ef5bba3ed21a003522fa088834b069b1909981f30/kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a", size = 104395, upload-time = "2026-08-28T10:28:27.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/7b/2de6908edc668427c149af5f93112e931f87e1fa4cab80bac32c5844dccc/kiwisolver-1.5.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b3d78f7bb2b9d9a30345be1474b9aaa8685430b54afb51ba3639b5c6c11e9ed6", size = 123364, upload-time = "2026-08-28T10:25:04.359Z" }, + { url = "https://files.pythonhosted.org/packages/8a/24/e70914415c77c97be7e22c80a0740869cb7428768cc380fdcdf6703e7084/kiwisolver-1.5.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5025e36fb4fb275cef0a4e30dbb11cb4ae61d1c83deb90189cb5d7e4cafd6b55", size = 66558, upload-time = "2026-08-28T10:25:05.506Z" }, + { url = "https://files.pythonhosted.org/packages/e8/2b/8b08b11833db4d475b8ef1f36174f8d8a7abd31bedd7e794be78e8814b48/kiwisolver-1.5.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dc1a26b8e53395a01c2c611e58602fa47461f136fba7cd5542e6db6d64be1839", size = 64071, upload-time = "2026-08-28T10:25:06.7Z" }, + { url = "https://files.pythonhosted.org/packages/89/00/05c2d0369ac322d22d5c05f84b5c4a6856fa6207fbae42869108a28f0383/kiwisolver-1.5.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:95a02752aa032eef4aed01cda6d9b687c669bd0396bf4519eef8bba22a286720", size = 1438206, upload-time = "2026-08-28T10:25:08.254Z" }, + { url = "https://files.pythonhosted.org/packages/c0/05/c941a139f27438c1910d630fdc3ccfdab7c8407c72052299ead12ece086e/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:719a35fa1156db3640555f95ebb94f60a444e64d1c69626b0edef5df78eba225", size = 1248975, upload-time = "2026-08-28T10:25:10.053Z" }, + { url = "https://files.pythonhosted.org/packages/58/a1/2669ee5512e39b9d4de25faacaedf788c957f93730c5f7c63993ec4f5933/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:febcce10f2bcdbb80b4ea919238a6a4ac13dbc4c7cadbe8d5d75c3682f8b5404", size = 1266301, upload-time = "2026-08-28T10:25:11.754Z" }, + { url = "https://files.pythonhosted.org/packages/28/b8/353f52f2c7f861a9e90cd2e8f90f85b3ad03060835f823e08298d094c463/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1d852545c4d0e35a72728d072cbaa59e2fa7dd84bdf01e068d670dd0ceb58eb6", size = 1319708, upload-time = "2026-08-28T10:25:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/21/0e/14b83200eadc2c1d63b76bac01c1813bf072aecf567429f303e00b70258e/kiwisolver-1.5.1-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:2e10ae1bba1899188b33557c10d73affcc12033edd18adddb57d209039976a4c", size = 971720, upload-time = "2026-08-28T10:25:14.934Z" }, + { url = "https://files.pythonhosted.org/packages/86/91/9d43d84d23b1cbff72a142d387ead1ea03db0cba8ff86ed5335addad3cc9/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b69602970994a2ed8bbfa78c2f0394a7435226c6040489702d9f0a0ad0c07052", size = 2200119, upload-time = "2026-08-28T10:25:16.636Z" }, + { url = "https://files.pythonhosted.org/packages/ff/7c/f2bd9616f27ffb5e17cecc0baa5d0bbcee7e55aeddc0ccc871d69e2fc3ee/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d50de98e8d807dc31822fff96f50293163a62418eb65487a21b42713d72ed0b7", size = 2295005, upload-time = "2026-08-28T10:25:18.374Z" }, + { url = "https://files.pythonhosted.org/packages/ba/17/ee671b72bf8f46a08379d4392c65582541759a542428197562f2898294ad/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3221f78211074f561c44ca42eac0619828171bec15a2c4cf6f7747d07df76e8e", size = 1960982, upload-time = "2026-08-28T10:25:19.893Z" }, + { url = "https://files.pythonhosted.org/packages/2e/f7/0e26b4c05bee3bdb0f048dfa305e4fe701999ea17b51e9c616ef91035bbe/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0ba9527afc80ae3d7814ed98b6572d02bf85eaf48065678342c5f0c6dab7a8c7", size = 2464918, upload-time = "2026-08-28T10:25:21.65Z" }, + { url = "https://files.pythonhosted.org/packages/ae/62/6eb431133d30ce656ac1e5ff72fac70dd34d54c3984f4011b9ac8bf77d54/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e12dfea7f5fc2a34a9080efbf79c4c44eb380ec5b9c6fea09407e08f0d1e941d", size = 2270967, upload-time = "2026-08-28T10:25:23.643Z" }, + { url = "https://files.pythonhosted.org/packages/bf/9f/6f9e489c188200e6fb3193935501894811e8c97577c8ffe9033589bf3521/kiwisolver-1.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:1a7587dc335f2c0f5bd577fd0540bd16c66006bdb60f759a1059f025e6c4f071", size = 70744, upload-time = "2026-08-28T10:25:25.061Z" }, + { url = "https://files.pythonhosted.org/packages/c6/6d/dfc430d1d43957061599adea3f08ea982bb6f4ab601a8c974bedcf2ba850/kiwisolver-1.5.1-cp311-cp311-win_arm64.whl", hash = "sha256:e4e4523d6f336708d732516e6cfca7796cf3d96c9474eb5aecf6165f2f1fefc3", size = 68404, upload-time = "2026-08-28T10:25:26.186Z" }, + { url = "https://files.pythonhosted.org/packages/b5/1d/59ba570b1774e95e97fde3a0981b2e22118a7a495f73bf74cedc538566a0/kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:416ba7ff9f233b7036689bb5a3783537e838ad483f63558d2a800f75afe738b1", size = 59450, upload-time = "2026-08-28T10:28:20.383Z" }, + { url = "https://files.pythonhosted.org/packages/22/98/a6849f04dc18b5400e8b98affa2cd8fd86ed583085f036e57b32e571f4fa/kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:8af9b142ad719ae3a911ebf616bc4b78b32bbab84d6a40d3ad2f129670509957", size = 57400, upload-time = "2026-08-28T10:28:21.632Z" }, + { url = "https://files.pythonhosted.org/packages/f4/ce/a7dc71353dd06a4cbe02222773f52d4a28c81e5a452a75797f8ed113dc99/kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5daa1f19e097050b9c4d9a78fcc9263cb96c9dfae08037ddc1b7c4ad1889f2a2", size = 79891, upload-time = "2026-08-28T10:28:22.936Z" }, + { url = "https://files.pythonhosted.org/packages/10/b1/d61c61a84ff85d1a36a99df2c152b59ffedb1d356c598902aba44abcdb60/kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cdaeeb6c350106df6bf9d873395973e5f066a9713200b72cd64f55d0a3eafab6", size = 77605, upload-time = "2026-08-28T10:28:24.322Z" }, + { url = "https://files.pythonhosted.org/packages/d3/52/5aef56f21a460a6e43ab3cdfc7697d59d7b87deb0ec97a0f7b91aa4a521b/kiwisolver-1.5.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:17851e5dad4484be0cbccbde3b15331deae036de9aebd45eed964487802b172f", size = 98465, upload-time = "2026-08-28T10:28:25.696Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/55/18dbb4778b30ada5ce071608503cc3edc9e14e13d868c17a6d178fc30f7a/markupsafe-3.0.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9e25feb9e330b63edb0278a0acdf85e50d0cb0fbf49c3084abbe4e24ae195346", size = 11520, upload-time = "2026-10-02T23:04:36.299Z" }, + { url = "https://files.pythonhosted.org/packages/6c/14/0b05f79b4733e264a18d08fe08fa1df7347630ff32a6cb82180d9dccec55/markupsafe-3.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7d3391b2188d18737cb2fa147028b1096236eaa7e156446c650a489fa2cadc91", size = 12063, upload-time = "2026-10-02T23:04:37.291Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3a/63ba10b6c1463216b3e4df669a9f0e5a3b0c3071557d2e8229e3968c79fb/markupsafe-3.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849dd2bb0e5e4ab2b71c7191726a4a8d5aa8a610daa584728cbee0b710ddc4ef", size = 24321, upload-time = "2026-10-02T23:04:38.262Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/5f015261b76ad633d187ef6f388b413aedd64a8773c4df59e530a0be5525/markupsafe-3.0.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:befb4158af32106b9a93db8d6d1d1cbbd418c0d5aca0cabb7b1780abf0c89169", size = 28845, upload-time = "2026-10-02T23:04:39.295Z" }, + { url = "https://files.pythonhosted.org/packages/33/cf/26e594b26be40c2f1fec63ccf8a8b99d0335a5b2cbe84835c7d82a994375/markupsafe-3.0.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:71f88e749ea29f67f21f3b36433c1dc54c7729ed2a6d9e2da2e0d9e0d7b224eb", size = 24701, upload-time = "2026-10-02T23:04:40.348Z" }, + { url = "https://files.pythonhosted.org/packages/81/a5/a513b76c139a3915b43404324e55c0b7979ae4f0d39eb6f075b0282e90a8/markupsafe-3.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6da83a088f8ef93b2d483a8232a4dbf4d69d3d8496b568a03c56becac43e1808", size = 22961, upload-time = "2026-10-02T23:04:41.372Z" }, + { url = "https://files.pythonhosted.org/packages/46/cf/4c66192c100b4542bcbe392ae06696b670f66927be3ac38a213234778ff9/markupsafe-3.0.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8f0fac8b13d14bb06c68195f849371924ae53dd7b1c00fed24650f704383b692", size = 21920, upload-time = "2026-10-02T23:04:42.429Z" }, + { url = "https://files.pythonhosted.org/packages/cb/17/ac3662678bfbad649893117ada2ba44dc30bf56884e84f13154a792b10f1/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4a7cdc2a420ca01058182da4253329764d4bfa055564d1eced90e6ba1e8b1d3d", size = 23726, upload-time = "2026-10-02T23:04:43.531Z" }, + { url = "https://files.pythonhosted.org/packages/f7/af/fe47cee339180a69ebca3c57fb3483d0f5cbd1e8337d1871fb1d9c1aebee/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:83b3944fea42a8400edf92fd1770fb8d0d4f7de651353bd2d8525a92dba69a21", size = 22539, upload-time = "2026-10-02T23:04:44.618Z" }, + { url = "https://files.pythonhosted.org/packages/12/32/d55440ba140442800e02d799c9cb5ab597bf6ebdb1177b5ea39a11f797bd/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8138eb83940ec7299024d92d4dee45f601b9e6c5ffde9d25f4e35e326203c707", size = 23963, upload-time = "2026-10-02T23:04:45.656Z" }, + { url = "https://files.pythonhosted.org/packages/50/9d/9c86042cb364c2ad4c971e6d1247929effd25f714cd7ee11b05e6316445b/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:811d02d5122171c1941357efd8f9bf4ffe907b7f0a1a4e729a880e4be3f46e3e", size = 21506, upload-time = "2026-10-02T23:04:46.671Z" }, + { url = "https://files.pythonhosted.org/packages/75/ef/5b824f03ba40c3b3652b6272d083d2fc4fcdd440de519a3a39ba2c3e7262/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:50b5bedc9ed8a94fc8857a42ef4f84a81ea88f8d4f05dc8705fb23ee6d8dcca7", size = 22955, upload-time = "2026-10-02T23:04:47.698Z" }, + { url = "https://files.pythonhosted.org/packages/1e/e8/44cfcb5ea40e5e43cec7793ef90704ed0c475280839076c4345757eb8e59/markupsafe-3.0.4-cp311-cp311-win32.whl", hash = "sha256:2e5a7cd7fdd14fcb1ae5d7d8bf23d24fbd1daefd1fbca2580132e1ea75f098b5", size = 14094, upload-time = "2026-10-02T23:04:48.788Z" }, + { url = "https://files.pythonhosted.org/packages/91/89/f2b509f7bf79352e40117824c1070dbeafd4df67031d3fa98165a3134228/markupsafe-3.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3", size = 14328, upload-time = "2026-10-02T23:04:49.801Z" }, + { url = "https://files.pythonhosted.org/packages/2b/5a/ccf22672a0f64dc682306e288f0dabcb06c7a201f3bb6e6cbf86d9e8ad03/markupsafe-3.0.4-cp311-cp311-win_arm64.whl", hash = "sha256:569d65055d367e3dcdf30c3f41119467b73d9ee9faf332bdf40402644f5ac08e", size = 14188, upload-time = "2026-10-02T23:04:50.847Z" }, +] + +[[package]] +name = "matplotlib" +version = "3.10.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "contourpy" }, + { name = "cycler" }, + { name = "fonttools" }, + { name = "kiwisolver" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "pyparsing" }, + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ae/e2/d2d5295be2f44c678ebaf3544ba32d20c1f9ef08c49fe47f496180e1db15/matplotlib-3.10.7.tar.gz", hash = "sha256:a06ba7e2a2ef9131c79c49e63dad355d2d878413a0376c1727c8b9335ff731c7", size = 34804865, upload-time = "2025-10-09T00:28:00.669Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/bc/0fb489005669127ec13f51be0c6adc074d7cf191075dab1da9fe3b7a3cfc/matplotlib-3.10.7-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:53b492410a6cd66c7a471de6c924f6ede976e963c0f3097a3b7abfadddc67d0a", size = 8257507, upload-time = "2025-10-09T00:26:19.073Z" }, + { url = "https://files.pythonhosted.org/packages/e2/6a/d42588ad895279ff6708924645b5d2ed54a7fb2dc045c8a804e955aeace1/matplotlib-3.10.7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d9749313deb729f08207718d29c86246beb2ea3fdba753595b55901dee5d2fd6", size = 8119565, upload-time = "2025-10-09T00:26:21.023Z" }, + { url = "https://files.pythonhosted.org/packages/10/b7/4aa196155b4d846bd749cf82aa5a4c300cf55a8b5e0dfa5b722a63c0f8a0/matplotlib-3.10.7-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2222c7ba2cbde7fe63032769f6eb7e83ab3227f47d997a8453377709b7fe3a5a", size = 8692668, upload-time = "2025-10-09T00:26:22.967Z" }, + { url = "https://files.pythonhosted.org/packages/e6/e7/664d2b97016f46683a02d854d730cfcf54ff92c1dafa424beebef50f831d/matplotlib-3.10.7-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e91f61a064c92c307c5a9dc8c05dc9f8a68f0a3be199d9a002a0622e13f874a1", size = 9521051, upload-time = "2025-10-09T00:26:25.041Z" }, + { url = "https://files.pythonhosted.org/packages/a8/a3/37aef1404efa615f49b5758a5e0261c16dd88f389bc1861e722620e4a754/matplotlib-3.10.7-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6f1851eab59ca082c95df5a500106bad73672645625e04538b3ad0f69471ffcc", size = 9576878, upload-time = "2025-10-09T00:26:27.478Z" }, + { url = "https://files.pythonhosted.org/packages/33/cd/b145f9797126f3f809d177ca378de57c45413c5099c5990de2658760594a/matplotlib-3.10.7-cp311-cp311-win_amd64.whl", hash = "sha256:6516ce375109c60ceec579e699524e9d504cd7578506f01150f7a6bc174a775e", size = 8115142, upload-time = "2025-10-09T00:26:29.774Z" }, + { url = "https://files.pythonhosted.org/packages/2e/39/63bca9d2b78455ed497fcf51a9c71df200a11048f48249038f06447fa947/matplotlib-3.10.7-cp311-cp311-win_arm64.whl", hash = "sha256:b172db79759f5f9bc13ef1c3ef8b9ee7b37b0247f987fbbbdaa15e4f87fd46a9", size = 7992439, upload-time = "2025-10-09T00:26:40.32Z" }, + { url = "https://files.pythonhosted.org/packages/58/8f/76d5dc21ac64a49e5498d7f0472c0781dae442dd266a67458baec38288ec/matplotlib-3.10.7-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:15112bcbaef211bd663fa935ec33313b948e214454d949b723998a43357b17b0", size = 8252283, upload-time = "2025-10-09T00:27:54.739Z" }, + { url = "https://files.pythonhosted.org/packages/27/0d/9c5d4c2317feb31d819e38c9f947c942f42ebd4eb935fc6fd3518a11eaa7/matplotlib-3.10.7-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d2a959c640cdeecdd2ec3136e8ea0441da59bcaf58d67e9c590740addba2cb68", size = 8116733, upload-time = "2025-10-09T00:27:56.406Z" }, + { url = "https://files.pythonhosted.org/packages/9a/cc/3fe688ff1355010937713164caacf9ed443675ac48a997bab6ed23b3f7c0/matplotlib-3.10.7-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3886e47f64611046bc1db523a09dd0a0a6bed6081e6f90e13806dd1d1d1b5e91", size = 8693919, upload-time = "2025-10-09T00:27:58.41Z" }, +] + +[[package]] +name = "mpmath" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, +] + +[[package]] +name = "multidict" +version = "7.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/6b/29ef8e752f5854dcc267ded0652c475bec99b86f255957a0d4fcad657b18/multidict-7.2.1.tar.gz", hash = "sha256:e8af3e6f1bdbc31fd762b094133b478b89988eaebc63cbe82b1d9e3bbd15cede", size = 369994, upload-time = "2026-10-24T20:41:35.457Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/24/4347a7502ad47cb05a1b8d4e219514b4f0b1e38d4e4734c053c20328949f/multidict-7.2.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:fd24c4425fdb8e822601335602375c6d0cb020f7a368e1d5842eb7925a9c8748", size = 173141, upload-time = "2026-10-24T20:40:02.481Z" }, + { url = "https://files.pythonhosted.org/packages/8d/f2/2a8fcfe4c2c435101f9227b7f7ea81d786ffef993cadd2394e6926020ca9/multidict-7.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cecb2c778f00a65c6ca01410dd194d0e797a9eebb7c6dea0db87718719f293c7", size = 97197, upload-time = "2026-10-24T20:40:06.534Z" }, + { url = "https://files.pythonhosted.org/packages/7a/57/39be4ac4fa9c20e3af7dd7e89adf7dd404b4547fb4453c5c96082e197b9c/multidict-7.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:0d852d3d9638f852158d7de7200dd77f7ff8d77fc8f3d396032f3d847883f631", size = 104843, upload-time = "2026-10-24T20:40:05.829Z" }, + { url = "https://files.pythonhosted.org/packages/63/da/6a5c78daa34e458ced17573b7527395c4c39ebb253220274382d361a1493/multidict-7.2.1-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:76a4f5132b8dc29eb3c768ee9b47e132a1d24fbc2e9259854c01af9beaff1d49", size = 490713, upload-time = "2026-10-24T20:40:41.715Z" }, + { url = "https://files.pythonhosted.org/packages/8a/75/b8252bc6411f7f4b9649b83e143789b7bc1dda44f656b09ce74f894ca027/multidict-7.2.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:295a15ccb8cfde9351dd6062b80af4e839460636b3c46813b4aa443905ded86a", size = 504189, upload-time = "2026-10-24T20:40:04.042Z" }, + { url = "https://files.pythonhosted.org/packages/c0/45/38e8191d0a7c7b56015dfc4c2910b731aa719c5ad3f369b2357567f03434/multidict-7.2.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:987f65f6c9321402bc7012f6c6d09ba501b88ddb1640f5b0b4a19f2caafe24a5", size = 465834, upload-time = "2026-10-24T20:40:08.058Z" }, + { url = "https://files.pythonhosted.org/packages/9f/55/378869573886f7efcac24d2c698938dadf973e0da40b812c8b0df847fc46/multidict-7.2.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:36b868758fb11cfa748c788b793994e73660abec90f83c780a678539c2c468bf", size = 522423, upload-time = "2026-10-24T20:40:07.427Z" }, + { url = "https://files.pythonhosted.org/packages/af/c5/8936fe02c11196994ac05c4876ad62336a66ef353ea2d1a2ca3adce71678/multidict-7.2.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5b944091cfa7da4f7a9bd2587569cd90c94b89ec4721f8e87fe62504f2432b67", size = 544512, upload-time = "2026-10-24T20:40:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/d0/38/b8403d97ae5273002fa664c3c440c5cc186082fa0ba20fcc93885d13a686/multidict-7.2.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3b7542fad2706595c1b1853b46f2c3c4ae5cc5a6252b7225f294d607a29e1bdf", size = 510054, upload-time = "2026-10-24T20:40:05.525Z" }, + { url = "https://files.pythonhosted.org/packages/18/5d/473e1436ea8577cdfb42371c0507a244d51f8d8ef08bea0f9e6e63906478/multidict-7.2.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:363e5db93fc3f65f3218a79fe108d217b9d264181a4e993c77552bfe275d0393", size = 452816, upload-time = "2026-10-24T20:40:09.49Z" }, + { url = "https://files.pythonhosted.org/packages/1e/b7/67376e6821fb28c21de1fb37731efd2e3a6a523bdefc4af6997bd043da7a/multidict-7.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5deadf03fb4a7842696d551f9f9a06dd4445bb43ca06b5f9736e4e1885561333", size = 490712, upload-time = "2026-10-24T20:40:09.097Z" }, + { url = "https://files.pythonhosted.org/packages/1a/89/5144d8b36f133109ff36408089a475b9a3a3c1840176a39a9a8fb67a0000/multidict-7.2.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:0ec95a02f9f08246cc7f1d85ac425e4d5c233fd3f098f5be1b2cca16aa690186", size = 462856, upload-time = "2026-10-24T20:40:44.771Z" }, + { url = "https://files.pythonhosted.org/packages/ff/7f/38310388c4c5e351dfc419a04e4c7a26cde14b0e1019bc72bbd1b0d95613/multidict-7.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:3d6fce7cc4ef63d9a7633cbae43e737798412805a4c3ba876cdf472dc6ff9c51", size = 490108, upload-time = "2026-10-24T20:40:06.965Z" }, + { url = "https://files.pythonhosted.org/packages/ce/0d/94162600e5bbf24bf33398f3b33ae2f78211375313dbdaaf1513b2554a66/multidict-7.2.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:37b161535e92776788957a165fcf38a80b33c1efde7b18cab287db4e4574df78", size = 508935, upload-time = "2026-10-24T20:40:10.882Z" }, + { url = "https://files.pythonhosted.org/packages/1d/40/a0cae932493346cb0d442ffa380e65491fdae8df338d8cdf2f39695c0947/multidict-7.2.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:e47d058c2db95010f5d2e1f6037acebdfb0e2fa4507650e1041437985c91db38", size = 447620, upload-time = "2026-10-24T20:40:10.548Z" }, + { url = "https://files.pythonhosted.org/packages/5e/a5/6ec5cd1c15574aca277ab08920f7e78a6a1e1c15912bfaf59b48683230f7/multidict-7.2.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:7238f7135481926d52a94c18a8cca633a9e72c1cbfccd5796548298a479b0656", size = 523896, upload-time = "2026-10-24T20:40:46.258Z" }, + { url = "https://files.pythonhosted.org/packages/ae/60/d164a2583548561f7e596f13bbd1c3492ea33a77d499d3ceaa2acf76d850/multidict-7.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:c10ac5e3e76837180656079008f71add8339b00c3c26314092bcd1e8e449049f", size = 502961, upload-time = "2026-10-24T20:40:08.732Z" }, + { url = "https://files.pythonhosted.org/packages/30/6b/474aee537e0c87210ce8f4fd21558b461e8a8e74c79440de036022a9eeda/multidict-7.2.1-cp311-cp311-win32.whl", hash = "sha256:2b4d0c4e13d329ffee73d46128e32dd3b4aeb2f9c6ac9c8a89eb28d3b82dcea8", size = 84159, upload-time = "2026-10-24T20:40:12.222Z" }, + { url = "https://files.pythonhosted.org/packages/1f/02/41d769148f32c9bd535fd0ddd946c4e42f38acaddf7899f3bf49d9e67703/multidict-7.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:a789e3d27fc5665cc0477f10a35a89383313e4c9cf8b5e6af7ea71f039cdcc0e", size = 94895, upload-time = "2026-10-24T20:40:12.036Z" }, + { url = "https://files.pythonhosted.org/packages/23/be/e04fcf29542d0db25cdec79acbe5662481c3ba6b760353c393f9c46156f2/multidict-7.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:2022bd3194968a027f64ed16f9779e62e71a823a9df3971a7328c1d45dfeb9ab", size = 92384, upload-time = "2026-10-24T20:40:47.827Z" }, + { url = "https://files.pythonhosted.org/packages/9d/96/1aaad0e5df33f1f5af21775c411349c0234a6edd581ea403bc81919a6eab/multidict-7.2.1-py3-none-any.whl", hash = "sha256:08ea94663d9e7c25d14d78222f7aee906c472d4837766bec62477c38f6e419dc", size = 28145, upload-time = "2026-10-24T20:40:59.159Z" }, +] + +[[package]] +name = "multiprocess" +version = "0.70.15" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dill" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/68/e0/a77ca96e772e13c828fa52f3ad370d413bef194aeaf78b7c6611870ad815/multiprocess-0.70.15.tar.gz", hash = "sha256:f20eed3036c0ef477b07a4177cf7c1ba520d9a2677870a4f47fe026f0cd6787e", size = 1894495, upload-time = "2023-07-23T05:03:29.314Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/a8/36d8d7b3e46b377800d8dec47891cdf05842d1a2366909ae4a0c89fbc5e6/multiprocess-0.70.15-py310-none-any.whl", hash = "sha256:7dd58e33235e83cf09d625e55cffd7b0f0eede7ee9223cdd666a87624f60c21a", size = 134824, upload-time = "2023-07-23T05:03:21.182Z" }, + { url = "https://files.pythonhosted.org/packages/e7/41/96ac938770ba6e7d5ae1d8c9cafebac54b413549042c6260f0d0a6ec6622/multiprocess-0.70.15-py311-none-any.whl", hash = "sha256:134f89053d82c9ed3b73edd3a2531eb791e602d4f4156fc92a79259590bd9670", size = 135392, upload-time = "2023-07-23T05:03:22.885Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3f/8354ce12fd13bd5c5bb4722261a10ca1d6e2eb7c1c08fa3d8a4e9dc98f44/multiprocess-0.70.15-py37-none-any.whl", hash = "sha256:f7d4a1629bccb433114c3b4885f69eccc200994323c80f6feee73b0edc9199c5", size = 116276, upload-time = "2023-07-23T05:03:24.718Z" }, + { url = "https://files.pythonhosted.org/packages/c2/a6/c5cb599d917904878f220a4dbdfdcc4ef291dd3956c35b3b0dc6fc42fb6d/multiprocess-0.70.15-py38-none-any.whl", hash = "sha256:bee9afba476c91f9ebee7beeee0601face9eff67d822e893f9a893725fbd6316", size = 132626, upload-time = "2023-07-23T05:03:25.895Z" }, + { url = "https://files.pythonhosted.org/packages/c6/c9/820b5ab056f4ada76fbe05bd481a948f287957d6cbfd59e2dd2618b408c1/multiprocess-0.70.15-py39-none-any.whl", hash = "sha256:3e0953f5d52b4c76f1c973eaf8214554d146f2be5decb48e928e55c7a2d19338", size = 133349, upload-time = "2023-07-23T05:03:27.022Z" }, +] + +[[package]] +name = "networkx" +version = "3.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c9/b2622292ea83fbb4ec318f5b9ab867d0a28ab43c5717bb85b0a5f6b3b0a4/networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762", size = 2068504, upload-time = "2025-12-08T17:02:38.159Z" }, +] + +[[package]] +name = "nltk" +version = "3.9.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "joblib" }, + { name = "regex" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f9/76/3a5e4312c19a028770f86fd7c058cf9f4ec4321c6cf7526bab998a5b683c/nltk-3.9.2.tar.gz", hash = "sha256:0f409e9b069ca4177c1903c3e843eef90c7e92992fa4931ae607da6de49e1419", size = 2887629, upload-time = "2025-10-01T07:19:23.764Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/90/81ac364ef94209c100e12579629dc92bf7a709a84af32f8c551b02c07e94/nltk-3.9.2-py3-none-any.whl", hash = "sha256:1e209d2b3009110635ed9709a67a1a3e33a10f799490fa71cf4bec218c11c88a", size = 1513404, upload-time = "2025-10-01T07:19:21.648Z" }, +] + +[[package]] +name = "numpy" +version = "1.26.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/65/6e/09db70a523a96d25e115e71cc56a6f9031e7b8cd166c1ac8438307c14058/numpy-1.26.4.tar.gz", hash = "sha256:2a02aba9ed12e4ac4eb3ea9421c420301a0c6460d9830d74a9df87efa4912010", size = 15786129, upload-time = "2024-02-06T00:26:44.495Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/57/baae43d14fe163fa0e4c47f307b6b2511ab8d7d30177c491960504252053/numpy-1.26.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4c66707fabe114439db9068ee468c26bbdf909cac0fb58686a42a24de1760c71", size = 20630554, upload-time = "2024-02-05T23:51:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/151484f49fd03944c4a3ad9c418ed193cfd02724e138ac8a9505d056c582/numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:edd8b5fe47dab091176d21bb6de568acdd906d1887a4584a15a9a96a1dca06ef", size = 13997127, upload-time = "2024-02-05T23:52:15.314Z" }, + { url = "https://files.pythonhosted.org/packages/79/ae/7e5b85136806f9dadf4878bf73cf223fe5c2636818ba3ab1c585d0403164/numpy-1.26.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7ab55401287bfec946ced39700c053796e7cc0e3acbef09993a9ad2adba6ca6e", size = 14222994, upload-time = "2024-02-05T23:52:47.569Z" }, + { url = "https://files.pythonhosted.org/packages/3a/d0/edc009c27b406c4f9cbc79274d6e46d634d139075492ad055e3d68445925/numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:666dbfb6ec68962c033a450943ded891bed2d54e6755e35e5835d63f4f6931d5", size = 18252005, upload-time = "2024-02-05T23:53:15.637Z" }, + { url = "https://files.pythonhosted.org/packages/09/bf/2b1aaf8f525f2923ff6cfcf134ae5e750e279ac65ebf386c75a0cf6da06a/numpy-1.26.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:96ff0b2ad353d8f990b63294c8986f1ec3cb19d749234014f4e7eb0112ceba5a", size = 13885297, upload-time = "2024-02-05T23:53:42.16Z" }, + { url = "https://files.pythonhosted.org/packages/df/a0/4e0f14d847cfc2a633a1c8621d00724f3206cfeddeb66d35698c4e2cf3d2/numpy-1.26.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:60dedbb91afcbfdc9bc0b1f3f402804070deed7392c23eb7a7f07fa857868e8a", size = 18093567, upload-time = "2024-02-05T23:54:11.696Z" }, + { url = "https://files.pythonhosted.org/packages/d2/b7/a734c733286e10a7f1a8ad1ae8c90f2d33bf604a96548e0a4a3a6739b468/numpy-1.26.4-cp311-cp311-win32.whl", hash = "sha256:1af303d6b2210eb850fcf03064d364652b7120803a0b872f5211f5234b399f20", size = 5968812, upload-time = "2024-02-05T23:54:26.453Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6b/5610004206cf7f8e7ad91c5a85a8c71b2f2f8051a0c0c4d5916b76d6cbb2/numpy-1.26.4-cp311-cp311-win_amd64.whl", hash = "sha256:cd25bcecc4974d09257ffcd1f098ee778f7834c3ad767fe5db785be9a4aa9cb2", size = 15811913, upload-time = "2024-02-05T23:54:53.933Z" }, +] + +[[package]] +name = "nvidia-cublas" +version = "13.1.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cuda-nvrtc", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" }, + { url = "https://files.pythonhosted.org/packages/3b/cd/154ca20c38269e05eff77c1464e6c1da89f50a6390b565e9d82e06bc11e1/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:37936a16db8fe4ac1f065c2139360608a543a09275cb1a1af612e08cfa065436", size = 423138758, upload-time = "2026-04-08T18:46:58.655Z" }, + { url = "https://files.pythonhosted.org/packages/45/9e/2f562daf80eb8f7a685fb7bea4fda71f6048e4f359d6fdd1b6e70206cb2f/nvidia_cublas-13.1.1.3-py3-none-win_amd64.whl", hash = "sha256:b6cdce694e47ff6aadf0a69df1cab6628d696f5ff56e8d16af50309d855fa20f", size = 404358158, upload-time = "2026-04-08T18:47:26.987Z" }, +] + +[[package]] +name = "nvidia-cuda-cupti" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/2a/80353b103fc20ce05ef51e928daed4b6015db4aaa9162ed0997090fe2250/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_aarch64.whl", hash = "sha256:796bd679890ee55fb14a94629b698b6db54bcfd833d391d5e94017dd9d7d3151", size = 10310827, upload-time = "2025-09-04T08:26:42.012Z" }, + { url = "https://files.pythonhosted.org/packages/33/6d/737d164b4837a9bbd202f5ae3078975f0525a55730fe871d8ed4e3b952b0/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_x86_64.whl", hash = "sha256:4eb01c08e859bf924d222250d2e8f8b8ff6d3db4721288cf35d14252a4d933c8", size = 10715597, upload-time = "2025-09-04T08:26:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/ad/df/b74b10025c1205695c5676373f2edd3e87a7202cc62ead0dfbc373b0f6ea/nvidia_cuda_cupti-13.0.85-py3-none-win_amd64.whl", hash = "sha256:683f58d301548deeefcb8f6fac1b8d907691b9d8b18eccab417f51e362102f00", size = 7736776, upload-time = "2025-09-04T08:38:08.38Z" }, +] + +[[package]] +name = "nvidia-cuda-nvrtc" +version = "13.0.88" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/68/483a78f5e8f31b08fb1bb671559968c0ca3a065ac7acabfc7cee55214fd6/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:ad9b6d2ead2435f11cbb6868809d2adeeee302e9bb94bcf0539c7a40d80e8575", size = 90215200, upload-time = "2025-09-04T08:28:44.204Z" }, + { url = "https://files.pythonhosted.org/packages/b7/dc/6bb80850e0b7edd6588d560758f17e0550893a1feaf436807d64d2da040f/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d27f20a0ca67a4bb34268a5e951033496c5b74870b868bacd046b1b8e0c3267b", size = 43015449, upload-time = "2025-09-04T08:28:20.239Z" }, + { url = "https://files.pythonhosted.org/packages/4a/af/345fedb9f4c76c84ab4fa445b36bd4048a4d9db60e6bc76b4f913ff4b852/nvidia_cuda_nvrtc-13.0.88-py3-none-win_amd64.whl", hash = "sha256:6bcd4e7f8e205cbe644f5a98f2f799bef9556fefc89dd786e79a16312ce49872", size = 76807835, upload-time = "2025-09-04T08:39:15.274Z" }, +] + +[[package]] +name = "nvidia-cuda-runtime" +version = "13.0.96" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/4f/17d7b9b8e285199c58ce28e31b5c5bbaa4d8271af06a89b6405258245de2/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ef9bcbe90493a2b9d810e43d249adb3d02e98dd30200d86607d8d02687c43f55", size = 2261060, upload-time = "2025-10-09T08:55:15.78Z" }, + { url = "https://files.pythonhosted.org/packages/2e/24/d1558f3b68b1d26e706813b1d10aa1d785e4698c425af8db8edc3dced472/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7f82250d7782aa23b6cfe765ecc7db554bd3c2870c43f3d1821f1d18aebf0548", size = 2243632, upload-time = "2025-10-09T08:55:36.117Z" }, + { url = "https://files.pythonhosted.org/packages/b7/94/6b867483bec07da24ffa32736c79fabb94ef3a7af4d787a9d4a974868576/nvidia_cuda_runtime-13.0.96-py3-none-win_amd64.whl", hash = "sha256:f79298c8a098cec150a597c8eba58ecdab96e3bdc4b9bc4f9983635031740492", size = 2927037, upload-time = "2025-10-09T09:04:23.782Z" }, +] + +[[package]] +name = "nvidia-cudnn-cu13" +version = "9.20.0.48" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cublas", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/c5/83384d846b2fd17c44bd499b36c75a45ed4f095fbbb2252294e89cea5c5c/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:e31454ae00094b0c55319d9d15b6fa2fc50a9e1c0f5c8c80fb75258234e731e1", size = 444574296, upload-time = "2026-03-09T19:28:27.751Z" }, + { url = "https://files.pythonhosted.org/packages/6e/5e/edb9c0ae051602c3ccaffe424256463636d639e27d7f302dde9975ef9e7a/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0c45dd8eeb50b603f07995b1b300c62ffe6a1980482b82b3bcf94a4ca9d49304", size = 366173588, upload-time = "2026-03-09T19:29:34.474Z" }, + { url = "https://files.pythonhosted.org/packages/78/39/21507455b1bca8b5702a9e9fc6ce73735f216f558dac2c9ede58e4d456b8/nvidia_cudnn_cu13-9.20.0.48-py3-none-win_amd64.whl", hash = "sha256:af8139732b99c0118be65ea5aac97f0d46018f8c552889e49d2fb0c6261a4a24", size = 350712614, upload-time = "2026-03-09T19:31:11.398Z" }, +] + +[[package]] +name = "nvidia-cufft" +version = "12.0.0.61" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, + { url = "https://files.pythonhosted.org/packages/a8/2f/7b57e29836ea8714f81e9898409196f47d772d5ddedddf1592eadb8ab743/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6c44f692dce8fd5ffd3e3df134b6cdb9c2f72d99cf40b62c32dde45eea9ddad3", size = 214085489, upload-time = "2025-09-04T08:31:56.044Z" }, + { url = "https://files.pythonhosted.org/packages/85/b2/f8af21a2ed1beed337a6a02c5a28aeb85441f4d578ec3d529543c775ea4b/nvidia_cufft-12.0.0.61-py3-none-win_amd64.whl", hash = "sha256:2abce5b39d2f5ae12730fb7e5db6696533e36c26e2d3e8fd1750bdd2853364eb", size = 213342123, upload-time = "2025-09-04T08:40:51.145Z" }, +] + +[[package]] +name = "nvidia-cufile" +version = "1.15.1.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/70/4f193de89a48b71714e74602ee14d04e4019ad36a5a9f20c425776e72cd6/nvidia_cufile-1.15.1.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:08a3ecefae5a01c7f5117351c64f17c7c62efa5fffdbe24fc7d298da19cd0b44", size = 1223672, upload-time = "2025-09-04T08:32:22.779Z" }, + { url = "https://files.pythonhosted.org/packages/ab/73/cc4a14c9813a8a0d509417cf5f4bdaba76e924d58beb9864f5a7baceefbf/nvidia_cufile-1.15.1.6-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:bdc0deedc61f548bddf7733bdc216456c2fdb101d020e1ab4b88d232d5e2f6d1", size = 1136992, upload-time = "2025-09-04T08:32:14.119Z" }, +] + +[[package]] +name = "nvidia-curand" +version = "10.4.0.35" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/72/7c2ae24fb6b63a32e6ae5d241cc65263ea18d08802aaae087d9f013335a2/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:133df5a7509c3e292aaa2b477afd0194f06ce4ea24d714d616ff36439cee349a", size = 61962106, upload-time = "2025-08-04T10:21:41.128Z" }, + { url = "https://files.pythonhosted.org/packages/a5/9f/be0a41ca4a4917abf5cb9ae0daff1a6060cc5de950aec0396de9f3b52bc5/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:1aee33a5da6e1db083fe2b90082def8915f30f3248d5896bcec36a579d941bfc", size = 59544258, upload-time = "2025-08-04T10:22:03.992Z" }, + { url = "https://files.pythonhosted.org/packages/99/27/72103153b1ffc00e09fdc40ac970235343dcd1ea8bd762e84d2d73219ffa/nvidia_curand-10.4.0.35-py3-none-win_amd64.whl", hash = "sha256:65b1710aa6961d326b411e314b374290904c5ddf41dc3f766ebc3f1d7d4ca69f", size = 55242481, upload-time = "2025-08-04T10:30:41.831Z" }, +] + +[[package]] +name = "nvidia-cusolver" +version = "12.0.4.66" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cublas", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-cusparse", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, + { url = "https://files.pythonhosted.org/packages/5f/67/cba3777620cdacb99102da4042883709c41c709f4b6323c10781a9c3aa34/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0a759da5dea5c0ea10fd307de75cdeb59e7ea4fcb8add0924859b944babf1112", size = 200941980, upload-time = "2025-09-04T08:33:22.767Z" }, + { url = "https://files.pythonhosted.org/packages/99/ef/332a0101260ca78a1daef046bf0b06199e8ed4dac1d2aa698289c358169c/nvidia_cusolver-12.0.4.66-py3-none-win_amd64.whl", hash = "sha256:16515bd33a8e76bb54d024cfa068fa68d30e80fc34b9e1090813ea9362e0cb65", size = 193551444, upload-time = "2025-09-04T08:41:46.813Z" }, +] + +[[package]] +name = "nvidia-cusparse" +version = "12.6.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, + { url = "https://files.pythonhosted.org/packages/fa/18/623c77619c31d62efd55302939756966f3ecc8d724a14dab2b75f1508850/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2b3c89c88d01ee0e477cb7f82ef60a11a4bcd57b6b87c33f789350b59759360b", size = 145942937, upload-time = "2025-09-04T08:33:58.029Z" }, + { url = "https://files.pythonhosted.org/packages/02/b0/b043d6f3480f102f885cf87fc3ffd3edcb5e23b855025a50e2ef4d059185/nvidia_cusparse-12.6.3.3-py3-none-win_amd64.whl", hash = "sha256:cbcf42feb737bd7ec15b4c0a63e62351886bd3f975027b8815d7f720a2b5ea79", size = 143783033, upload-time = "2025-09-04T08:42:12.391Z" }, +] + +[[package]] +name = "nvidia-cusparselt-cu13" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/e1/cdc1797eadf82d3a9a575a19b33fdc871a97edbec42c00b5b5e914f4aff4/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:4dca476c50bf4780d46cd0bfbd82e2bc10a08e4fef7950917ce8d7578d22a23f", size = 221051344, upload-time = "2025-09-05T18:49:51.289Z" }, + { url = "https://files.pythonhosted.org/packages/34/7d/2661f2fb3ac4302f3a246f5fc030213ac60c1fe0bce84f9783dbd831dbb7/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:786ce87568c303fadb5afcc7102d454cd3040d75f6f8626f5db460d1871f4dd0", size = 170148586, upload-time = "2025-09-05T18:50:50.248Z" }, + { url = "https://files.pythonhosted.org/packages/31/83/f3647ce26916c94a6ca4ff1810623e2c405cff2dea6e78d29516b2514df9/nvidia_cusparselt_cu13-0.8.1-py3-none-win_amd64.whl", hash = "sha256:dccbd362f91a7b9024d1f55ee9f548ac065027ff15d8c8b0db889ab3a8f31215", size = 156885108, upload-time = "2025-09-05T18:51:35.958Z" }, +] + +[[package]] +name = "nvidia-nccl-cu13" +version = "2.29.7" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/0d/daf50d44177ee0cbc7ff0a0c91eb5ff676c82be42f9a970bc7597f440c3a/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_aarch64.whl", hash = "sha256:674a12383e3c38a1bcccae7d4f3633b37852230b6047883cb2f4c2d1b36d9bf5", size = 206014712, upload-time = "2026-03-03T05:34:20.843Z" }, + { url = "https://files.pythonhosted.org/packages/67/f4/58e4e91b6919367c7aafb8e36fce9aad1a3047e536bf7e2fd560927d3a4c/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:edd81538446786ec3b73972543e53bb43bcaf0bfc8ef76cb679fcc390ffe136d", size = 205976000, upload-time = "2026-03-03T05:36:24.472Z" }, +] + +[[package]] +name = "nvidia-nvjitlink" +version = "13.5.37" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cc/1f/2321702b8d60b4b4dd18b957f61612dbac9cb1c07e940cf6582106b7c8b8/nvidia_nvjitlink-13.5.37-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:280d7cb9649704145f074b8dbde500de04ce02d0872e066e20a83c17bcaa93eb", size = 46642491, upload-time = "2026-11-04T23:33:31.696Z" }, + { url = "https://files.pythonhosted.org/packages/24/15/dd228f798cd01d7aeaf19d872b2b20f9aeafc1a7d8b6bfaa878b30b8d6f7/nvidia_nvjitlink-13.5.37-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:893f6f9a55b2720ed94913b5ba3332e972da8c78dfa2863d0244403dbd528ffc", size = 45253761, upload-time = "2026-11-04T23:33:22.854Z" }, + { url = "https://files.pythonhosted.org/packages/a7/53/c43398492e8374880d5e01c23c4dac33ba0c3bd03515d6ecc574254c0967/nvidia_nvjitlink-13.5.37-py3-none-win_amd64.whl", hash = "sha256:4465d4e8f2212118220b580c82523c5654f93a62906bd51d29d79bdfc12376c1", size = 41467665, upload-time = "2026-11-04T23:38:44.689Z" }, + { url = "https://files.pythonhosted.org/packages/d7/4a/1ff9ab7d0c961a1b5539f8291c881bea82adbbf8ba40a9e81f9c9b3a8d5d/nvidia_nvjitlink-13.5.37-py3-none-win_arm64.whl", hash = "sha256:eb30348ae64c525180a280025dd12a089c3e2e1dc4e19cdd58f68c6edc622404", size = 38552904, upload-time = "2026-11-04T23:43:27.658Z" }, +] + +[[package]] +name = "nvidia-nvshmem-cu13" +version = "3.4.5" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/0f/05cc9c720236dcd2db9c1ab97fff629e96821be2e63103569da0c9b72f19/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dc2a197f38e5d0376ad52cd1a2a3617d3cdc150fd5966f4aee9bcebb1d68fe9", size = 60215947, upload-time = "2025-09-06T00:32:20.022Z" }, + { url = "https://files.pythonhosted.org/packages/3c/35/a9bf80a609e74e3b000fef598933235c908fcefcef9026042b8e6dfde2a9/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:290f0a2ee94c9f3687a02502f3b9299a9f9fe826e6d0287ee18482e78d495b80", size = 60412546, upload-time = "2025-09-06T00:32:41.564Z" }, +] + +[[package]] +name = "nvidia-nvtx" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c2/f3/d86c845465a2723ad7e1e5c36dcd75ddb82898b3f53be47ebd429fb2fa5d/nvidia_nvtx-13.0.85-py3-none-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4936d1d6780fbe68db454f5e72a42ff64d1fd6397df9f363ae786930fd5c1cd4", size = 148047, upload-time = "2025-09-04T08:29:01.761Z" }, + { url = "https://files.pythonhosted.org/packages/a8/64/3708a90d1ebe202ffdeb7185f878a3c84d15c2b2c31858da2ce0583e2def/nvidia_nvtx-13.0.85-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb7780edb6b14107373c835bf8b72e7a178bac7367e23da7acb108f973f157a6", size = 148878, upload-time = "2025-09-04T08:28:53.627Z" }, + { url = "https://files.pythonhosted.org/packages/d2/50/0e2220f8620a177de994211186ffc5bfa9f2ce1e1282797f8f90096f9f88/nvidia_nvtx-13.0.85-py3-none-win_amd64.whl", hash = "sha256:d66ea44254dd3c6eacc300047af6e1288d2269dd072b417e0adffbf479e18519", size = 137066, upload-time = "2025-09-04T08:39:25.649Z" }, +] + +[[package]] +name = "official-lozo-experiment" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "einops" }, + { name = "matplotlib" }, + { name = "nltk" }, + { name = "numpy" }, + { name = "psutil" }, + { name = "rouge" }, + { name = "scikit-learn" }, + { name = "sentencepiece" }, + { name = "setuptools" }, + { name = "torch" }, + { name = "wandb" }, +] + +[package.dev-dependencies] +modern = [ + { name = "accelerate", version = "1.12.0", source = { registry = "https://pypi.org/simple" } }, + { name = "datasets", version = "3.6.0", source = { registry = "https://pypi.org/simple" } }, + { name = "huggingface-hub" }, + { name = "pyarrow", version = "20.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "transformers", version = "4.57.1", source = { registry = "https://pypi.org/simple" } }, +] +native = [ + { name = "accelerate", version = "0.20.3", source = { registry = "https://pypi.org/simple" } }, + { name = "datasets", version = "2.14.7", source = { registry = "https://pypi.org/simple" } }, + { name = "huggingface-hub" }, + { name = "pyarrow", version = "17.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "transformers", version = "4.28.1", source = { registry = "https://pypi.org/simple" } }, +] + +[package.metadata] +requires-dist = [ + { name = "einops", specifier = "==0.8.1" }, + { name = "matplotlib", specifier = "==3.10.7" }, + { name = "nltk", specifier = "==3.9.2" }, + { name = "numpy", specifier = "==1.26.4" }, + { name = "psutil", specifier = "==7.1.3" }, + { name = "rouge", specifier = "==1.0.1" }, + { name = "scikit-learn", specifier = "==1.7.2" }, + { name = "sentencepiece", specifier = "==0.2.1" }, + { name = "setuptools", specifier = "==80.9.0" }, + { name = "torch", specifier = "==2.13.0" }, + { name = "wandb", specifier = "==0.23.1" }, +] + +[package.metadata.requires-dev] +modern = [ + { name = "accelerate", specifier = "==1.12.0" }, + { name = "datasets", specifier = "==3.6.0" }, + { name = "huggingface-hub", specifier = "==0.36.0" }, + { name = "pyarrow", specifier = "==20.0.0" }, + { name = "transformers", specifier = "==4.57.1" }, +] +native = [ + { name = "accelerate", specifier = "==0.20.3" }, + { name = "datasets", specifier = "==2.14.7" }, + { name = "huggingface-hub", specifier = "==0.36.0" }, + { name = "pyarrow", specifier = "==17.0.0" }, + { name = "transformers", specifier = "==4.28.1" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pandas" +version = "3.0.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e2/17/d7b106e05bfa642e8694451e7d3d759c6a241c5386a5d962e4f66c047e06/pandas-3.0.6.tar.gz", hash = "sha256:66b07ef7315a31bfe1089cd3d71a7de781c9dca986762d0b4fe7c0ef17465d10", size = 4667686, upload-time = "2026-09-17T23:23:18.345Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7d/48/88e8d250d28efa8163294f6809a71683c7ee67f63ac7c33021c0503b3547/pandas-3.0.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:085e3786ae6b2e82b406266bce36690f72b9dc1421903ba9296b2981a9fcf586", size = 10391798, upload-time = "2026-09-17T23:20:20.96Z" }, + { url = "https://files.pythonhosted.org/packages/55/a6/39db5d41f3eb5d7846626312cb30e0cea48e988fc47a3725698bc931ad3c/pandas-3.0.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d7564d86a94c2eb8ab290b07f63ddaae5c032fa53897c29a2ff2197d43aee8af", size = 10023718, upload-time = "2026-09-17T23:20:25.094Z" }, + { url = "https://files.pythonhosted.org/packages/54/b7/707e966129f77ee8a39d41a41bbd989b790b3fef581c6e26b821315cba6b/pandas-3.0.6-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e7c0afdcaf6661d795fcefc2f647ddd1136f62cdc153fba177c685d97a87808", size = 10612800, upload-time = "2026-09-17T23:20:27.99Z" }, + { url = "https://files.pythonhosted.org/packages/63/be/dfb6cc9329d0bbe76dadda8a1113d026bb996ec76c509221368dc68349f4/pandas-3.0.6-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:47121f9571503f724c9b93e297ab6254ac99c77adf5e9ed085ea419fd585c258", size = 11108900, upload-time = "2026-09-17T23:20:30.65Z" }, + { url = "https://files.pythonhosted.org/packages/1a/6f/3d58f15bbe972f3d7bfa13ee06d731785a76fe8d232c92b2655a8de14127/pandas-3.0.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:994a79608263fe1c14cc48ffa7300e2b834b7d1cb406ffe96a08828cb0cdd79b", size = 11630226, upload-time = "2026-09-17T23:20:33.582Z" }, + { url = "https://files.pythonhosted.org/packages/58/54/9b494de4a3dd92fc6eb19187db1b21afb50fdc21962f32ea1aca9f270cb2/pandas-3.0.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a3a22e07fe75347eaacc75b0e85297947af4fba6b4aae23916bd8b6828d0bba3", size = 12146942, upload-time = "2026-09-17T23:20:36.792Z" }, + { url = "https://files.pythonhosted.org/packages/d3/dc/d2df02854aec5d47659acfb2be352eecc691845b2f86e99c84f1010a8671/pandas-3.0.6-cp311-cp311-win_amd64.whl", hash = "sha256:2e5fa32ff162dfdbc280157d664f44d23049ae414725af9676df339c501d82cd", size = 9859246, upload-time = "2026-09-17T23:20:43.976Z" }, + { url = "https://files.pythonhosted.org/packages/79/1e/2a30df0d7dede5c195300a1820b0bc21cea3aa24e4c8b6c4431565ecc79a/pandas-3.0.6-cp311-cp311-win_arm64.whl", hash = "sha256:5e75072773c1b2f7cb63faa3a6f562aede11f3976f68ed34cb538bc091a28171", size = 9106923, upload-time = "2026-09-17T23:20:46.611Z" }, +] + +[[package]] +name = "pillow" +version = "13.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/d7/af6af1b8cc55e07cb0489d5b0950bf5a9bb1461eeba825700b6d8d0e26ea/pillow-13.0.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb", size = 5592324, upload-time = "2026-10-16T22:15:24.672Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d2/2c12cb4fbb5d95f38d1001ff3d95fafcb830077018cba40e56a8f932dfbc/pillow-13.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061", size = 4856298, upload-time = "2026-10-16T22:15:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/229b27472483a4801ea94990815e710391836afdf987b4b722b62bd75db6/pillow-13.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0", size = 6517304, upload-time = "2026-10-16T22:15:29.43Z" }, + { url = "https://files.pythonhosted.org/packages/36/46/f509b74787f40ce0627501089d630b2c741b63b244c1f40b640b3b01e181/pillow-13.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c", size = 7140667, upload-time = "2026-10-16T22:15:31.368Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/5a398b8ec2c37145397d6461c0b551c23ec03072aa64f357aed25e582b00/pillow-13.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f", size = 6610583, upload-time = "2026-10-16T22:15:34.025Z" }, + { url = "https://files.pythonhosted.org/packages/4f/7b/f2f1109b230fd4e2d57ab2305de31adc37ea9b4ff8719436c623cb484415/pillow-13.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806", size = 7218241, upload-time = "2026-10-16T22:15:36.214Z" }, + { url = "https://files.pythonhosted.org/packages/ab/d3/069edb9083b267746baf59756282cacef904d3475c5288c7216fb5195a98/pillow-13.0.0-cp311-cp311-win32.whl", hash = "sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5", size = 6515278, upload-time = "2026-10-16T22:15:38.129Z" }, + { url = "https://files.pythonhosted.org/packages/7d/f6/6e2d96413e4c9dbec12ea584d9e646d602877d4cce3ea669099f959deac6/pillow-13.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3", size = 7278471, upload-time = "2026-10-16T22:15:40.286Z" }, + { url = "https://files.pythonhosted.org/packages/70/e7/baff21f8cb60496c8c250609501b88919eeedb4088d3da106f6c62f3f3c0/pillow-13.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13", size = 2698981, upload-time = "2026-10-16T22:15:42.637Z" }, + { url = "https://files.pythonhosted.org/packages/68/c0/fb7b1caf25ed5ac5d46116f09b8b0706b9559833c65c667cecb1a53153f2/pillow-13.0.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca", size = 5521630, upload-time = "2026-10-16T22:17:50.008Z" }, + { url = "https://files.pythonhosted.org/packages/1a/e6/4d11d5b1137f4fc080605cce410cfaae4f303ad400bdec75d27d3083fa29/pillow-13.0.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039", size = 4806023, upload-time = "2026-10-16T22:17:51.932Z" }, + { url = "https://files.pythonhosted.org/packages/f1/45/0923202a658e8ff6aafd72c1a4395ebadcdebaa182c437d8595d3dd3db32/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad", size = 5464831, upload-time = "2026-10-16T22:17:53.742Z" }, + { url = "https://files.pythonhosted.org/packages/07/52/d3e38f0cad1dadea2a658b9a7d6ba8a04048f5ae14f011b806e5c3bd6bcb/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2", size = 6043133, upload-time = "2026-10-16T22:17:55.625Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f9/2ed7685980c1d64f8131a7d87a19c369424747577152622b73ddeff163b7/pillow-13.0.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c", size = 7365208, upload-time = "2026-10-16T22:17:57.509Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.14.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/9a/8475be631fb33ca1466915e70fd594c42a4e84b512db650eaa14f90fe75d/platformdirs-4.14.5.tar.gz", hash = "sha256:32e9921db7385aa8169bee4fe9501923e5715ba9fb7ea3b9c69b0d8e0639f7a1", size = 71464, upload-time = "2026-11-04T16:54:50.358Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7c/ae/ecbbbfd0e4343a6a521d49b3c8656fb4643dee2a4f6eaf941cf3280391a8/platformdirs-4.14.5-py3-none-any.whl", hash = "sha256:8e778c6fa421516f4d3369449f8df3b0e1b72c0e0005fe88e3ec772d0a14e750", size = 35402, upload-time = "2026-11-04T16:54:48.875Z" }, +] + +[[package]] +name = "propcache" +version = "0.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b3/9a/9fbf4e4ec0c2d7f1c32519fff782ef467859b8faa9fbc5331a96f6395d43/propcache-0.5.4.tar.gz", hash = "sha256:ff6b113f50bc066a698db5d944d2c6dc7507168dd3341e255a8892fd0715a558", size = 61545, upload-time = "2026-09-16T00:17:14.386Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/40/14b21e505b7921617466576423f188a5c9caddfdaa1cf4b2b8a83d8fe216/propcache-0.5.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:897d1ddf6716e8f47200f7aad9a0efa6cc7586df66c6defa572f9eab379c078e", size = 86393, upload-time = "2026-09-16T00:14:06.9Z" }, + { url = "https://files.pythonhosted.org/packages/e7/4b/5a52e1a7b43563f7d408814194bb23cc8bf214eb6b86639b667a33a8d0d0/propcache-0.5.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9cbfff4423eef4cc6cafc021469641a2b835f610b2647a6c5281903e21b8670d", size = 50431, upload-time = "2026-09-16T00:14:08.025Z" }, + { url = "https://files.pythonhosted.org/packages/05/cf/b5248180bf056cc76acc60c9c6e8c0ebbfdbd1c6cffd31fd14996927b7c8/propcache-0.5.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3fc24f209c1b7f7f688b66b98293954f5504279760999b58920ee12dd8471c1d", size = 52116, upload-time = "2026-09-16T00:14:09.114Z" }, + { url = "https://files.pythonhosted.org/packages/86/a8/7c6cd6bfead1a11f2e411e688640e6d26574cb0bde7dcaa7423b0b65ed7a/propcache-0.5.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:62530ca89187827e4a4fe733f971abe81a7542eeea48ff61995f19b64d7199c8", size = 238729, upload-time = "2026-09-16T00:14:10.357Z" }, + { url = "https://files.pythonhosted.org/packages/5c/b4/442715b2e980df51be52d203549279e027728f24c80b00b5e525e31cd5ea/propcache-0.5.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:56fc3f7599528db40b1efa0889a620116e2704144495273d66066e8164e45838", size = 246121, upload-time = "2026-09-16T00:14:11.735Z" }, + { url = "https://files.pythonhosted.org/packages/bc/5d/df0684fc2b1732a01a7bec26d7897369022712422d25b09c37ce7dbc88a2/propcache-0.5.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4f2d880ff60f45898f4acfa152aac8d04e3ee627d90ff4003491bf92239d5757", size = 251735, upload-time = "2026-09-16T00:14:13.053Z" }, + { url = "https://files.pythonhosted.org/packages/c7/06/519a5ebb48b6f94beb48396e55c905f12246a25c3a3608a7ec7bceabf50e/propcache-0.5.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6e9368e87a3efc285e559131092c5db643eb8e56de4ee42064d5baec22ef2bb5", size = 235381, upload-time = "2026-09-16T00:14:14.398Z" }, + { url = "https://files.pythonhosted.org/packages/3c/07/1e0a9bb310830f2245edbd5cd3c6d24a783c053c4efd8e08e386e513c940/propcache-0.5.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:004e685b315646c410771836e72a44f143bbe624f29653a42687815069a303d5", size = 208973, upload-time = "2026-09-16T00:14:15.715Z" }, + { url = "https://files.pythonhosted.org/packages/62/5c/9324fab27d6088eecc47fe4332bf7aaf8c1ded93c36f558391e8a06d41a7/propcache-0.5.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:594eb4c6ec35e7179b058481f4e9f02521b56de16fa577c4b85c76fb1bf8a9f8", size = 233897, upload-time = "2026-09-16T00:14:17.25Z" }, + { url = "https://files.pythonhosted.org/packages/9c/a3/570d92fc952eae93b676f3a1568f4b89264102abd3c982ab6a9ebec58dcf/propcache-0.5.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:2dba2f02d2d5c09ef8a0e6c1a42aeaa451f4be9898cb00b04fe98717da2eb23b", size = 223512, upload-time = "2026-09-16T00:14:18.87Z" }, + { url = "https://files.pythonhosted.org/packages/65/47/26810d889d89bba31db397e6a88f8984af775f5ed6bad0a29dce84324cff/propcache-0.5.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:c3ef2818d63bc86071e9d2989ae75a1bc32b8f7059cfd9f5abbbee70c32e2ed6", size = 239043, upload-time = "2026-09-16T00:14:20.366Z" }, + { url = "https://files.pythonhosted.org/packages/89/2d/f9c47691aa024c8299a3afacd78d22a01ab57eb627b481b6089708e71017/propcache-0.5.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:dd2ac8f5b643454c2cc6b6118b13da16e88f4a6434fc3ba61aca384029f04f36", size = 208218, upload-time = "2026-09-16T00:14:21.801Z" }, + { url = "https://files.pythonhosted.org/packages/74/6b/d510c0c378cabbf9d0ac7b663af6d00f2e9074073d93b20c85f24aa5c071/propcache-0.5.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:4054acf80d40456a0537f2913b349718649d8d6458a14ab7f48d0ce28c30869d", size = 240301, upload-time = "2026-09-16T00:14:23.121Z" }, + { url = "https://files.pythonhosted.org/packages/3d/80/c80f6adaaa1e51f0db2dce8c9b3714d94ec45e358a21f9a1910b10b40a80/propcache-0.5.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:40e94adb1e7d39ff28a8bd8d8b8fbd1df6b9f40976dbe379134f1ce058e532dd", size = 230785, upload-time = "2026-09-16T00:14:24.458Z" }, + { url = "https://files.pythonhosted.org/packages/d9/e2/c32a7df3f39caa7f11b2eb37ea5b6960a6946f2bc7c4b8ff97bbdf6d6b6e/propcache-0.5.4-cp311-cp311-win32.whl", hash = "sha256:9f86f7259efe2c951f43e57d471c9b41daa5bfc7db9f67189059cf1ae6d77fd9", size = 42747, upload-time = "2026-09-16T00:14:25.715Z" }, + { url = "https://files.pythonhosted.org/packages/0a/8a/3db6a3543d8101263b4c52978b6276a04ead2caff2c5ab880d934f47bd89/propcache-0.5.4-cp311-cp311-win_amd64.whl", hash = "sha256:e904d4d01f36bd6e197590be1533c44e06058771e0746dd073a8ebb3ef880858", size = 46268, upload-time = "2026-09-16T00:14:26.996Z" }, + { url = "https://files.pythonhosted.org/packages/41/07/5222e2665bbf6e45847492ecbf3b9f3e4975a0ae300e5fd465df7d48ce55/propcache-0.5.4-cp311-cp311-win_arm64.whl", hash = "sha256:d42a9a856a4a6e2f6c10f1318c07e7daa498d6593abe745c71dae4521a26ca39", size = 43547, upload-time = "2026-09-16T00:14:28.143Z" }, + { url = "https://files.pythonhosted.org/packages/f5/cd/785c64ed382f3f04201870267b02783f63b4678c2acfddc177a3ebcc2727/propcache-0.5.4-py3-none-any.whl", hash = "sha256:62c60aec739ed00124573cce1178138fd690c7676352d67a37328c1cf51d7468", size = 16338, upload-time = "2026-09-16T00:17:13.106Z" }, +] + +[[package]] +name = "protobuf" +version = "6.33.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/66/70/e908e9c5e52ef7c3a6c7902c9dfbb34c7e29c25d2f81ade3856445fd5c94/protobuf-6.33.6.tar.gz", hash = "sha256:a6768d25248312c297558af96a9f9c929e8c4cee0659cb07e780731095f38135", size = 444531, upload-time = "2026-03-18T19:05:00.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/9f/2f509339e89cfa6f6a4c4ff50438db9ca488dec341f7e454adad60150b00/protobuf-6.33.6-cp310-abi3-win32.whl", hash = "sha256:7d29d9b65f8afef196f8334e80d6bc1d5d4adedb449971fefd3723824e6e77d3", size = 425739, upload-time = "2026-03-18T19:04:48.373Z" }, + { url = "https://files.pythonhosted.org/packages/76/5d/683efcd4798e0030c1bab27374fd13a89f7c2515fb1f3123efdfaa5eab57/protobuf-6.33.6-cp310-abi3-win_amd64.whl", hash = "sha256:0cd27b587afca21b7cfa59a74dcbd48a50f0a6400cfb59391340ad729d91d326", size = 437089, upload-time = "2026-03-18T19:04:50.381Z" }, + { url = "https://files.pythonhosted.org/packages/5c/01/a3c3ed5cd186f39e7880f8303cc51385a198a81469d53d0fdecf1f64d929/protobuf-6.33.6-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:9720e6961b251bde64edfdab7d500725a2af5280f3f4c87e57c0208376aa8c3a", size = 427737, upload-time = "2026-03-18T19:04:51.866Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/b3c01fdec7d2f627b3a6884243ba328c1217ed2d978def5c12dc50d328a3/protobuf-6.33.6-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:e2afbae9b8e1825e3529f88d514754e094278bb95eadc0e199751cdd9a2e82a2", size = 324610, upload-time = "2026-03-18T19:04:53.096Z" }, + { url = "https://files.pythonhosted.org/packages/9b/ca/25afc144934014700c52e05103c2421997482d561f3101ff352e1292fb81/protobuf-6.33.6-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:c96c37eec15086b79762ed265d59ab204dabc53056e3443e702d2681f4b39ce3", size = 339381, upload-time = "2026-03-18T19:04:54.616Z" }, + { url = "https://files.pythonhosted.org/packages/16/92/d1e32e3e0d894fe00b15ce28ad4944ab692713f2e7f0a99787405e43533a/protobuf-6.33.6-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:e9db7e292e0ab79dd108d7f1a94fe31601ce1ee3f7b79e0692043423020b0593", size = 323436, upload-time = "2026-03-18T19:04:55.768Z" }, + { url = "https://files.pythonhosted.org/packages/c4/72/02445137af02769918a93807b2b7890047c32bfb9f90371cbc12688819eb/protobuf-6.33.6-py3-none-any.whl", hash = "sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901", size = 170656, upload-time = "2026-03-18T19:04:59.826Z" }, +] + +[[package]] +name = "psutil" +version = "7.1.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e1/88/bdd0a41e5857d5d703287598cbf08dad90aed56774ea52ae071bae9071b6/psutil-7.1.3.tar.gz", hash = "sha256:6c86281738d77335af7aec228328e944b30930899ea760ecf33a4dba66be5e74", size = 489059, upload-time = "2025-11-02T12:25:54.619Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/94/46b9154a800253e7ecff5aaacdf8ebf43db99de4a2dfa18575b02548654e/psutil-7.1.3-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2bdbcd0e58ca14996a42adf3621a6244f1bb2e2e528886959c72cf1e326677ab", size = 238359, upload-time = "2025-11-02T12:26:25.284Z" }, + { url = "https://files.pythonhosted.org/packages/68/3a/9f93cff5c025029a36d9a92fef47220ab4692ee7f2be0fba9f92813d0cb8/psutil-7.1.3-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:bc31fa00f1fbc3c3802141eede66f3a2d51d89716a194bf2cd6fc68310a19880", size = 239171, upload-time = "2025-11-02T12:26:27.23Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b1/5f49af514f76431ba4eea935b8ad3725cdeb397e9245ab919dbc1d1dc20f/psutil-7.1.3-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3bb428f9f05c1225a558f53e30ccbad9930b11c3fc206836242de1091d3e7dd3", size = 263261, upload-time = "2025-11-02T12:26:29.48Z" }, + { url = "https://files.pythonhosted.org/packages/e0/95/992c8816a74016eb095e73585d747e0a8ea21a061ed3689474fabb29a395/psutil-7.1.3-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56d974e02ca2c8eb4812c3f76c30e28836fffc311d55d979f1465c1feeb2b68b", size = 264635, upload-time = "2025-11-02T12:26:31.74Z" }, + { url = "https://files.pythonhosted.org/packages/55/4c/c3ed1a622b6ae2fd3c945a366e64eb35247a31e4db16cf5095e269e8eb3c/psutil-7.1.3-cp37-abi3-win_amd64.whl", hash = "sha256:f39c2c19fe824b47484b96f9692932248a54c43799a84282cfe58d05a6449efd", size = 247633, upload-time = "2025-11-02T12:26:33.887Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ad/33b2ccec09bf96c2b2ef3f9a6f66baac8253d7565d8839e024a6b905d45d/psutil-7.1.3-cp37-abi3-win_arm64.whl", hash = "sha256:bd0d69cee829226a761e92f28140bec9a5ee9d5b4fb4b0cc589068dbfff559b1", size = 244608, upload-time = "2025-11-02T12:26:36.136Z" }, +] + +[[package]] +name = "pyarrow" +version = "17.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/27/4e/ea6d43f324169f8aec0e57569443a38bab4b398d09769ca64f7b4d467de3/pyarrow-17.0.0.tar.gz", hash = "sha256:4beca9521ed2c0921c1023e68d097d0299b62c362639ea315572a58f3f50fd28", size = 1112479, upload-time = "2024-07-17T10:41:25.092Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/46/ce89f87c2936f5bb9d879473b9663ce7a4b1f4359acc2f0eb39865eaa1af/pyarrow-17.0.0-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:1c8856e2ef09eb87ecf937104aacfa0708f22dfeb039c363ec99735190ffb977", size = 29028748, upload-time = "2024-07-16T10:30:02.609Z" }, + { url = "https://files.pythonhosted.org/packages/8d/8e/ce2e9b2146de422f6638333c01903140e9ada244a2a477918a368306c64c/pyarrow-17.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2e19f569567efcbbd42084e87f948778eb371d308e137a0f97afe19bb860ccb3", size = 27190965, upload-time = "2024-07-16T10:30:10.718Z" }, + { url = "https://files.pythonhosted.org/packages/3b/c8/5675719570eb1acd809481c6d64e2136ffb340bc387f4ca62dce79516cea/pyarrow-17.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b244dc8e08a23b3e352899a006a26ae7b4d0da7bb636872fa8f5884e70acf15", size = 39269081, upload-time = "2024-07-16T10:30:18.878Z" }, + { url = "https://files.pythonhosted.org/packages/5e/78/3931194f16ab681ebb87ad252e7b8d2c8b23dad49706cadc865dff4a1dd3/pyarrow-17.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0b72e87fe3e1db343995562f7fff8aee354b55ee83d13afba65400c178ab2597", size = 39864921, upload-time = "2024-07-16T10:30:27.008Z" }, + { url = "https://files.pythonhosted.org/packages/d8/81/69b6606093363f55a2a574c018901c40952d4e902e670656d18213c71ad7/pyarrow-17.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:dc5c31c37409dfbc5d014047817cb4ccd8c1ea25d19576acf1a001fe07f5b420", size = 38740798, upload-time = "2024-07-16T10:30:34.814Z" }, + { url = "https://files.pythonhosted.org/packages/4c/21/9ca93b84b92ef927814cb7ba37f0774a484c849d58f0b692b16af8eebcfb/pyarrow-17.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:e3343cb1e88bc2ea605986d4b94948716edc7a8d14afd4e2c097232f729758b4", size = 39871877, upload-time = "2024-07-16T10:30:42.672Z" }, + { url = "https://files.pythonhosted.org/packages/30/d1/63a7c248432c71c7d3ee803e706590a0b81ce1a8d2b2ae49677774b813bb/pyarrow-17.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:a27532c38f3de9eb3e90ecab63dfda948a8ca859a66e3a47f5f42d1e403c4d03", size = 25151089, upload-time = "2024-07-16T10:30:49.279Z" }, +] + +[[package]] +name = "pyarrow" +version = "20.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/a2/ee/a7810cb9f3d6e9238e61d312076a9859bf3668fd21c69744de9532383912/pyarrow-20.0.0.tar.gz", hash = "sha256:febc4a913592573c8d5805091a6c2b5064c8bd6e002131f01061797d91c783c1", size = 1125187, upload-time = "2025-04-27T12:34:23.264Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/a2/b7930824181ceadd0c63c1042d01fa4ef63eee233934826a7a2a9af6e463/pyarrow-20.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:24ca380585444cb2a31324c546a9a56abbe87e26069189e14bdba19c86c049f0", size = 30856035, upload-time = "2025-04-27T12:28:40.78Z" }, + { url = "https://files.pythonhosted.org/packages/9b/18/c765770227d7f5bdfa8a69f64b49194352325c66a5c3bb5e332dfd5867d9/pyarrow-20.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:95b330059ddfdc591a3225f2d272123be26c8fa76e8c9ee1a77aad507361cfdb", size = 32309552, upload-time = "2025-04-27T12:28:47.051Z" }, + { url = "https://files.pythonhosted.org/packages/44/fb/dfb2dfdd3e488bb14f822d7335653092dde150cffc2da97de6e7500681f9/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5f0fb1041267e9968c6d0d2ce3ff92e3928b243e2b6d11eeb84d9ac547308232", size = 41334704, upload-time = "2025-04-27T12:28:55.064Z" }, + { url = "https://files.pythonhosted.org/packages/58/0d/08a95878d38808051a953e887332d4a76bc06c6ee04351918ee1155407eb/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b8ff87cc837601532cc8242d2f7e09b4e02404de1b797aee747dd4ba4bd6313f", size = 42399836, upload-time = "2025-04-27T12:29:02.13Z" }, + { url = "https://files.pythonhosted.org/packages/f3/cd/efa271234dfe38f0271561086eedcad7bc0f2ddd1efba423916ff0883684/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:7a3a5dcf54286e6141d5114522cf31dd67a9e7c9133d150799f30ee302a7a1ab", size = 40711789, upload-time = "2025-04-27T12:29:09.951Z" }, + { url = "https://files.pythonhosted.org/packages/46/1f/7f02009bc7fc8955c391defee5348f510e589a020e4b40ca05edcb847854/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:a6ad3e7758ecf559900261a4df985662df54fb7fdb55e8e3b3aa99b23d526b62", size = 42301124, upload-time = "2025-04-27T12:29:17.187Z" }, + { url = "https://files.pythonhosted.org/packages/4f/92/692c562be4504c262089e86757a9048739fe1acb4024f92d39615e7bab3f/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6bb830757103a6cb300a04610e08d9636f0cd223d32f388418ea893a3e655f1c", size = 42916060, upload-time = "2025-04-27T12:29:24.253Z" }, + { url = "https://files.pythonhosted.org/packages/a4/ec/9f5c7e7c828d8e0a3c7ef50ee62eca38a7de2fa6eb1b8fa43685c9414fef/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96e37f0766ecb4514a899d9a3554fadda770fb57ddf42b63d80f14bc20aa7db3", size = 44547640, upload-time = "2025-04-27T12:29:32.782Z" }, + { url = "https://files.pythonhosted.org/packages/54/96/46613131b4727f10fd2ffa6d0d6f02efcc09a0e7374eff3b5771548aa95b/pyarrow-20.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:3346babb516f4b6fd790da99b98bed9708e3f02e734c84971faccb20736848dc", size = 25781491, upload-time = "2025-04-27T12:29:38.464Z" }, +] + +[[package]] +name = "pyarrow-hotfix" +version = "0.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d2/ed/c3e8677f7abf3981838c2af7b5ac03e3589b3ef94fcb31d575426abae904/pyarrow_hotfix-0.7.tar.gz", hash = "sha256:59399cd58bdd978b2e42816a4183a55c6472d4e33d183351b6069f11ed42661d", size = 9910, upload-time = "2025-04-25T10:17:06.247Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2e/c3/94ade4906a2f88bc935772f59c934013b4205e773bcb4239db114a6da136/pyarrow_hotfix-0.7-py3-none-any.whl", hash = "sha256:3236f3b5f1260f0e2ac070a55c1a7b339c4bb7267839bd2015e283234e758100", size = 7923, upload-time = "2025-04-25T10:17:05.224Z" }, +] + +[[package]] +name = "pydantic" +version = "2.14.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/fc/1203d011145c98ddce3cd2f505bb54375ef8d43223053df6bfcf3c746f46/pydantic-2.14.3.tar.gz", hash = "sha256:1054f237f4d4733e5a30e1e2333bd33a2004ab9ab1510bd053a9a31bb48e232d", size = 925636, upload-time = "2026-11-05T09:17:04.686Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/b8/b864503789ef5c58597d2a7b4adbee62c26440ab1e682581fc6838df8947/pydantic-2.14.3-py3-none-any.whl", hash = "sha256:3f7b347782ab7e4cf4c798496ae3a82787d9f21ec12676a9c564355eeef8daa8", size = 494071, upload-time = "2026-11-05T09:17:02.426Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.50.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9c/0f/34f9ce4ba701dd0b815033ef94d99b56f66200e578ee6052aa3ac26f064e/pydantic_core-2.50.4.tar.gz", hash = "sha256:aead3b74b68396bf0feab5d57e050b730ded7df55853c1e048a87e00aaf033c6", size = 522249, upload-time = "2026-11-05T09:15:26.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/00/85e80811834d7cbd9bc228f9b5cdf8ec0edd69b55351ad720aac8c412d8c/pydantic_core-2.50.4-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:3e547ceec1da7382f01f9e13963023e53367a71802c88778b21b9645a077cbdf", size = 2170584, upload-time = "2026-11-05T09:11:41.139Z" }, + { url = "https://files.pythonhosted.org/packages/a3/f1/438de1fb99d717dcc6521922478dc16ef7b757302d4fc1f7faba3aaeac09/pydantic_core-2.50.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c813ada7a651193acda85b6bc1cf12abd4b37cd25c7c6a75d7183512cc374969", size = 2128471, upload-time = "2026-11-05T09:11:42.65Z" }, + { url = "https://files.pythonhosted.org/packages/b7/74/f21ab568c6d3f315988b40e53f809c95b63fafc5403332963aa6dfc2c054/pydantic_core-2.50.4-cp311-cp311-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:57fa0a9490785139f1a4e4f43891830d55dfe4408845c0c9cb5eff4aeaf75f69", size = 2281509, upload-time = "2026-11-05T09:11:44.359Z" }, + { url = "https://files.pythonhosted.org/packages/a1/42/24ed3ea8e2fb6463c9ba5b8b1f089e69040905c7fd81dcfa6f52fcc692d5/pydantic_core-2.50.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:30d4dc35bc0eea52202a90b3820445ee0072c820241bfa710a623a078c9b267b", size = 2128064, upload-time = "2026-11-05T09:11:46.01Z" }, + { url = "https://files.pythonhosted.org/packages/d6/d1/44f541b2c18a46df6f18281a557acefeb5bbf0733a0b80b0a5e835e10ee4/pydantic_core-2.50.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:789f88dea57841cdebef392b5d6e90444d767117e9ff2e0d9172df5c9de6690c", size = 2214472, upload-time = "2026-11-05T09:11:47.503Z" }, + { url = "https://files.pythonhosted.org/packages/bd/1b/e9a9ad8733e8051abca9e4acce37ba3ddd13930fd3b8730f4c7816fa979a/pydantic_core-2.50.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:d690121e80ab16e623415351ab24713534d4e500b3cadff216409cb6826063d4", size = 2401153, upload-time = "2026-11-05T09:11:49.403Z" }, + { url = "https://files.pythonhosted.org/packages/79/84/d88e8e6aa42d4d677666d6625db9177ad6851be9e7564a25aeb0b0cbcaf2/pydantic_core-2.50.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b42f64825f5d750228f08318a9bf4d723b7ecb4c472aedcb3013c3ec2dc1f949", size = 2453307, upload-time = "2026-11-05T09:11:51.118Z" }, + { url = "https://files.pythonhosted.org/packages/56/51/cbb7a1bc0196ff94d3478d265eed7449f811759988eb760d41f4edd0893b/pydantic_core-2.50.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0574866e05f6adeecc520d87e87dd06210c0a51706341f6ef8421572f5a64444", size = 2253434, upload-time = "2026-11-05T09:11:52.997Z" }, + { url = "https://files.pythonhosted.org/packages/9e/04/206b4881d631033ae88f005da6e11bd610c850e1850217342c03053d253b/pydantic_core-2.50.4-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:dcf2c7eaaa4cafe8e49b017e5bb49e76e084ab6f0cd712ee4019c812b5cf68b8", size = 2279365, upload-time = "2026-11-05T09:11:54.822Z" }, + { url = "https://files.pythonhosted.org/packages/a1/7c/d815b5a3f83069b283d3b6a2e61de6e14baac3b20c6cd3418e9e629551cf/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:3b8ee2589a082739c522c1fe4be227412fcf108b903abb6672ae2f5570558882", size = 2319407, upload-time = "2026-11-05T09:11:56.46Z" }, + { url = "https://files.pythonhosted.org/packages/ee/00/c9a483276d1052d5142e1e01eccac97d939f83a3a3fd94c4766495a9b807/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:aec3c2d741a8e3ee993de7f95f37afb51e31b169c95dbd29da4cf6688f340914", size = 2489900, upload-time = "2026-11-05T09:11:58.102Z" }, + { url = "https://files.pythonhosted.org/packages/2d/b5/8cd8ee29a1d63ad47f95593384df92476cef6896c644f280db0748b8e76b/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8923fcd49f875e8a0448d7223d1fdf1a9973ae2d1f20d4158753ceb8909facd2", size = 2497732, upload-time = "2026-11-05T09:11:59.928Z" }, + { url = "https://files.pythonhosted.org/packages/60/31/050a48c0c373df16442ac07f3fa167414bb0e22f54a3e886f6d6cb7ad1d4/pydantic_core-2.50.4-cp311-cp311-win32.whl", hash = "sha256:fc04affef30be98c1f36f0c422a4061ef618fdc1dde79f5ad5458dd496fecffa", size = 2132347, upload-time = "2026-11-05T09:12:01.928Z" }, + { url = "https://files.pythonhosted.org/packages/c6/06/cebeeb7a8e87b42a3d8bc189d0d400e47df5d1736cb326764bae8a74c433/pydantic_core-2.50.4-cp311-cp311-win_amd64.whl", hash = "sha256:15bece43a02ad543c621c8305e67dedb5f27d378c5ba741e5a2c36523f8ef37f", size = 2255970, upload-time = "2026-11-05T09:12:03.888Z" }, + { url = "https://files.pythonhosted.org/packages/46/db/5b4bf14347da658c994483043fbabffedcab98929c41c261ec168c3c1f87/pydantic_core-2.50.4-cp311-cp311-win_arm64.whl", hash = "sha256:e498900bfbf7ddddd862f810440c09e9b81674739e8a11d619b40906dccd4a9a", size = 2196799, upload-time = "2026-11-05T09:12:05.389Z" }, + { url = "https://files.pythonhosted.org/packages/d8/18/3ca5b3b8ce7a540305e6856d013e9c6b9c0fef93258fef6038db0beb233a/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:39f489ce31272073e6e146f6781690f9c1ee8c126836e6403361ef91154d89fe", size = 2166960, upload-time = "2026-11-05T09:15:06.902Z" }, + { url = "https://files.pythonhosted.org/packages/a3/60/65d725001bffcde0170f6d37ae8bccce715e5311122eb6127f698115957e/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:5b26e5f1793b96cdc60242bf38da86ff24a27a708aa396214cac9b534bf571c7", size = 2085636, upload-time = "2026-11-05T09:15:08.395Z" }, + { url = "https://files.pythonhosted.org/packages/ac/12/934cf1d44a3fee3c47231d4690dddee19264150c3aa59a3ddf66fa43454d/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:7210398a1607ad607dc73196e575b3148b00a333cbb602ddbe1b60ba54554f43", size = 2284621, upload-time = "2026-11-05T09:15:09.82Z" }, + { url = "https://files.pythonhosted.org/packages/c4/91/52248eee98d76f8d9239166d24928f805292df16729109f4f189cdb59be4/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2f42584e5785385f681163a42506cab0d51295e17599a648396c52a7046c1372", size = 2277673, upload-time = "2026-11-05T09:15:11.236Z" }, + { url = "https://files.pythonhosted.org/packages/9f/89/900a7970ef19843aa79522a95b461e9c365b7fedd7ee80ef28a84dae9a41/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:2039e323acee9abfec1fb5f661776e8965fe5928f3b7f8431900a774cba5c317", size = 2297354, upload-time = "2026-11-05T09:15:12.798Z" }, + { url = "https://files.pythonhosted.org/packages/de/ec/053d829437f70070cdd7116a0257cc0da651103328ff1e9e82954c45efd6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:71ade6d2e445839350d589ff99bbddfde16f3f32db28da5c894a09f99c8b2a03", size = 2469913, upload-time = "2026-11-05T09:15:14.319Z" }, + { url = "https://files.pythonhosted.org/packages/80/af/207c821cb0813e16d630660e0073491e3ab07370efaa6fa0b8b10fffb7b6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:d7d406709ae924cf0b08b8282ca2f0e1c90526911d93bc040557cbc83b74c55f", size = 2503746, upload-time = "2026-11-05T09:15:15.736Z" }, + { url = "https://files.pythonhosted.org/packages/e7/ca/8a053f24e22d8150349cabaecb2f35c89dcf07fbaadb5e48295184dd0e5b/pydantic_core-2.50.4-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:7472c39480ccc11dda69a196d1b7c7a6b48eb6594b77f05d945599d3e47f731c", size = 2333540, upload-time = "2026-11-05T09:15:17.883Z" }, + { url = "https://files.pythonhosted.org/packages/ac/9d/41b374c62cdb87f84081e2ef2963a115eacc6284a26dbc96bb83568e83ec/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_10_12_x86_64.whl", hash = "sha256:b67d38e8bb0ade7e6e84575e4bb153fab35b122458077273aeb08fdf12be9d2c", size = 2166962, upload-time = "2026-11-05T09:15:20.276Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/51ef440ee346d4388a2c4a3ac4b271fcc7b1d3ff68be8da2ed2be4d488b0/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:4eda7e3fdef382b7d4492745988a5baaf6953923a337f8b9dde5f76fa8afde20", size = 2085634, upload-time = "2026-11-05T09:15:21.953Z" }, + { url = "https://files.pythonhosted.org/packages/4b/5f/c9ed62b96beb9050db221d29e81856b6e28f277db601f8b0c3a08f8cf913/pydantic_core-2.50.4-pp311-pypy311_pp80-manylinux_2_28_x86_64.whl", hash = "sha256:474f7e598c7902165662a5d5160d3fce31037890a2975a9871ebf7c05862300b", size = 2277804, upload-time = "2026-11-05T09:15:23.836Z" }, + { url = "https://files.pythonhosted.org/packages/63/bd/b912a5e251ef10ed7be5e543a2bfbeebb0c79bf6302bee786f8dc3bf4341/pydantic_core-2.50.4-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:3e0b395648c6cb871bceb2906907f255dc876ec425f2d5b024e129985cea8519", size = 2333539, upload-time = "2026-11-05T09:15:25.354Z" }, +] + +[[package]] +name = "pyparsing" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/11/b213bebff182584360cb8d17c72c1677fec5c5c228de439e63bcf8ab1c8f/pyparsing-3.3.3.tar.gz", hash = "sha256:928ae7e20211f3b6f3915a72f06a0cfd29ab9d24279dd6346b6b1a7146397d36", size = 1050487, upload-time = "2026-09-20T20:59:05.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" }, +] + +[[package]] +name = "python-dateutil" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/16/a95b6757765b7b031c9374925bb718d55e0a9ba8a1b6a12d25962ea44347/pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", size = 185826, upload-time = "2025-09-25T21:31:58.655Z" }, + { url = "https://files.pythonhosted.org/packages/16/19/13de8e4377ed53079ee996e1ab0a9c33ec2faf808a4647b7b4c0d46dd239/pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", size = 175577, upload-time = "2025-09-25T21:32:00.088Z" }, + { url = "https://files.pythonhosted.org/packages/0c/62/d2eb46264d4b157dae1275b573017abec435397aa59cbcdab6fc978a8af4/pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", size = 775556, upload-time = "2025-09-25T21:32:01.31Z" }, + { url = "https://files.pythonhosted.org/packages/10/cb/16c3f2cf3266edd25aaa00d6c4350381c8b012ed6f5276675b9eba8d9ff4/pyyaml-6.0.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00", size = 882114, upload-time = "2025-09-25T21:32:03.376Z" }, + { url = "https://files.pythonhosted.org/packages/71/60/917329f640924b18ff085ab889a11c763e0b573da888e8404ff486657602/pyyaml-6.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d", size = 806638, upload-time = "2025-09-25T21:32:04.553Z" }, + { url = "https://files.pythonhosted.org/packages/dd/6f/529b0f316a9fd167281a6c3826b5583e6192dba792dd55e3203d3f8e655a/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a", size = 767463, upload-time = "2025-09-25T21:32:06.152Z" }, + { url = "https://files.pythonhosted.org/packages/f2/6a/b627b4e0c1dd03718543519ffb2f1deea4a1e6d42fbab8021936a4d22589/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4", size = 794986, upload-time = "2025-09-25T21:32:07.367Z" }, + { url = "https://files.pythonhosted.org/packages/45/91/47a6e1c42d9ee337c4839208f30d9f09caa9f720ec7582917b264defc875/pyyaml-6.0.3-cp311-cp311-win32.whl", hash = "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b", size = 142543, upload-time = "2025-09-25T21:32:08.95Z" }, + { url = "https://files.pythonhosted.org/packages/da/e3/ea007450a105ae919a72393cb06f122f288ef60bba2dc64b26e2646fa315/pyyaml-6.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf", size = 158763, upload-time = "2025-09-25T21:32:09.96Z" }, +] + +[[package]] +name = "regex" +version = "2026.11.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/61/27/a5afeb952577b84ee5fe48b8b9ce47ae662dbb69cc5b76c28eff98f83b1e/regex-2026.11.9.tar.gz", hash = "sha256:316a70fbd70e999c9664681cb0eb5b4982b2cc0f623c7c86a8a112e1bd4c6277", size = 419513, upload-time = "2026-11-09T00:42:09.786Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/cd/83393cd04d1cdafb07dc6d3e4f6f40455c7d54edcfb7513a51c632a2fa32/regex-2026.11.9-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bc0414bae708e91fa635af848ea1fdc13e442f30497077da562014f88ac67436", size = 496166, upload-time = "2026-11-09T00:39:39.152Z" }, + { url = "https://files.pythonhosted.org/packages/13/90/65cd23cc77094ea6953a7f4f9808539611b71881b7d91729243fcaa43109/regex-2026.11.9-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:26f5137412492f043d13903b8ee3bbc464a73c67ec9432e187f5a5eef25c398f", size = 295747, upload-time = "2026-11-09T00:39:40.41Z" }, + { url = "https://files.pythonhosted.org/packages/3d/61/6523251b377f38be938342fd52da4aead1a1d1b79ce137d4412e5b1eb79e/regex-2026.11.9-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:cf8ba77a8d23fac7912cd9890a49d8f006106147bb80312c9954558b24ec7f95", size = 292719, upload-time = "2026-11-09T00:39:41.711Z" }, + { url = "https://files.pythonhosted.org/packages/97/5c/59cceda8ed285cb277f90f22b220c89576a38ebd1f2d7f0af198af98a5c7/regex-2026.11.9-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c876a5e3992b5f14709c7260188929174247485ed3f940bd94d4beb70abbfed3", size = 799904, upload-time = "2026-11-09T00:39:43.023Z" }, + { url = "https://files.pythonhosted.org/packages/9b/d0/498c4f67179885a4baf3b4500ea371d671180c20e136844065c239fe95d4/regex-2026.11.9-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:49eecd9b855cc9e683fed1b258d4e22dcb8e7b3c82f09c5778ce154359607f09", size = 874027, upload-time = "2026-11-09T00:39:44.36Z" }, + { url = "https://files.pythonhosted.org/packages/33/b9/61d474ad8aa93022edb00f13fcaac44678a5ef858801c804ad7d201d048b/regex-2026.11.9-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2405a0e564a5a1226427b21ee02a70c64f33a10015a18e480039c8ddb46b4f00", size = 915647, upload-time = "2026-11-09T00:39:45.587Z" }, + { url = "https://files.pythonhosted.org/packages/82/14/ec0c0f9e600f308280b901b46dd6e0095b56017fc2216b2abe6182009655/regex-2026.11.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0447593c5f4e2b88446da7466c83fc913ddf191600bbb7aebc6c8856595ccfb1", size = 805976, upload-time = "2026-11-09T00:39:47.654Z" }, + { url = "https://files.pythonhosted.org/packages/5e/de/bf7d2789051771e637d36aab03adea41b1e5729fe0c2a3d1df5e85a422bb/regex-2026.11.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:727989b08b98af7592eb86af12ca4227c017579094d5893a76fdd20b319cd8cd", size = 807143, upload-time = "2026-11-09T00:39:48.999Z" }, + { url = "https://files.pythonhosted.org/packages/0d/14/1a62ebd94dc36f74e2bb7f37bb7d7faf3bfc013cc90c1b1463d157e20136/regex-2026.11.9-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b886e1b7be6c392ea99d1c04de9b7adb4774038a1041514dfc6d0c5fb1bee6c5", size = 780582, upload-time = "2026-11-09T00:39:50.189Z" }, + { url = "https://files.pythonhosted.org/packages/3e/9b/42ce68062387ad6cbc4e2c5dc36d7f25d7a4d7621b5a67b8cd1a913ff2b4/regex-2026.11.9-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f1ec6903dc8054129ccc9404a5aaf19e4fab9af98b03604c69db903da3c045a4", size = 788733, upload-time = "2026-11-09T00:39:51.267Z" }, + { url = "https://files.pythonhosted.org/packages/ff/17/8e5268e78894c2a979a1599f9261eb0ede9952028d0a2689fbd80f2998b5/regex-2026.11.9-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:5c31a4e92c02f5c9e85c37a3851b9f83a36d2afdaaa88368f0d29ac56d8c81b8", size = 863625, upload-time = "2026-11-09T00:39:52.437Z" }, + { url = "https://files.pythonhosted.org/packages/97/0a/82e544ef361afc84e85a47907210bd9d1ef5c887b11ae3e091317c699327/regex-2026.11.9-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3dbccc60fa24fa1bab1cffe580c9bcd6467a885b6260d5e419f6d13db8c3596f", size = 766599, upload-time = "2026-11-09T00:39:54.03Z" }, + { url = "https://files.pythonhosted.org/packages/bf/4b/6484189c5f81e668059464780802b4bd6023415655c9410e8668a0a52a29/regex-2026.11.9-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:b5ce8fd914c9eaedfefa444ed329fc5a80c723136bda90e9e69159c536854c52", size = 855980, upload-time = "2026-11-09T00:39:55.184Z" }, + { url = "https://files.pythonhosted.org/packages/59/f8/954254f0c28b8113b304f0a9fec86274ad043b997161bb019ece9a00e5b8/regex-2026.11.9-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ff675c20d54564cb2b6c480c2e4b362dcc3ce74887ee2d2e63037658a0f01ab5", size = 793610, upload-time = "2026-11-09T00:39:56.351Z" }, + { url = "https://files.pythonhosted.org/packages/d9/2e/c30c186c8e0d55f4fa6cc882fb3f7eb3731ad70ffc5f99d40e99f261fadc/regex-2026.11.9-cp311-cp311-win32.whl", hash = "sha256:dd679c8172c94291ccee40e17b03b6e34c553ad855a57dc52e811c3bb83403f1", size = 269436, upload-time = "2026-11-09T00:39:57.808Z" }, + { url = "https://files.pythonhosted.org/packages/b5/6a/c23207465db6bb7a98211e82e5f79dc5473abea56464960f1c705bda888a/regex-2026.11.9-cp311-cp311-win_amd64.whl", hash = "sha256:b75ea29155c988eb375325a9fd9270a550ea3427acf275d350538c5f83571abc", size = 281159, upload-time = "2026-11-09T00:39:58.824Z" }, + { url = "https://files.pythonhosted.org/packages/df/7e/fe3c59e5adec098cddf9d65ed5f6543c070a344527a20d20e6731d4e57da/regex-2026.11.9-cp311-cp311-win_arm64.whl", hash = "sha256:b9c9746f25607eabe931c42f25535c9461589e25a80879a361f9c02f7abb6dce", size = 279986, upload-time = "2026-11-09T00:39:59.892Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "rouge" +version = "1.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/db/e4/3420a1ab1e82a280fb6107f7ae99e88eb12383c978fe573c0c64d0327d6b/rouge-1.0.1.tar.gz", hash = "sha256:12b48346ca47d6bcf3c45061f315452b9ccec0620ee895ec85b7efc3d54aae34", size = 14292, upload-time = "2021-07-20T08:45:56.53Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/7c/650ae86f92460e9e8ef969cc5008b24798dcf56a9a8947d04c78f550b3f5/rouge-1.0.1-py3-none-any.whl", hash = "sha256:28d118536e8c774dc47d1d15ec266479b4dd0914c4672ce117d4002789bdc644", size = 13725, upload-time = "2021-07-20T08:45:54.605Z" }, +] + +[[package]] +name = "safetensors" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/a0/f718cda65b05407d228f97602cf60dca269c979867aa5beb25410de26cd3/safetensors-0.8.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0", size = 473568, upload-time = "2026-06-09T07:52:18.829Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b1/fa7c600e7dceae12e9606c7578cbc9ff1e1ed55844883ee5c92205e86226/safetensors-0.8.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25", size = 484562, upload-time = "2026-06-09T07:52:17.518Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" }, + { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" }, + { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" }, + { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" }, + { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" }, + { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" }, + { url = "https://files.pythonhosted.org/packages/0d/49/1e15de264dcc3b77943d2d0c56a95809956883b1c2d6d585c792523f180b/safetensors-0.8.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca", size = 559930, upload-time = "2026-06-09T07:52:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" }, + { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" }, + { url = "https://files.pythonhosted.org/packages/29/4b/1c19c509d56e01f4fbb3d0a2e597450f6cc04d1d56cf52defb0a62dfd715/safetensors-0.8.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d", size = 765683, upload-time = "2026-06-09T07:52:22.594Z" }, + { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" }, + { url = "https://files.pythonhosted.org/packages/8e/3f/73ccf82579412b4a71c4ca673f10b5f1f888d7cf5af7fe24f27d30307be4/safetensors-0.8.0-cp310-abi3-win32.whl", hash = "sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d", size = 342401, upload-time = "2026-06-09T07:52:28.895Z" }, + { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" }, + { url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" }, +] + +[[package]] +name = "scikit-learn" +version = "1.7.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "joblib" }, + { name = "numpy" }, + { name = "scipy" }, + { name = "threadpoolctl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/c2/a7855e41c9d285dfe86dc50b250978105dce513d6e459ea66a6aeb0e1e0c/scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda", size = 7193136, upload-time = "2025-09-09T08:21:29.075Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/83/564e141eef908a5863a54da8ca342a137f45a0bfb71d1d79704c9894c9d1/scikit_learn-1.7.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c7509693451651cd7361d30ce4e86a1347493554f172b1c72a39300fa2aea79e", size = 9331967, upload-time = "2025-09-09T08:20:32.421Z" }, + { url = "https://files.pythonhosted.org/packages/18/d6/ba863a4171ac9d7314c4d3fc251f015704a2caeee41ced89f321c049ed83/scikit_learn-1.7.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:0486c8f827c2e7b64837c731c8feff72c0bd2b998067a8a9cbc10643c31f0fe1", size = 8648645, upload-time = "2025-09-09T08:20:34.436Z" }, + { url = "https://files.pythonhosted.org/packages/ef/0e/97dbca66347b8cf0ea8b529e6bb9367e337ba2e8be0ef5c1a545232abfde/scikit_learn-1.7.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:89877e19a80c7b11a2891a27c21c4894fb18e2c2e077815bcade10d34287b20d", size = 9715424, upload-time = "2025-09-09T08:20:36.776Z" }, + { url = "https://files.pythonhosted.org/packages/f7/32/1f3b22e3207e1d2c883a7e09abb956362e7d1bd2f14458c7de258a26ac15/scikit_learn-1.7.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8da8bf89d4d79aaec192d2bda62f9b56ae4e5b4ef93b6a56b5de4977e375c1f1", size = 9509234, upload-time = "2025-09-09T08:20:38.957Z" }, + { url = "https://files.pythonhosted.org/packages/9f/71/34ddbd21f1da67c7a768146968b4d0220ee6831e4bcbad3e03dd3eae88b6/scikit_learn-1.7.2-cp311-cp311-win_amd64.whl", hash = "sha256:9b7ed8d58725030568523e937c43e56bc01cadb478fc43c042a9aca1dacb3ba1", size = 8894244, upload-time = "2025-09-09T08:20:41.166Z" }, +] + +[[package]] +name = "scipy" +version = "1.17.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/75/b4ce781849931fef6fd529afa6b63711d5a733065722d0c3e2724af9e40a/scipy-1.17.1-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1f95b894f13729334fb990162e911c9e5dc1ab390c58aa6cbecb389c5b5e28ec", size = 31613675, upload-time = "2026-02-23T00:16:00.13Z" }, + { url = "https://files.pythonhosted.org/packages/f7/58/bccc2861b305abdd1b8663d6130c0b3d7cc22e8d86663edbc8401bfd40d4/scipy-1.17.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:e18f12c6b0bc5a592ed23d3f7b891f68fd7f8241d69b7883769eb5d5dfb52696", size = 28162057, upload-time = "2026-02-23T00:16:09.456Z" }, + { url = "https://files.pythonhosted.org/packages/6d/ee/18146b7757ed4976276b9c9819108adbc73c5aad636e5353e20746b73069/scipy-1.17.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:a3472cfbca0a54177d0faa68f697d8ba4c80bbdc19908c3465556d9f7efce9ee", size = 20334032, upload-time = "2026-02-23T00:16:17.358Z" }, + { url = "https://files.pythonhosted.org/packages/ec/e6/cef1cf3557f0c54954198554a10016b6a03b2ec9e22a4e1df734936bd99c/scipy-1.17.1-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:766e0dc5a616d026a3a1cffa379af959671729083882f50307e18175797b3dfd", size = 22709533, upload-time = "2026-02-23T00:16:25.791Z" }, + { url = "https://files.pythonhosted.org/packages/4d/60/8804678875fc59362b0fb759ab3ecce1f09c10a735680318ac30da8cd76b/scipy-1.17.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:744b2bf3640d907b79f3fd7874efe432d1cf171ee721243e350f55234b4cec4c", size = 33062057, upload-time = "2026-02-23T00:16:36.931Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/af933f0f6e0767995b4e2d705a0665e454d1c19402aa7e895de3951ebb04/scipy-1.17.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43af8d1f3bea642559019edfe64e9b11192a8978efbd1539d7bc2aaa23d92de4", size = 35349300, upload-time = "2026-02-23T00:16:49.108Z" }, + { url = "https://files.pythonhosted.org/packages/b4/3d/7ccbbdcbb54c8fdc20d3b6930137c782a163fa626f0aef920349873421ba/scipy-1.17.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:cd96a1898c0a47be4520327e01f874acfd61fb48a9420f8aa9f6483412ffa444", size = 35127333, upload-time = "2026-02-23T00:17:01.293Z" }, + { url = "https://files.pythonhosted.org/packages/e8/19/f926cb11c42b15ba08e3a71e376d816ac08614f769b4f47e06c3580c836a/scipy-1.17.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4eb6c25dd62ee8d5edf68a8e1c171dd71c292fdae95d8aeb3dd7d7de4c364082", size = 37741314, upload-time = "2026-02-23T00:17:12.576Z" }, + { url = "https://files.pythonhosted.org/packages/95/da/0d1df507cf574b3f224ccc3d45244c9a1d732c81dcb26b1e8a766ae271a8/scipy-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:d30e57c72013c2a4fe441c2fcb8e77b14e152ad48b5464858e07e2ad9fbfceff", size = 36607512, upload-time = "2026-02-23T00:17:23.424Z" }, + { url = "https://files.pythonhosted.org/packages/68/7f/bdd79ceaad24b671543ffe0ef61ed8e659440eb683b66f033454dcee90eb/scipy-1.17.1-cp311-cp311-win_arm64.whl", hash = "sha256:9ecb4efb1cd6e8c4afea0daa91a87fbddbce1b99d2895d151596716c0b2e859d", size = 24599248, upload-time = "2026-02-23T00:17:34.561Z" }, +] + +[[package]] +name = "sentencepiece" +version = "0.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/15/15/2e7a025fc62d764b151ae6d0f2a92f8081755ebe8d4a64099accc6f77ba6/sentencepiece-0.2.1.tar.gz", hash = "sha256:8138cec27c2f2282f4a34d9a016e3374cd40e5c6e9cb335063db66a0a3b71fad", size = 3228515, upload-time = "2025-08-12T07:00:51.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d8/15/46afbab00733d81788b64be430ca1b93011bb9388527958e26cc31832de5/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6356d0986b8b8dc351b943150fcd81a1c6e6e4d439772e8584c64230e58ca987", size = 1942560, upload-time = "2025-08-12T06:59:25.82Z" }, + { url = "https://files.pythonhosted.org/packages/fa/79/7c01b8ef98a0567e9d84a4e7a910f8e7074fcbf398a5cd76f93f4b9316f9/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8f8ba89a3acb3dc1ae90f65ec1894b0b9596fdb98ab003ff38e058f898b39bc7", size = 1325385, upload-time = "2025-08-12T06:59:27.722Z" }, + { url = "https://files.pythonhosted.org/packages/bb/88/2b41e07bd24f33dcf2f18ec3b74247aa4af3526bad8907b8727ea3caba03/sentencepiece-0.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:02593eca45440ef39247cee8c47322a34bdcc1d8ae83ad28ba5a899a2cf8d79a", size = 1253319, upload-time = "2025-08-12T06:59:29.306Z" }, + { url = "https://files.pythonhosted.org/packages/a0/54/38a1af0c6210a3c6f95aa46d23d6640636d020fba7135cd0d9a84ada05a7/sentencepiece-0.2.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a0d15781a171d188b661ae4bde1d998c303f6bd8621498c50c671bd45a4798e", size = 1316162, upload-time = "2025-08-12T06:59:30.914Z" }, + { url = "https://files.pythonhosted.org/packages/ef/66/fb191403ade791ad2c3c1e72fe8413e63781b08cfa3aa4c9dfc536d6e795/sentencepiece-0.2.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4f5a3e0d9f445ed9d66c0fec47d4b23d12cfc858b407a03c194c1b26c2ac2a63", size = 1387785, upload-time = "2025-08-12T06:59:32.491Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/3bd9b08e70067b2124518b308db6a84a4f8901cc8a4317e2e4288cdd9b4d/sentencepiece-0.2.1-cp311-cp311-win32.whl", hash = "sha256:6d297a1748d429ba8534eebe5535448d78b8acc32d00a29b49acf28102eeb094", size = 999555, upload-time = "2025-08-12T06:59:34.475Z" }, + { url = "https://files.pythonhosted.org/packages/32/b8/f709977f5fda195ae1ea24f24e7c581163b6f142b1005bc3d0bbfe4d7082/sentencepiece-0.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:82d9ead6591015f009cb1be1cb1c015d5e6f04046dbb8c9588b931e869a29728", size = 1054617, upload-time = "2025-08-12T06:59:36.461Z" }, + { url = "https://files.pythonhosted.org/packages/7a/40/a1fc23be23067da0f703709797b464e8a30a1c78cc8a687120cd58d4d509/sentencepiece-0.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:39f8651bd10974eafb9834ce30d9bcf5b73e1fc798a7f7d2528f9820ca86e119", size = 1033877, upload-time = "2025-08-12T06:59:38.391Z" }, +] + +[[package]] +name = "sentry-sdk" +version = "2.74.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8e/7f/1b16ab4aee53cc5db976bac12e6df5d562aae3880965200cef812e7121d9/sentry_sdk-2.74.0.tar.gz", hash = "sha256:dd91d75aacaef636006b579ac3ddb2fdbc9dce35f00f4b353b6b1b110c6b256a", size = 1081514, upload-time = "2026-11-05T14:50:27.444Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/55/b1/736d4b4b308694b0071844a533522ac06669ad61751687b94edfbf863f17/sentry_sdk-2.74.0-py3-none-any.whl", hash = "sha256:40b205af015649df3ec9986e057ce24ce85956bee3fb75efa72c93aa7036bdff", size = 549800, upload-time = "2026-11-05T14:50:25.767Z" }, +] + +[[package]] +name = "setuptools" +version = "80.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/5d/3bf57dcd21979b887f014ea83c24ae194cfcd12b9e0fda66b957c69d1fca/setuptools-80.9.0.tar.gz", hash = "sha256:f36b47402ecde768dbfafc46e8e4207b4360c654f1f3bb84475f0a28628fb19c", size = 1319958, upload-time = "2025-05-27T00:56:51.443Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922", size = 1201486, upload-time = "2025-05-27T00:56:49.664Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "smmap" +version = "5.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/ea/49c993d6dfdd7338c9b1000a0f36817ed7ec84577ae2e52f890d1a4ff909/smmap-5.0.3.tar.gz", hash = "sha256:4d9debb8b99007ae47165abc08670bd74cb74b5227dda7f643eccc4e9eb5642c", size = 22506, upload-time = "2026-03-09T03:43:26.1Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/d4/59e74daffcb57a07668852eeeb6035af9f32cbfd7a1d2511f17d2fe6a738/smmap-5.0.3-py3-none-any.whl", hash = "sha256:c106e05d5a61449cf6ba9a1e650227ecfb141590d2a98412103ff35d89fc7b2f", size = 24390, upload-time = "2026-03-09T03:43:24.361Z" }, +] + +[[package]] +name = "sympy" +version = "1.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mpmath" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, +] + +[[package]] +name = "threadpoolctl" +version = "3.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/56/97/b4748951a683e369513691c8eea33d100298d556308dcb0ab66b132a67f0/threadpoolctl-3.8.0.tar.gz", hash = "sha256:01080674ad7ac6182429c918a79de92da789bb448acc02fc0b620b1abd6b6137", size = 39424, upload-time = "2026-11-05T11:08:51.112Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/1b/831f2de4840a25db1dd7b1afea433ccafe6bb10aca07e13264f2079462d0/threadpoolctl-3.8.0-py3-none-any.whl", hash = "sha256:f1b49c82704d50f13ffae019c727b0fa4f6791a58f48f06a09c45face1be66da", size = 32091, upload-time = "2026-11-05T11:08:49.773Z" }, +] + +[[package]] +name = "tokenizers" +version = "0.13.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/29/9c/936ebad6dd963616189d6362f4c2c03a0314cf2a221ba15e48dd714d29cf/tokenizers-0.13.3.tar.gz", hash = "sha256:2e546dbb68b623008a5442353137fbb0123d311a6d7ba52f2667c8862a75af2e", size = 314856, upload-time = "2023-04-05T08:16:06.94Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7a/fe/003cb6ed585f1879d0eb5bedf80c0261efc351885027dffefbd86202d463/tokenizers-0.13.3-cp311-cp311-macosx_10_11_universal2.whl", hash = "sha256:56b726e0d2bbc9243872b0144515ba684af5b8d8cd112fb83ee1365e26ec74c8", size = 3975604, upload-time = "2023-04-05T08:15:33.475Z" }, + { url = "https://files.pythonhosted.org/packages/0c/e0/f51b2d52fcc2c64e0b81da0a1c68d57b3859212143dbc64b0d175ed78693/tokenizers-0.13.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:cc5c022ce692e1f499d745af293ab9ee6f5d92538ed2faf73f9708c89ee59ce6", size = 3896389, upload-time = "2023-04-05T08:15:34.885Z" }, + { url = "https://files.pythonhosted.org/packages/09/6c/68f532b76033b7ef745777955ad0645069baa80cc0e47363432817323c53/tokenizers-0.13.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f55c981ac44ba87c93e847c333e58c12abcbb377a0c2f2ef96e1a266e4184ff2", size = 7450422, upload-time = "2023-04-05T10:13:20.375Z" }, + { url = "https://files.pythonhosted.org/packages/a6/cb/5ea65756be1cd97582fa0d3e466d20e041cf7e21ae47e5032a2b0c8a86db/tokenizers-0.13.3-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f247eae99800ef821a91f47c5280e9e9afaeed9980fc444208d5aa6ba69ff148", size = 8606313, upload-time = "2023-04-05T10:13:22.974Z" }, + { url = "https://files.pythonhosted.org/packages/92/85/74b09728fc3a34991595b103fb5d2c00801e2106f57b4306a4beab39354d/tokenizers-0.13.3-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4b3e3215d048e94f40f1c95802e45dcc37c5b05eb46280fc2ccc8cd351bff839", size = 8204210, upload-time = "2023-04-05T10:13:25.001Z" }, + { url = "https://files.pythonhosted.org/packages/e9/d9/660f08ecd88bed54df9f85cab44e01184733c8e42d79b583fb985f1dc412/tokenizers-0.13.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9ba2b0bf01777c9b9bc94b53764d6684554ce98551fec496f71bc5be3a03e98b", size = 7778045, upload-time = "2023-04-05T08:15:37.039Z" }, + { url = "https://files.pythonhosted.org/packages/85/6d/5401879fc61526a48c20576ea85b8c6acfc0a67afdec18353522380e2e44/tokenizers-0.13.3-cp311-cp311-win32.whl", hash = "sha256:cc78d77f597d1c458bf0ea7c2a64b6aa06941c7a99cb135b5969b0278824d808", size = 3211955, upload-time = "2023-04-05T08:15:38.604Z" }, + { url = "https://files.pythonhosted.org/packages/62/41/93d3135ec30f596a71490ce11a73572190fe80e85a2aea18f116a520cc41/tokenizers-0.13.3-cp311-cp311-win_amd64.whl", hash = "sha256:ecf182bf59bd541a8876deccf0360f5ae60496fd50b58510048020751cf1724c", size = 3469503, upload-time = "2023-04-05T08:15:40.169Z" }, +] + +[[package]] +name = "tokenizers" +version = "0.22.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "huggingface-hub" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/97/5dbfabf04c7e348e655e907ed27913e03db0923abb5dfdd120d7b25630e1/tokenizers-0.22.2-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:544dd704ae7238755d790de45ba8da072e9af3eea688f698b137915ae959281c", size = 3100275, upload-time = "2026-01-05T10:41:02.158Z" }, + { url = "https://files.pythonhosted.org/packages/2e/47/174dca0502ef88b28f1c9e06b73ce33500eedfac7a7692108aec220464e7/tokenizers-0.22.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:1e418a55456beedca4621dbab65a318981467a2b188e982a23e117f115ce5001", size = 2981472, upload-time = "2026-01-05T10:41:00.276Z" }, + { url = "https://files.pythonhosted.org/packages/d6/84/7990e799f1309a8b87af6b948f31edaa12a3ed22d11b352eaf4f4b2e5753/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2249487018adec45d6e3554c71d46eb39fa8ea67156c640f7513eb26f318cec7", size = 3290736, upload-time = "2026-01-05T10:40:32.165Z" }, + { url = "https://files.pythonhosted.org/packages/78/59/09d0d9ba94dcd5f4f1368d4858d24546b4bdc0231c2354aa31d6199f0399/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:25b85325d0815e86e0bac263506dd114578953b7b53d7de09a6485e4a160a7dd", size = 3168835, upload-time = "2026-01-05T10:40:38.847Z" }, + { url = "https://files.pythonhosted.org/packages/47/50/b3ebb4243e7160bda8d34b731e54dd8ab8b133e50775872e7a434e524c28/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bfb88f22a209ff7b40a576d5324bf8286b519d7358663db21d6246fb17eea2d5", size = 3521673, upload-time = "2026-01-05T10:40:56.614Z" }, + { url = "https://files.pythonhosted.org/packages/e0/fa/89f4cb9e08df770b57adb96f8cbb7e22695a4cb6c2bd5f0c4f0ebcf33b66/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1c774b1276f71e1ef716e5486f21e76333464f47bece56bbd554485982a9e03e", size = 3724818, upload-time = "2026-01-05T10:40:44.507Z" }, + { url = "https://files.pythonhosted.org/packages/64/04/ca2363f0bfbe3b3d36e95bf67e56a4c88c8e3362b658e616d1ac185d47f2/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:df6c4265b289083bf710dff49bc51ef252f9d5be33a45ee2bed151114a56207b", size = 3379195, upload-time = "2026-01-05T10:40:51.139Z" }, + { url = "https://files.pythonhosted.org/packages/2e/76/932be4b50ef6ccedf9d3c6639b056a967a86258c6d9200643f01269211ca/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:369cc9fc8cc10cb24143873a0d95438bb8ee257bb80c71989e3ee290e8d72c67", size = 3274982, upload-time = "2026-01-05T10:40:58.331Z" }, + { url = "https://files.pythonhosted.org/packages/1d/28/5f9f5a4cc211b69e89420980e483831bcc29dade307955cc9dc858a40f01/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:29c30b83d8dcd061078b05ae0cb94d3c710555fbb44861139f9f83dcca3dc3e4", size = 9478245, upload-time = "2026-01-05T10:41:04.053Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fb/66e2da4704d6aadebf8cb39f1d6d1957df667ab24cff2326b77cda0dcb85/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:37ae80a28c1d3265bb1f22464c856bd23c02a05bb211e56d0c5301a435be6c1a", size = 9560069, upload-time = "2026-01-05T10:45:10.673Z" }, + { url = "https://files.pythonhosted.org/packages/16/04/fed398b05caa87ce9b1a1bb5166645e38196081b225059a6edaff6440fac/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:791135ee325f2336f498590eb2f11dc5c295232f288e75c99a36c5dbce63088a", size = 9899263, upload-time = "2026-01-05T10:45:12.559Z" }, + { url = "https://files.pythonhosted.org/packages/05/a1/d62dfe7376beaaf1394917e0f8e93ee5f67fea8fcf4107501db35996586b/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38337540fbbddff8e999d59970f3c6f35a82de10053206a7562f1ea02d046fa5", size = 10033429, upload-time = "2026-01-05T10:45:14.333Z" }, + { url = "https://files.pythonhosted.org/packages/fd/18/a545c4ea42af3df6effd7d13d250ba77a0a86fb20393143bbb9a92e434d4/tokenizers-0.22.2-cp39-abi3-win32.whl", hash = "sha256:a6bf3f88c554a2b653af81f3204491c818ae2ac6fbc09e76ef4773351292bc92", size = 2502363, upload-time = "2026-01-05T10:45:20.593Z" }, + { url = "https://files.pythonhosted.org/packages/65/71/0670843133a43d43070abeb1949abfdef12a86d490bea9cd9e18e37c5ff7/tokenizers-0.22.2-cp39-abi3-win_amd64.whl", hash = "sha256:c9ea31edff2968b44a88f97d784c2f16dc0729b8b143ed004699ebca91f05c48", size = 2747786, upload-time = "2026-01-05T10:45:18.411Z" }, + { url = "https://files.pythonhosted.org/packages/72/f4/0de46cfa12cdcbcd464cc59fde36912af405696f687e53a091fb432f694c/tokenizers-0.22.2-cp39-abi3-win_arm64.whl", hash = "sha256:9ce725d22864a1e965217204946f830c37876eee3b2ba6fc6255e8e903d5fcbc", size = 2612133, upload-time = "2026-01-05T10:45:17.232Z" }, +] + +[[package]] +name = "torch" +version = "2.13.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-bindings", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "nvidia-nvshmem-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "triton", marker = "sys_platform == 'linux' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, + { name = "typing-extensions" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/fe/cba54dc58523434919b66f13a667e36e436deddd77ca519e96553617d4ec/torch-2.13.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:e76f9bcecc52b8ff711239a2f7547d5353df95878ab232f0773c1d95928b92f8", size = 111187938, upload-time = "2026-07-08T16:05:17.065Z" }, + { url = "https://files.pythonhosted.org/packages/c2/59/1e3160e18e12aa3038390efab3ce02b36a9d4d6a527ecdd8520dca2e68d8/torch-2.13.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:092790c696a760c729fd5722835f50b9d81fd7c8f141571f3f3cf4081a8f664c", size = 427199369, upload-time = "2026-07-08T16:04:51.054Z" }, + { url = "https://files.pythonhosted.org/packages/01/79/1f2d34ad7034ee1c7ffc1cf8bf0f8213af2a81df6ecdb3997ecec107c09d/torch-2.13.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:60fcdcb2f3876e21146cb4524ef06397d727ca9ad5f020818547e25075fe3cb7", size = 526574961, upload-time = "2026-07-08T16:04:07.075Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fd/0f2ce40f58aefbdb3392f9acce3c8171940943ae2d661f70558bfa73befb/torch-2.13.0-cp311-cp311-win_amd64.whl", hash = "sha256:a0d8b11f16a48d60e2015d8213aa0390744cbebb98e58b62b3514dddc656e330", size = 122015870, upload-time = "2026-07-08T16:05:27.59Z" }, +] + +[[package]] +name = "tqdm" +version = "4.70.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'group-24-official-lozo-experiment-modern' and extra == 'group-24-official-lozo-experiment-native')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0d/ea/b2a5bd54b28a324dae8211928b2d730b6547500342c7e6c6dea08bd0a485/tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4", size = 171846, upload-time = "2026-09-11T07:25:16.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" }, +] + +[[package]] +name = "transformers" +version = "4.28.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "filelock" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "requests" }, + { name = "tokenizers", version = "0.13.3", source = { registry = "https://pypi.org/simple" } }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0d/9f/0d27dec00839c14866d03c9992542d31992ef94d496765789234c9593e94/transformers-4.28.1.tar.gz", hash = "sha256:7334f8730cff7ac31d9ba5c12f2113fcb7a7a5b61eeb5dbbdb162117c3aaa2d1", size = 6007419, upload-time = "2023-04-14T16:55:55.624Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d8/a7/a6ff727fd5d96d6625f4658944a2ae230f0c75743a9a117fbda013b03d3d/transformers-4.28.1-py3-none-any.whl", hash = "sha256:f30a006220d0475789ac0e7c874f51bf5143956797616d89975b637883ce0be6", size = 6952278, upload-time = "2023-04-14T16:55:50.932Z" }, +] + +[[package]] +name = "transformers" +version = "4.57.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "filelock" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "requests" }, + { name = "safetensors" }, + { name = "tokenizers", version = "0.22.2", source = { registry = "https://pypi.org/simple" } }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/68/a39307bcc4116a30b2106f2e689130a48de8bd8a1e635b5e1030e46fcd9e/transformers-4.57.1.tar.gz", hash = "sha256:f06c837959196c75039809636cd964b959f6604b75b8eeec6fdfc0440b89cc55", size = 10142511, upload-time = "2025-10-14T15:39:26.18Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/d3/c16c3b3cf7655a67db1144da94b021c200ac1303f82428f2beef6c2e72bb/transformers-4.57.1-py3-none-any.whl", hash = "sha256:b10d05da8fa67dc41644dbbf9bc45a44cb86ae33da6f9295f5fbf5b7890bd267", size = 11990925, upload-time = "2025-10-14T15:39:23.085Z" }, +] + +[[package]] +name = "triton" +version = "3.7.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/f9/19d842d06a08559534fa1eaab6ca551b1bcf40f06620bddec1babaa2772d/triton-3.7.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4a0e1cd4c4a76370ed74a8432a53cea28716827d19e40ffc732233e35ceb3f6", size = 184664887, upload-time = "2026-06-17T20:03:42.913Z" }, + { url = "https://files.pythonhosted.org/packages/cd/5e/fce69606f7f240297f163e25539906732b199530d486ce67ae319877e821/triton-3.7.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6744957e9fd610a29680ec2346057d0c86948ed3812468670719f391e94b44a5", size = 197701306, upload-time = "2026-06-17T19:53:13.673Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ff/50/0195198eb1d75bab716bb0a813abea4cc394bfa17a92a189f021a34859af/typing_inspection-0.4.5.tar.gz", hash = "sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7", size = 81194, upload-time = "2026-11-04T14:13:23.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" }, +] + +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + +[[package]] +name = "wandb" +version = "0.23.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "gitpython" }, + { name = "packaging" }, + { name = "platformdirs" }, + { name = "protobuf" }, + { name = "pydantic" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "sentry-sdk" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0a/cc/770ae3aa7ae44f6792f7ecb81c14c0e38b672deb35235719bb1006519487/wandb-0.23.1.tar.gz", hash = "sha256:f6fb1e3717949b29675a69359de0eeb01e67d3360d581947d5b3f98c273567d6", size = 44298053, upload-time = "2025-12-03T02:25:10.79Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/0b/c3d7053dfd93fd259a63c7818d9c4ac2ba0642ff8dc8db98662ea0cf9cc0/wandb-0.23.1-py3-none-macosx_12_0_arm64.whl", hash = "sha256:358e15471d19b7d73fc464e37371c19d44d39e433252ac24df107aff993a286b", size = 21527293, upload-time = "2025-12-03T02:24:48.011Z" }, + { url = "https://files.pythonhosted.org/packages/ee/9f/059420fa0cb6c511dc5c5a50184122b6aca7b178cb2aa210139e354020da/wandb-0.23.1-py3-none-macosx_12_0_x86_64.whl", hash = "sha256:110304407f4b38f163bdd50ed5c5225365e4df3092f13089c30171a75257b575", size = 22745926, upload-time = "2025-12-03T02:24:50.519Z" }, + { url = "https://files.pythonhosted.org/packages/96/b6/fd465827c14c64d056d30b4c9fcf4dac889a6969dba64489a88fc4ffa333/wandb-0.23.1-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:6cc984cf85feb2f8ee0451d76bc9fb7f39da94956bb8183e30d26284cf203b65", size = 21212973, upload-time = "2025-12-03T02:24:52.828Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/9a8bb9a39cc1f09c3060456cc79565110226dc4099a719af5c63432da21d/wandb-0.23.1-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:67431cd3168d79fdb803e503bd669c577872ffd5dadfa86de733b3274b93088e", size = 22887885, upload-time = "2025-12-03T02:24:55.281Z" }, + { url = "https://files.pythonhosted.org/packages/6d/4d/8d9e75add529142e037b05819cb3ab1005679272950128d69d218b7e5b2e/wandb-0.23.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:07be70c0baa97ea25fadc4a9d0097f7371eef6dcacc5ceb525c82491a31e9244", size = 21250967, upload-time = "2025-12-03T02:24:57.603Z" }, + { url = "https://files.pythonhosted.org/packages/97/72/0b35cddc4e4168f03c759b96d9f671ad18aec8bdfdd84adfea7ecb3f5701/wandb-0.23.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:216c95b08e0a2ec6a6008373b056d597573d565e30b43a7a93c35a171485ee26", size = 22988382, upload-time = "2025-12-03T02:25:00.518Z" }, + { url = "https://files.pythonhosted.org/packages/c0/6d/e78093d49d68afb26f5261a70fc7877c34c114af5c2ee0ab3b1af85f5e76/wandb-0.23.1-py3-none-win32.whl", hash = "sha256:fb5cf0f85692f758a5c36ab65fea96a1284126de64e836610f92ddbb26df5ded", size = 22150756, upload-time = "2025-12-03T02:25:02.734Z" }, + { url = "https://files.pythonhosted.org/packages/05/27/4f13454b44c9eceaac3d6e4e4efa2230b6712d613ff9bf7df010eef4fd18/wandb-0.23.1-py3-none-win_amd64.whl", hash = "sha256:21c8c56e436eb707b7d54f705652e030d48e5cfcba24cf953823eb652e30e714", size = 22150760, upload-time = "2025-12-03T02:25:05.106Z" }, + { url = "https://files.pythonhosted.org/packages/30/20/6c091d451e2a07689bfbfaeb7592d488011420e721de170884fedd68c644/wandb-0.23.1-py3-none-win_arm64.whl", hash = "sha256:8aee7f3bb573f2c0acf860f497ca9c684f9b35f2ca51011ba65af3d4592b77c1", size = 20137463, upload-time = "2025-12-03T02:25:08.317Z" }, +] + +[[package]] +name = "xxhash" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c9/b5/3d11d3830ace56d67ea83136c24385c3b07da5a9bc62b73b0b94ac096da3/xxhash-4.1.0.tar.gz", hash = "sha256:c9b288e4c1f5dae54417bc8a05e6f6daf505783d916b4783f4dd2f2e7d5db486", size = 114122, upload-time = "2026-11-09T13:47:33.276Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/cb/da501f3abc32f8c3a6f0fb24f1988ec6b862897034a6f44bff92e06b6f29/xxhash-4.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cf3e28ee18b17d253d85c0a0b3608b9b54f765df4af207722c1ce851f386a26d", size = 51515, upload-time = "2026-11-09T13:46:45.912Z" }, + { url = "https://files.pythonhosted.org/packages/5c/1d/112856c31d49a814854f19b3ecf8d81196a5b2d0c8cccbbe5a0cfe571e86/xxhash-4.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:796b8e5212ba90ebc8afac5ae3615502acd0d65363730cccd1d629b0fe7e87f6", size = 36825, upload-time = "2026-11-09T13:46:48.399Z" }, + { url = "https://files.pythonhosted.org/packages/40/37/fb258a692f0ecd93ff3af8f77a0122db1e33853f6c6c433cb841f46da13f/xxhash-4.1.0-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:822f6aa36f336f65188ae987b9627e843b6963f749d8a2a187f5b6fd72715088", size = 448119, upload-time = "2026-11-09T13:46:48.427Z" }, + { url = "https://files.pythonhosted.org/packages/2f/be/4e9efad09e3152cd437a6ad46148a9fe992f9bdfc1117808e71bc02178c4/xxhash-4.1.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f948b71013e0a0922176563dd4538967e2d7717b845bd61e0407f2e410962050", size = 274457, upload-time = "2026-11-09T13:46:46.078Z" }, + { url = "https://files.pythonhosted.org/packages/3a/11/177b6b4a781ae0a38e2d335b2a6bfe4e70c3e8edace541b1615da408d4ef/xxhash-4.1.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3fbf446e75b80f2a605b4b1637cb5bfdad5c317bc54ecd91ac7cb9e28314fe4b", size = 296295, upload-time = "2026-11-09T13:46:48.728Z" }, + { url = "https://files.pythonhosted.org/packages/30/d7/d59d72875eb268e83743ce507de3ce983a611e18c79d4d4169500932a747/xxhash-4.1.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:586ce49f8d73dc214f9da8e87824f332f2b4ddb7d15534736a2f906373b2030d", size = 273599, upload-time = "2026-11-09T13:46:49.98Z" }, + { url = "https://files.pythonhosted.org/packages/10/8a/3c85277e544cae7f6fa1dad71e23485b21d5695d3ac69a10ea46d3257896/xxhash-4.1.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b6b09351f73f6d0a3df59b02b9d2154a66fcc716fae8f0b8b2bdd63c42a1d2f6", size = 506958, upload-time = "2026-11-09T13:46:47.172Z" }, + { url = "https://files.pythonhosted.org/packages/b6/4f/5b195a79fafb6e9ab8e95229cc5346572a6cc40d6d6ed9227183a25315ea/xxhash-4.1.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e713f5db9e1a8aafac59a45cc1ffce11ca507730f5dc12e212ea7b73d9debde", size = 471448, upload-time = "2026-11-09T13:46:47.314Z" }, + { url = "https://files.pythonhosted.org/packages/d8/6d/c34662fae63220b90d6803dab8fdc9240cf6cef06fbdea73fef0750ff438/xxhash-4.1.0-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:eadb2724470fd9507cb8f864c969d761dac7d549223ff15ff998c1c3c8e134d5", size = 337233, upload-time = "2026-11-09T13:46:49.72Z" }, + { url = "https://files.pythonhosted.org/packages/86/f7/7def1a3b835ef30b8f1a192405dd99db448922aeda8f45eb0359f00613c0/xxhash-4.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0119cf9ae630c5365596dd9dccf29932f364e8ef0f9162e1d7ef9df3e15ccb8e", size = 270274, upload-time = "2026-11-09T13:46:50.189Z" }, + { url = "https://files.pythonhosted.org/packages/bf/fb/677fef1a69b67c62eb12f71b7f49f801db1191df2f336d2930608f61c9f4/xxhash-4.1.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:3f580ff0d8dec8b495c6c6b281a89be3913158b01937281006993168b4375f84", size = 297452, upload-time = "2026-11-09T13:46:47.438Z" }, + { url = "https://files.pythonhosted.org/packages/95/15/5017ecacab16636c244e2cbd014cc56e17528caa736abcea4e151102e514/xxhash-4.1.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6179c5e008d2f1ca3a2e9c7935c021f84c5dc7516dfe5c9ee3edc0e9f26d20f0", size = 442167, upload-time = "2026-11-09T13:46:50.278Z" }, + { url = "https://files.pythonhosted.org/packages/45/0d/29c13f74ac43011aaafff9d9b23effefdf9243fcce764fed17087b1bd12c/xxhash-4.1.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:bdeaa333f8fbc237c5e62e0fb70e694dbfde62d15e242be23ba491ecd706e520", size = 271153, upload-time = "2026-11-09T13:46:51.737Z" }, + { url = "https://files.pythonhosted.org/packages/ef/89/d01eedb87d3ef1f7ec81080a160acd7ba42f29a43706b36d7fb4a8192706/xxhash-4.1.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:7c6bcd4eeeb5411a176b1a63dc505de99cd6182e88b02722d4407f96cf082e62", size = 327241, upload-time = "2026-11-09T13:46:48.482Z" }, + { url = "https://files.pythonhosted.org/packages/69/6a/82eb13aff0e06861cf2ff7a5b4e91092a3e7f7da5442c8be19e4c876d1a4/xxhash-4.1.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9f200a2bc05bade88e7c50c28d2a6637468ff0bacbcf1720928ae55b905bb1af", size = 474740, upload-time = "2026-11-09T13:46:48.76Z" }, + { url = "https://files.pythonhosted.org/packages/64/eb/0859f45d7b690f44704f3d8dc9a6a00eea931bcb0f3c5f5da7799a8740bb/xxhash-4.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e8b54cf9df8802572be9b8af0e3c1bc9eae80f653cd16f97d340a0098c48bb9c", size = 453590, upload-time = "2026-11-09T13:46:51.495Z" }, + { url = "https://files.pythonhosted.org/packages/18/99/e74773a5bc7b8decc874f0c74fb13e2058259101c6f54f87ecf07709e030/xxhash-4.1.0-cp311-cp311-win32.whl", hash = "sha256:b0042c684cf5739352d47afa77d387300805773a756f3677c1113481015934d6", size = 45112, upload-time = "2026-11-09T13:46:51.691Z" }, + { url = "https://files.pythonhosted.org/packages/5d/5f/299d6c8733add97f1b3e25f102dc473cd25b7ca147e6a828ec560c9740f2/xxhash-4.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:306a5538aa1152a3c411ebcce31a824721159495f391290ddcfa5b3f07c051a5", size = 48163, upload-time = "2026-11-09T13:46:48.804Z" }, + { url = "https://files.pythonhosted.org/packages/49/ee/e6d087e0fb37800c84ad842a4f6989ae3bc24964b63440fef1c89ec7f0e9/xxhash-4.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:bf3ebcbed4efff1ec177385e4b906c8ba75881d975ea59f49aa6edc2d37752aa", size = 33410, upload-time = "2026-11-09T13:46:51.735Z" }, + { url = "https://files.pythonhosted.org/packages/c0/41/89fa8c4f2d1190f8a9efca46f5779bdb4481356aec35119529e1ba91d35c/xxhash-4.1.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:d7a55bb01f866f948a4439e325e3e92645d97ca22c43777d2a71e7e51b63a986", size = 47341, upload-time = "2026-11-09T13:49:04.925Z" }, + { url = "https://files.pythonhosted.org/packages/93/5c/aa12a2f255cceb0941fa706d802bd502f64d42a76f17ea68ad62d860499b/xxhash-4.1.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:50e76857c8c47d8feb48ff1de711eaccfc5d28d97a5b1f7bd449b20796ecbf2b", size = 33938, upload-time = "2026-11-09T13:47:34.712Z" }, + { url = "https://files.pythonhosted.org/packages/c8/d1/d009e49747f1344c5c6fce52d67dfd53dfd0a0e75c4525abfc1dac44380b/xxhash-4.1.0-pp311-pypy311_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:49471b564ebae5d664daae4ecb2a02b03dc2e86f2065ed49f85e9367e8ca1428", size = 61619, upload-time = "2026-11-09T13:49:08.256Z" }, + { url = "https://files.pythonhosted.org/packages/9f/b7/473abf21c56969387bf90ac1d36bfbef620776bbe43a66ab4b1dc9fe0f1a/xxhash-4.1.0-pp311-pypy311_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2967f41d315ef1f9530af306ab79af7e5e6f3a4fdb3f02228bfc39414c11c273", size = 42795, upload-time = "2026-11-09T13:47:27.548Z" }, + { url = "https://files.pythonhosted.org/packages/e8/91/7981fb798edebeb130f95bd062f71f2512178af37925da889638ad63eb64/xxhash-4.1.0-pp311-pypy311_pp80-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0dcfb880344d6f1ed6feb867a898031b942f9c158f777c9ad678c078d7614b99", size = 47906, upload-time = "2026-11-09T13:47:30.555Z" }, + { url = "https://files.pythonhosted.org/packages/30/01/3876a8938f4dab623b501c77e874d7b3ac211fb1871e3bb236815dc66499/xxhash-4.1.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:100efa355bcc08b60a719926f9ce3c9ebf21cfa61db0a3bf43ebf64686d66ea3", size = 95476, upload-time = "2026-11-09T13:47:35.059Z" }, +] + +[[package]] +name = "yarl" +version = "1.25.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/75/16/e8be8e2fb175bbf41a0680381a319f1199fae256588241a2ac8677eafb49/yarl-1.25.1.tar.gz", hash = "sha256:03dd38de09bc213e9a8b29761eec33ee1d5318dac0e49d8af36e4d27830e23a7", size = 246245, upload-time = "2026-09-15T19:35:02.264Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/b3/2cea721d495ca57f8f414aa4867ee263f486b274e07463158cf52f02ba7f/yarl-1.25.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9d693bf4bf534e9ba3ae2780cfd577f5135629f7b5ac653490859d0b77864865", size = 143794, upload-time = "2026-09-15T19:30:26.946Z" }, + { url = "https://files.pythonhosted.org/packages/55/e6/cd145cff8e5cf60b8b3c41fbecfa2a45028a8dec3fbc52bec03595ff3d3b/yarl-1.25.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ab2054c5531af2a9ba7b69b8ec91e4f884420e83a8c5e579b013084cb57e5e5d", size = 103993, upload-time = "2026-09-15T19:30:28.661Z" }, + { url = "https://files.pythonhosted.org/packages/ce/7c/fbb40fe2d53747c40aa36a9e2bd2178a202f942bda0b670f3306d4aefbce/yarl-1.25.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:564fdc7085d2245ab84f88882fdb1d6ac0723124bff6ded35bfb1c00f812630d", size = 104010, upload-time = "2026-09-15T19:30:31.069Z" }, + { url = "https://files.pythonhosted.org/packages/f0/0b/5a516f70641092283f57cf3670bdb75e7327bcc0dcb5038697e4dfbfd569/yarl-1.25.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:acae6b45d1ace09b6ba3876da43b88366ef368f73b988c7f57e14231753d4420", size = 116444, upload-time = "2026-09-15T19:30:32.894Z" }, + { url = "https://files.pythonhosted.org/packages/b6/8a/d1a627f827b0a404ae0f5647cab0534959081cde13b0756a783469fb3b5e/yarl-1.25.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1fb2a01ba8cd9c5d2c5dc1ec35e0fc951d04b4f037541d4ac090c993ce58b3d7", size = 107565, upload-time = "2026-09-15T19:30:35.188Z" }, + { url = "https://files.pythonhosted.org/packages/aa/cf/c8e0aaec886840a6c4480fe44eaec7cd4319f79a563b79321473be79c56f/yarl-1.25.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e92b6bcc741b86d67606c40d3cb9c7cc8e6c737f81e31f4a94efc204456c92e3", size = 125006, upload-time = "2026-09-15T19:30:37.1Z" }, + { url = "https://files.pythonhosted.org/packages/50/26/0cce366d54a93cdc8342965dc7663385e4db161625cc1e8b18e786753d24/yarl-1.25.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:72c34ac7ad4314c19362d5ce27626dcc8429bd30bbf8c179f4234078851f9492", size = 128717, upload-time = "2026-09-15T19:30:38.904Z" }, + { url = "https://files.pythonhosted.org/packages/95/0c/a71501bbc1a674ff72c4d6c2b75f4d9a5af819f5244c3a7558080a8802c5/yarl-1.25.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d5add7b4ca7afeea91d52e4d4e4db3b1fe9885b71f07054560d8c4296b7441a2", size = 117728, upload-time = "2026-09-15T19:30:40.809Z" }, + { url = "https://files.pythonhosted.org/packages/e7/6f/c3267ca01defeed9ed9c4ff9b17bd54915432c405945233265b707475d1c/yarl-1.25.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:def538065f9e4d4cf1ae164bd59aba00dfa84f03923e0de4c3788f252d6bcd17", size = 116224, upload-time = "2026-09-15T19:30:42.818Z" }, + { url = "https://files.pythonhosted.org/packages/8f/69/fad57ee52d648431718ee0f1f68966a99c1352c3924688ffbdcc9d3fe51a/yarl-1.25.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0a191bfdb30a79b98e5d175d75285f9fcb78bf0e46ba5efda042e1c72071a0de", size = 116299, upload-time = "2026-09-15T19:30:44.966Z" }, + { url = "https://files.pythonhosted.org/packages/2a/d4/6a8c1e29f33338687ca278cba0a8fbf6525a322c2c02a9a500ccbe041152/yarl-1.25.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:71f42c5b9a948c113bbdebfa544598321431d064ff959d32e99b1feb61d68345", size = 108625, upload-time = "2026-09-15T19:30:46.874Z" }, + { url = "https://files.pythonhosted.org/packages/e8/d2/3a35ae791c9cb6522c106923ff25c3230d999091e5e65511bca23bbd9914/yarl-1.25.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:72849d892954be4d09e569b8b831ac39ce58417fedc767d4308a0fe542018a40", size = 124515, upload-time = "2026-09-15T19:30:49.082Z" }, + { url = "https://files.pythonhosted.org/packages/be/fd/2b022109a6b4af0f7dc371cf7500af380b0d4f034010243e1b0ce218dc93/yarl-1.25.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:efb01a106f971cb3752856bca2318bbdf7f01bd8823779c461586cbe5ffd5258", size = 115711, upload-time = "2026-09-15T19:30:51.208Z" }, + { url = "https://files.pythonhosted.org/packages/18/59/f7586271136c3ddb0126bbfe661844699369b76b555fe38c4efe86870b2e/yarl-1.25.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:a1daf47cd95a7c3a63456336bc5aaa8c86dd3a47d07ed3d0e76132ae4666a5a1", size = 122751, upload-time = "2026-09-15T19:30:53.535Z" }, + { url = "https://files.pythonhosted.org/packages/a0/0b/07f7a2d881f7e16c385b47fc1753382600847cad305dcc7fa0c25828acf8/yarl-1.25.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9489e6abf47ba37f332075a91444c7cfedb03e6ce99fbb2f116bfe1ce810da3b", size = 117983, upload-time = "2026-09-15T19:30:55.277Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9d/8cdceec66a9b940700cb45931741403f045b162afd79bcb93c41cadd0972/yarl-1.25.1-cp311-cp311-win_amd64.whl", hash = "sha256:d7306dee25b8a0e737363f347362b875094b4dc4e367311470656ae420fdbf8e", size = 102894, upload-time = "2026-09-15T19:30:57.606Z" }, + { url = "https://files.pythonhosted.org/packages/17/f1/7ec357db1d3ad2863542d71e8fe64a126bbec17b134cd7d30951196809a5/yarl-1.25.1-cp311-cp311-win_arm64.whl", hash = "sha256:abb1384477f5901d436b5d2e5465954de46ea6098f59163d243660b5c4461d35", size = 98609, upload-time = "2026-09-15T19:30:59.705Z" }, + { url = "https://files.pythonhosted.org/packages/54/22/318c7980066769c6bcd9221ed2248294f5698811da099013098c670565ed/yarl-1.25.1-py3-none-any.whl", hash = "sha256:681c758b0490f9e96b78e5fa8e8dc6e648e9185bb6eaebe73183c33ea0c445f3", size = 63617, upload-time = "2026-09-15T19:34:59.616Z" }, +] diff --git a/baselines/mezo/.gitignore b/baselines/mezo/.gitignore new file mode 100644 index 0000000..31c94ee --- /dev/null +++ b/baselines/mezo/.gitignore @@ -0,0 +1,161 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +lp_models/ + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +*.sh +.venv +.vscode +data +log* +runs +result +wandb +ensemble_predict_results +auto* +my* +slurm +tmp +display.py +llm_eval/result +llm_eval/display_result.py +llm_eval/data +*.ipynb +*.output +*.pdf diff --git a/baselines/mezo/.python-version b/baselines/mezo/.python-version new file mode 100644 index 0000000..ed7d51a --- /dev/null +++ b/baselines/mezo/.python-version @@ -0,0 +1 @@ +3.11.15 diff --git a/baselines/mezo/LICENSE b/baselines/mezo/LICENSE new file mode 100644 index 0000000..61d8849 --- /dev/null +++ b/baselines/mezo/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Princeton Natural Language Processing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/baselines/mezo/README.md b/baselines/mezo/README.md new file mode 100644 index 0000000..31c7e9c --- /dev/null +++ b/baselines/mezo/README.md @@ -0,0 +1,48 @@ +# MeZO: Fine-Tuning Language Models with Just Forward Passes + +This is the implementation for the paper [Fine-Tuning Language Models with Just Forward Passes](https://arxiv.org/pdf/2305.17333.pdf). +In this paper we propose a memory-efficient zeroth-order optimizer (**MeZO**), +adapting the classical zeroth-order SGD method to operate in-place, thereby fine-tuning language models (LMs) with the same memory footprint as inference. + +With a single A100 80GB GPU, MeZO can train a 30-billion parameter OPT model, whereas fine-tuning with Adam can train only a 2.7B LM. +MeZO demonstrates comparable performance to fine-tuning with backpropagation across multiple tasks, with up to 12× memory reduction. MeZO is also compatible with both full-parameter and parameter-efficient tuning techniques such as LoRA and prefix tuning. We also show that MeZO can effectively optimize non-differentiable objectives (e.g., maximizing accuracy or F1). + + +

+ Fig + + GPU memory usage comparison between zero-shot, in-context learning (ICL), Adam fine-tuning (FT), and our proposed MeZO. + +

+ +

+ Fig + + OPT-13B results with zero-shot, in-context learning (ICL), MeZO (we report the best among MeZO/MeZO (LoRA)/MeZO (prefix)), and fine-tuning with Adam (FT). MeZO demonstrates superior results over zero-shot and ICL and performs on par with FT (within 1%) on 7 out of 11 tasks, despite using only 1/12 memory. + +

+ + +## Reproduce our paper results + +For reproducing RoBERTa-large experiments, please refer to the [medium_models](https://github.com/princeton-nlp/MeZO/tree/main/medium_models) folder. For autoregressive LM (OPT) experiments, please refer to the [large_models](https://github.com/princeton-nlp/MeZO/tree/main/large_models) folder. If you want to learn more about how MeZO works and how we implement it, we recommend you to read the [large_models](https://github.com/princeton-nlp/MeZO/tree/main/large_models) folder as the implementation is clearer and more extensible. If you want to explore more variants of MeZO, we recommend trying out [medium_models](https://github.com/princeton-nlp/MeZO/tree/main/medium_models) as it's faster and has more variants implemented. + +## How to add MeZO to my own code? + +Our implementation of MeZO is based on [HuggingFace's Trainer](https://github.com/huggingface/transformers/blob/main/src/transformers/trainer.py). We add MeZO to the official implementation of trainer with minimum editing. Please refer to "How to add MeZO to my own code?" section in [large_models](https://github.com/princeton-nlp/MeZO/tree/main/large_models) README for more details. + +## Bugs or questions? + +If you have any questions related to the code or the paper, feel free to email Sadhika (`smalladi@princeton.edu`) or Tianyu (`tianyug@princeton.edu`). If you encounter any problems when using the code, or want to report a bug, you can open an issue. Please try to specify the problem with details so we can help you better and quicker! + + + +## Citation + +```bibtex +@article{malladi2023mezo, + title={Fine-Tuning Large Language Models with Just Forward Passes}, + author={Malladi, Sadhika and Gao, Tianyu and Nichani, Eshaan and Damian, Alex and Lee, Jason D and Chen, Danqi and Arora, Sanjeev}, + year={2023} +} +``` diff --git a/baselines/mezo/TROUBLESHOOTING.md b/baselines/mezo/TROUBLESHOOTING.md new file mode 100644 index 0000000..405d6cd --- /dev/null +++ b/baselines/mezo/TROUBLESHOOTING.md @@ -0,0 +1,81 @@ +# MEZO:独立环境、入口与排障 + +官方来源:https://github.com/princeton-nlp/MeZO.git;锁定提交:`552cb1b710767f9a6e1dc8f9645d7640376f9941`。 +官方文件保留原样;此目录新增 pyproject.toml、uv.lock、native.py、run_compatible.py 和本文。 +原仓库 Git 历史存放在被忽略的 `.upstream-git/`,防止主项目意外把整个目录当成 gitlink。 +查看上游版本:`git --git-dir=.upstream-git --work-tree=. rev-parse HEAD`。 +不要在这个目录执行普通 git commit/push;主项目尚未提交。 + +## 安装与版本 + +在 WSL 中执行(不需要激活根目录环境): + +```bash +cd ~/experiments_codebase +source scripts/env.sh +cd baselines/mezo +uv sync --locked +uv run --locked python native.py --help +``` + +此目录 `.venv` 独立,Python 3.11,torch 2.13.0,原生 Transformers 4.28.1。 +直接依赖精确版本写在 pyproject.toml,全部间接依赖和 wheel 哈希写在 uv.lock。 +`uv sync --locked` 默认 native;`uv sync --locked --no-default-groups --group modern` 切换到 Transformers 4.57.1。 +两组互斥,使用同一个本库 `.venv`,不会激活其他方法的环境。不要使用 `uv pip install -U` 绕开锁。 + +## 官方入口及命令 + +原入口 `large_models/run.py`。本地资源包装入口 `native.py` 仅设置共享路径、提供本地 Dataset 和启动参数,然后运行原始程序。 +`--asset-model`、`--asset-task`、`--asset-out` 是包装参数,其余参数透传官方入口;以 `--help` 为准。 +MeZO/LOZO/AGZO包装器默认固定 train_set_seed=42,并将result_file显式指向共享输出;否则原版会因num_dev配合空采样seed触发断言,或因相对result目录缺失在训练完成后报错。用户后置同名参数可覆盖这些默认值。 + +```bash +uv run --locked python native.py --asset-model facebook/opt-1.3b --asset-task sst2 --max_steps 2 --num_train 16 --num_dev 4 --num_eval 4 --per_device_train_batch_size 2 --learning_rate 1e-6 --zo_eps 1e-3 --evaluation_strategy no --save_strategy no --logging_steps 1 +``` + +调参请使用官方参数:学习率 `--learning_rate`,差分半径 `--zo_eps`,batch `--per_device_train_batch_size`。 +参数覆盖:MeZO/LOZO/AGZO 默认 full(不传 LoRA/prefix/head-only 开关);LOREN 包装器显式传 `--full_parameter`。 +全参数覆盖不等于无结构全维搜索;LOZO/AGZO 仍使用结构化扰动。 + +## Qwen3 / DROP 与统一比较入口 + +```bash +uv run --locked --no-default-groups --group modern python run_compatible.py --model Qwen/Qwen3-0.6B --task sst2 --budget 12 --train-samples 16 --dev-samples 4 --eval-samples 4 --batch-size 2 --eval-batch-size 2 --calibration-samples 2 --no-save-checkpoint +# DROP:将 --task 改为 drop,并合理增加 --max-length(短冒烟可以先用128)。 +``` + +兼容层 `../../src/experiments_codebase/official.py` 从本库源码编译官方数值函数;不导入旧 Trainer,也不另写一套公式。 +通用数据协议和计账在 `../../src/experiments_codebase/task.py`、`runner.py`。 +此入口统一 SST2 为两 verbalizer 的交叉熵、DROP 为答案 token 的 teacher-forced CE;它与部分官方任务目标不同,日志会标记 task adapter。 +预算为总 main forward,而非更新步数;检测和基提取前向不免费。评估前向另列。 +不支持从兼容检查点续训;可用 `--action evaluate --checkpoint ...` 或 `--action generate --checkpoint ... --prompt ...` 推理。 + +## 核心位置 + +- 核心算法:`large_models/trainer.py: zo_step / zo_update`。 +- 模型/数据:`large_models/run.py: Framework; large_models/tasks.py / templates.py`。 +- 官方超参数原型:入口中的参数 dataclass/parser 与原始 shell 脚本;与本站兼容入口参数不是同一命名空间。 + +## 系统组件与常见问题 + +原始 Transformers 4.28.1 不认识 Qwen3;Qwen3 必须使用 modern 依赖组和兼容入口。不要在原生环境单独升级 Transformers,这会破坏旧 Trainer 私有接口。 + +WSL 必须能看到 NVIDIA 驱动:先运行 `nvidia-smi`。RTX 5070 Ti 是 Blackwell;原论文旧版 torch/CUDA wheel 不支持其架构。 +本机选用支持当前显卡的 torch 2.13.0,不声称完全复刻论文年代的二进制环境。 +CUDA runtime 随 wheel 安装,普通运行无需 nvcc;自编译第三方扩展才需要 CUDA toolkit、gcc/g++、make、Python headers。 +Fedora 常见系统依赖:`git curl ca-certificates libgomp libstdc++`;缺库先用 `ldd` 核查,不要盲目替换驱动。 +uv 会下载 Python 3.11,不依赖系统 Python 3.14;保持 `.python-version`。 +如果 WSL 解析到 198.18.* 且直连超时,可在未跟踪的根 `.env` 配置你现有代理,再 `source ../../scripts/env.sh`;不要把代理/token 写入源码。 +本次用临时 HTTP(S)_PROXY 沿用主机代理;未修改系统网络配置。 +`huggingface-hub` 不能随意升到2.x:Transformers 4.x 需要 <1.0。已锁0.36.0。 +新版setuptools移除了pkg_resources,旧Trainer/accelerate仍导入它;锁80.9.0同时满足torch要求的>=77.0.3。LOREN官方requirements漏列loguru,本环境已补0.7.3。 +旧 datasets/pyarrow/numpy 有 ABI 约束,三者必须遵守 uv.lock;不能拿现代 `.venv` 的 site-packages 混入原生环境。 +共享DROP不能用datasets5.x的List元数据序列化后直接给2.x/3.x读;请在根锁定环境datasets3.6执行prepare_assets,工具可从原始parquet重建不兼容资产。 +E盘必须真实挂载。Assets默认位于 `/mnt/e/Experiments/Assets`,包装器在写入前检查 mountpoint。 +模型和数据只从本地共享目录读取;资产缺失先在根环境运行 `scripts/prepare_assets.py --download-missing`。 +Qwen的词表较大,长序列或大 batch 会增显存;先减batch/长度,不要把OOM归因于优化算法。 + +## 验证状态 + +以根目录 `reports/validation_report.json` 和 `reports/validation.log` 为准,区分安装、导入、短步训练、模型任务矩阵。 +`--help` 通过不代表训练通过,短步通过也不代表论文精度复现。未完成项目会明确记录。 diff --git a/baselines/mezo/assets/fig1.png b/baselines/mezo/assets/fig1.png new file mode 100644 index 0000000..b663d9e Binary files /dev/null and b/baselines/mezo/assets/fig1.png differ diff --git a/baselines/mezo/assets/fig2.png b/baselines/mezo/assets/fig2.png new file mode 100644 index 0000000..32be383 Binary files /dev/null and b/baselines/mezo/assets/fig2.png differ diff --git a/baselines/mezo/large_models/README.md b/baselines/mezo/large_models/README.md new file mode 100644 index 0000000..ce45e70 --- /dev/null +++ b/baselines/mezo/large_models/README.md @@ -0,0 +1,75 @@ +# MeZO on Large Autoregressive Language Models + +This part of the code is for MeZO experiments on large autoregressive language models. It includes training autoregressive LMs with linear probing, head tuning, full fine-tuning, parameter-efficient fine-tuning (PEFT), and MeZO. It also covers zero-shot and in-context learning (ICL) evaluation. It is tested on OPT-13B, 30B, and 66B but should be able to extend to other sizes and other autoregressive LMs. + + +## Installation + +Please install the latest versions of PyTorch (`pytorch` following [https://pytorch.org](https://pytorch.org)), Transformers (`transformers`), and Accelerate (`accelerate`). This code is tested on `torch==2.1.0.dev20230514+cu118`, `transformers==4.28.1`, and `accelerate==0.17.1` with Python 3.9.7, but should work with older/later versions of these packages too. + +## Usage + +Use `run.py` for all functions (zero-shot/ICL/fine-tuning/MeZO): +```bash +python run.py {ARGUMENTS} +``` + +Please read `run.py` for a complete list of arguments. We introduce some of the most important ones below. +* `--num_train`: Number of training examples. For ICL, this is the number of demonstrations. +* `--num_dev`: Number of validation examples. +* `--num_test`: Number of testing examples. +* `--model_name`: HuggingFace model name or path. +* `--task_name`: Task name. +* `--trainer`: can be `none` (zero-shot/ICL), `regular` (fine-tuning), or `zo` (MeZO). +* `--train_as_classification`: turn this on for classification tasks (Cross Entropy over likelihood of each class' label words). Otherwise it is LM-style teacher forcing. +* `--zo_eps`: MeZO hyperparameter epsilon. +* `--prefix_tuning`: use prefix-tuning. +* `--lora`: use LoRA. + +We also support all [HuggingFace trainer arguments](https://github.com/huggingface/transformers/blob/main/src/transformers/training_args.py) for easily setting fine-tuning hyperparameters. + +We provide example scripts below for reproducing our experiments. All our examples sample 1,000 training examples, 500 validation examples, and 1,000 testing examples. For ICL, we use 32 demonstrations. For detailed hyperparameters and grid search configs, please refer to Appendix D of [our paper](https://arxiv.org/pdf/2305.17333.pdf). +```bash +# Zero-shot +MODEL=facebook/opt-13b TASK=SST2 bash icl.sh --num_train 0 + +# In-context learning +MODEL=facebook/opt-13b TASK=SST2 bash icl.sh + +# Full-parameter fine-tuning, prefix-tuning, and LoRA +MODEL=facebook/opt-1.3b TASK=SST2 MODE=ft LR=1e-5 bash finetune.sh +MODEL=facebook/opt-1.3b TASK=SST2 MODE=prefix LR=1e-2 bash finetune.sh +MODEL=facebook/opt-1.3b TASK=SST2 MODE=lora LR=1e-4 bash finetune.sh + +# Full-parameter fine-tuning using fully-sharded data parallel or FSDP (multi-GPU) +MODEL=facebook/opt-13b TASK=SST2 MODE=ft LR=1e-5 NUM_GPU=4 bash finetune_fsdp.sh + +# MeZO (full-parameter, prefix-tuning, and LoRA) +MODEL=facebook/opt-13b TASK=SST2 MODE=ft LR=1e-7 EPS=1e-3 bash mezo.sh +MODEL=facebook/opt-13b TASK=SST2 MODE=prefix LR=1e-3 EPS=1e-1 bash mezo.sh +MODEL=facebook/opt-13b TASK=SST2 MODE=lora LR=5e-5 EPS=1e-2 bash mezo.sh + +# MeZO with non-differentiable objective (SQuAD (F1) + MeZO prefix as an example) +MODEL=facebook/opt-13b TASK=SQuAD MODE=prefix LR=1e-2 EPS=1e-1 bash mezo.sh --non_diff --evaluation_strategy no --save_strategy no --save_model +``` + +Note that `icl.sh` and `mezo.sh` automatically support multi-GPU usage. For fine-tuning, use `finetune_fsdp.sh` for multi-GPU training and specific `NUM_GPU`. Evaluation results (json format) and checkpoints (HuggingFace format) will be saved in `result` folder. + +Our recommended hyperparameter search range for OPT-13b (should also work for other sizes/models) are as follows, + +| MeZO methods | LR | EPS | +| ------------- | ------------ | --- | +| Full parameter | 1e-6/1e-7 | 1e-3 | +| Prefix-tuning | 1e-2/1e-3 | 1e-1 | +| LoRA | 1e-4/5e-5 | 1e-2 | + +## How to add MeZO to my own code? + +Our implementation of MeZO is based on [HuggingFace Trainer](https://github.com/huggingface/transformers/blob/main/src/transformers/trainer.py). We try to add MeZO to the official implementation of trainer with minimum editing. Please refer to `trainer.py` for details. We edit the `_inner_training_loop` function (to see where we edited, search `MeZO added`; ignore the linear probing part) to replace the original optimizer with MeZO, which contains the following operations: + +* `zo_perturb_parameters`: our in-place parameter perturbation function. +* `zo_forward` and `zo_forward_nondiff`: get loss value (differentiable/non-differentiable). +* `zo_step`: estimate the gradient by MeZO +* `zo_update`: update parameters by the estimated gradient. + +To incorporate MeZO in your own HuggingFace code, simply overload HuggingFace's `Trainer` class and edit `_inner_training_loop` as we did in `trainer.py`, and add the above MeZO functions from `trainer.py` in your trainer. For a more intuitive explanation of the MeZO algorithm, please refer to Algorithm 1 in [our paper](https://arxiv.org/pdf/2305.17333.pdf). diff --git a/baselines/mezo/large_models/ht_opt.py b/baselines/mezo/large_models/ht_opt.py new file mode 100644 index 0000000..3079a49 --- /dev/null +++ b/baselines/mezo/large_models/ht_opt.py @@ -0,0 +1,1268 @@ +# For head-tuning, we use torch.no_grad() for all the forward functions except the lm head +# The following code is mostly copied from https://github.com/huggingface/transformers/blob/main/src/transformers/models/opt/modeling_opt.py +# Search "MeZO added" to find we we added + +# coding=utf-8 +# Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" PyTorch OPT model.""" +import random +from typing import List, Optional, Tuple, Union + +import torch +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +from transformers.activations import ACT2FN +from transformers.modeling_outputs import ( + BaseModelOutputWithPast, + CausalLMOutputWithPast, + QuestionAnsweringModelOutput, + SequenceClassifierOutputWithPast, +) +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import ( + add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, + logging, + replace_return_docstrings, +) +from transformers.models.opt.configuration_opt import OPTConfig + + +logger = logging.get_logger(__name__) + +_CHECKPOINT_FOR_DOC = "facebook/opt-350m" +_CONFIG_FOR_DOC = "OPTConfig" + +# Base model docstring +_EXPECTED_OUTPUT_SHAPE = [1, 8, 1024] + +# SequenceClassification docstring +_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ArthurZ/opt-350m-dummy-sc" +_SEQ_CLASS_EXPECTED_LOSS = 1.71 +_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_0'" + +OPT_PRETRAINED_MODEL_ARCHIVE_LIST = [ + "facebook/opt-125m", + "facebook/opt-350m", + "facebook/opt-1.3b", + "facebook/opt-2.7b", + "facebook/opt-6.7b", + "facebook/opt-13b", + "facebook/opt-30b", + # See all OPT models at https://huggingface.co/models?filter=opt +] + + +# Copied from transformers.models.bart.modeling_bart._make_causal_mask +def _make_causal_mask( + input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0 +): + """ + Make causal mask used for bi-directional self-attention. + """ + bsz, tgt_len = input_ids_shape + mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device) + mask_cond = torch.arange(mask.size(-1), device=device) + mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) + mask = mask.to(dtype) + + if past_key_values_length > 0: + mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1) + return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) + + +def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + bsz, src_len = mask.size() + tgt_len = tgt_len if tgt_len is not None else src_len + + expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) + + inverted_mask = 1.0 - expanded_mask + + return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) + + +class OPTLearnedPositionalEmbedding(nn.Embedding): + """ + This module learns positional embeddings up to a fixed maximum size. + """ + + def __init__(self, num_embeddings: int, embedding_dim: int): + # OPT is set up so that if padding_idx is specified then offset the embedding ids by 2 + # and adjust num_embeddings appropriately. Other models don't have this hack + self.offset = 2 + super().__init__(num_embeddings + self.offset, embedding_dim) + + def forward(self, attention_mask: torch.LongTensor, past_key_values_length: int = 0): + """`input_ids_shape` is expected to be [bsz x seqlen].""" + attention_mask = attention_mask.long() + + # create positions depending on attention_mask + positions = (torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask).long() - 1 + + # cut positions if `past_key_values_length` is > 0 + positions = positions[:, past_key_values_length:] + + return super().forward(positions + self.offset) + + +class OPTAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__( + self, + embed_dim: int, + num_heads: int, + dropout: float = 0.0, + is_decoder: bool = False, + bias: bool = True, + ): + super().__init__() + self.embed_dim = embed_dim + self.num_heads = num_heads + self.dropout = dropout + self.head_dim = embed_dim // num_heads + + if (self.head_dim * num_heads) != self.embed_dim: + raise ValueError( + f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" + f" and `num_heads`: {num_heads})." + ) + self.scaling = self.head_dim**-0.5 + self.is_decoder = is_decoder + + self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def forward( + self, + hidden_states: torch.Tensor, + key_value_states: Optional[torch.Tensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + """Input shape: Batch x Time x Channel""" + + # if key_value_states are provided this layer is used as a cross-attention layer + # for the decoder + is_cross_attention = key_value_states is not None + + bsz, tgt_len, _ = hidden_states.size() + + # get query proj + query_states = self.q_proj(hidden_states) * self.scaling + # get key, value proj + if is_cross_attention and past_key_value is not None: + # reuse k,v, cross_attentions + key_states = past_key_value[0] + value_states = past_key_value[1] + elif is_cross_attention: + # cross_attentions + key_states = self._shape(self.k_proj(key_value_states), -1, bsz) + value_states = self._shape(self.v_proj(key_value_states), -1, bsz) + elif past_key_value is not None: + # reuse k, v, self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + else: + # self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + + if self.is_decoder: + # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. + # Further calls to cross_attention layer can then reuse all cross-attention + # key/value_states (first "if" case) + # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of + # all previous decoder key/value_states. Further calls to uni-directional self-attention + # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) + # if encoder bi-directional self-attention `past_key_value` is always `None` + past_key_value = (key_states, value_states) + + proj_shape = (bsz * self.num_heads, -1, self.head_dim) + query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape) + key_states = key_states.view(*proj_shape) + value_states = value_states.view(*proj_shape) + + src_len = key_states.size(1) + attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) + + if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len): + raise ValueError( + f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, tgt_len, src_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" + ) + attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask + attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437 + if attn_weights.dtype == torch.float16: + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16) + else: + attn_weights = nn.functional.softmax(attn_weights, dim=-1) + + if layer_head_mask is not None: + if layer_head_mask.size() != (self.num_heads,): + raise ValueError( + f"Head mask for a single layer should be of size {(self.num_heads,)}, but is" + f" {layer_head_mask.size()}" + ) + attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + if output_attentions: + # this operation is a bit awkward, but it's required to + # make sure that attn_weights keeps its gradient. + # In order to do so, attn_weights have to be reshaped + # twice and have to be reused in the following + attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len) + else: + attn_weights_reshaped = None + + attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) + + attn_output = torch.bmm(attn_probs, value_states) + + if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) + attn_output = attn_output.transpose(1, 2) + + # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be + # partitioned aross GPUs when using tensor-parallelism. + attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) + + attn_output = self.out_proj(attn_output) + + return attn_output, attn_weights_reshaped, past_key_value + + +class OPTDecoderLayer(nn.Module): + def __init__(self, config: OPTConfig): + super().__init__() + self.embed_dim = config.hidden_size + self.self_attn = OPTAttention( + embed_dim=self.embed_dim, + num_heads=config.num_attention_heads, + dropout=config.attention_dropout, + is_decoder=True, + bias=config.enable_bias, + ) + self.do_layer_norm_before = config.do_layer_norm_before + self.dropout = config.dropout + self.activation_fn = ACT2FN[config.activation_function] + + self.self_attn_layer_norm = nn.LayerNorm( + self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine + ) + self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim, bias=config.enable_bias) + self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim, bias=config.enable_bias) + self.final_layer_norm = nn.LayerNorm(self.embed_dim, elementwise_affine=config.layer_norm_elementwise_affine) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size + `(encoder_attention_heads,)`. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + past_key_value=past_key_value, + attention_mask=attention_mask, + layer_head_mask=layer_head_mask, + output_attentions=output_attentions, + ) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + hidden_states = residual + hidden_states + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Fully Connected + hidden_states_shape = hidden_states.shape + hidden_states = hidden_states.reshape(-1, hidden_states.size(-1)) + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + hidden_states = self.fc1(hidden_states) + hidden_states = self.activation_fn(hidden_states) + + hidden_states = self.fc2(hidden_states) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + + hidden_states = (residual + hidden_states).view(hidden_states_shape) + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +OPT_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`OPTConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTPreTrainedModel(PreTrainedModel): + config_class = OPTConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["OPTDecoderLayer"] + _keys_to_ignore_on_load_unexpected = [r"decoder\.version"] + + def _init_weights(self, module): + std = self.config.init_std + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, (OPTDecoder)): + module.gradient_checkpointing = value + + +OPT_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape + `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape + `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +class OPTDecoder(OPTPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`] + + Args: + config: OPTConfig + """ + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.dropout = config.dropout + self.layerdrop = config.layerdrop + self.padding_idx = config.pad_token_id + self.max_target_positions = config.max_position_embeddings + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.word_embed_proj_dim, self.padding_idx) + self.embed_positions = OPTLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size) + + if config.word_embed_proj_dim != config.hidden_size: + self.project_out = nn.Linear(config.hidden_size, config.word_embed_proj_dim, bias=False) + else: + self.project_out = None + + if config.word_embed_proj_dim != config.hidden_size: + self.project_in = nn.Linear(config.word_embed_proj_dim, config.hidden_size, bias=False) + else: + self.project_in = None + + # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility + # with checkpoints that have been fine-tuned before transformers v4.20.1 + # see https://github.com/facebookresearch/metaseq/pull/164 + if config.do_layer_norm_before and not config._remove_final_layer_norm: + self.final_layer_norm = nn.LayerNorm( + config.hidden_size, elementwise_affine=config.layer_norm_elementwise_affine + ) + else: + self.final_layer_norm = None + + self.layers = nn.ModuleList([OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)]) + + self.gradient_checkpointing = False + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask + def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): + # create causal mask + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + combined_attention_mask = None + if input_shape[-1] > 1: + combined_attention_mask = _make_causal_mask( + input_shape, + inputs_embeds.dtype, + device=inputs_embeds.device, + past_key_values_length=past_key_values_length, + ) + + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( + inputs_embeds.device + ) + combined_attention_mask = ( + expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask + ) + + return combined_attention_mask + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + """ + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + batch_size, seq_length = input_shape + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + # required mask seq length can be calculated via length of past + mask_seq_length = past_key_values_length + seq_length + + # embed positions + if attention_mask is None: + attention_mask = torch.ones(batch_size, mask_seq_length, device=inputs_embeds.device) + causal_attention_mask = self._prepare_decoder_attention_mask( + attention_mask, input_shape, inputs_embeds, past_key_values_length + ) + pos_embeds = self.embed_positions(attention_mask, past_key_values_length) + + if self.project_in is not None: + inputs_embeds = self.project_in(inputs_embeds) + + hidden_states = inputs_embeds + pos_embeds + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + # check if head_mask has a correct number of layers specified if desired + for attn_mask, mask_name in zip([head_mask], ["head_mask"]): + if attn_mask is not None: + if attn_mask.size()[0] != (len(self.layers)): + raise ValueError( + f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" + f" {head_mask.size()[0]}." + ) + + for idx, decoder_layer in enumerate(self.layers): + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + causal_attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=causal_attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + if self.final_layer_norm is not None: + hidden_states = self.final_layer_norm(hidden_states) + + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTModel(OPTPreTrainedModel): + def __init__(self, config: OPTConfig): + super().__init__(config) + self.decoder = OPTDecoder(config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.decoder.embed_tokens = value + + def get_decoder(self): + return self.decoder + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=BaseModelOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_EXPECTED_OUTPUT_SHAPE, + ) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn) + decoder_outputs = self.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + if not return_dict: + return decoder_outputs + + return BaseModelOutputWithPast( + last_hidden_state=decoder_outputs.last_hidden_state, + past_key_values=decoder_outputs.past_key_values, + hidden_states=decoder_outputs.hidden_states, + attentions=decoder_outputs.attentions, + ) + + +class OPTForCausalLM(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = OPTModel(config) + + # the lm_head weight is automatically tied to the embed tokens weight + self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model.decoder = decoder + + def get_decoder(self): + return self.model.decoder + + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional + tensors are only required when the model is used as a decoder in a Sequence to Sequence model. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, OPTForCausalLM + + >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m") + >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") + + >>> prompt = "Hey, are you consciours? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + # MeZO added: torch.no_grad + with torch.no_grad(): + outputs = self.model.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + logits = self.lm_head(outputs[0]).contiguous() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs + ): + if past_key_values: + input_ids = input_ids[:, -1:] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + model_inputs.update( + { + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + @staticmethod + def _reorder_cache(past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) + return reordered_past + + +@add_start_docstrings( + """ + The OPT Model transformer with a sequence classification head on top (linear layer). + + [`OPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + OPT_START_DOCSTRING, +) +class OPTForSequenceClassification(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.num_labels = config.num_labels + self.model = OPTModel(config) + self.score = nn.Linear(config.word_embed_proj_dim, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION, + output_type=SequenceClassifierOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_SEQ_CLASS_EXPECTED_OUTPUT, + expected_loss=_SEQ_CLASS_EXPECTED_LOSS, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size, sequence_length = input_ids.shape[:2] + else: + batch_size, sequence_length = inputs_embeds.shape[:2] + + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device) + else: + sequence_lengths = -1 + logger.warning( + f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " + "unexpected if using padding tokens in conjunction with `inputs_embeds.`" + ) + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + +@add_start_docstrings( + """ + The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD + (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + """, + OPT_START_DOCSTRING, +) +class OPTForQuestionAnswering(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.model = OPTModel(config) + self.qa_outputs = nn.Linear(config.word_embed_proj_dim, 2) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + start_positions: Optional[torch.LongTensor] = None, + end_positions: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, QuestionAnsweringModelOutput]: + r""" + start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, OPTForQuestionAnswering + >>> import torch + + >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT + >>> tokenizer = AutoTokenizer.from_pretrained("facebook/opt-350m") + + >>> # note: we are loading a OPTForQuestionAnswering from the hub here, + >>> # so the head will be randomly initialized, hence the predictions will be random + >>> model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m") + + >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" + + >>> inputs = tokenizer(question, text, return_tensors="pt") + >>> with torch.no_grad(): + ... outputs = model(**inputs) + + >>> answer_start_index = outputs.start_logits.argmax() + >>> answer_end_index = outputs.end_logits.argmax() + + >>> answer_offset = len(tokenizer(question)[0]) + + >>> predict_answer_tokens = inputs.input_ids[ + ... 0, answer_offset + answer_start_index : answer_offset + answer_end_index + 1 + ... ] + >>> predicted = tokenizer.decode(predict_answer_tokens) + >>> predicted + ' a nice puppet' + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + + logits = self.qa_outputs(hidden_states) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + transformer_outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value diff --git a/baselines/mezo/large_models/lora.py b/baselines/mezo/large_models/lora.py new file mode 100644 index 0000000..a87dd6e --- /dev/null +++ b/baselines/mezo/large_models/lora.py @@ -0,0 +1,147 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import torch +from torch import nn +from torch.nn import functional as F +import math + +def find_module(root_module: nn.Module, key: str): + """ + Find a module with a specific name in a Transformer model + From OpenDelta https://github.com/thunlp/OpenDelta + """ + sub_keys = key.split(".") + parent_module = root_module + for sub_key in sub_keys[:-1]: + parent_module = getattr(parent_module, sub_key) + module = getattr(parent_module, sub_keys[-1]) + return parent_module, sub_keys[-1], module + + +class LoRALinear(nn.Linear): + """ + LoRA implemented in a dense layer + From https://github.com/microsoft/LoRA/blob/main/loralib/layers.py + """ + def __init__( + self, + in_features: int, + out_features: int, + r: int = 0, + lora_alpha: int = 1, + lora_dropout: float = 0., + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + merge_weights: bool = False, # Not sure if this will affect saving/loading models so just set it to be False + **kwargs + ): + nn.Linear.__init__(self, in_features, out_features, **kwargs) + + self.r = r + self.lora_alpha = lora_alpha + # Optional dropout + if lora_dropout > 0.: + self.lora_dropout = nn.Dropout(p=lora_dropout) + else: + self.lora_dropout = lambda x: x + # Mark the weight as unmerged + self.merged = False + self.merge_weights = merge_weights + self.fan_in_fan_out = fan_in_fan_out + # Actual trainable parameters + if r > 0: + self.lora_A = nn.Parameter(self.weight.new_zeros((r, in_features))) + self.lora_B = nn.Parameter(self.weight.new_zeros((out_features, r))) + self.scaling = self.lora_alpha / self.r + # Freezing the pre-trained weight matrix + self.weight.requires_grad = False + self.reset_parameters() + if fan_in_fan_out: + self.weight.data = self.weight.data.transpose(0, 1) + + def reset_parameters(self): + nn.Linear.reset_parameters(self) + if hasattr(self, 'lora_A'): + # initialize A the same way as the default for nn.Linear and B to zero + nn.init.kaiming_uniform_(self.lora_A, a=math.sqrt(5)) + nn.init.zeros_(self.lora_B) + + def train(self, mode: bool = True): + def T(w): + return w.transpose(0, 1) if self.fan_in_fan_out else w + nn.Linear.train(self, mode) + if mode: + if self.merge_weights and self.merged: + # Make sure that the weights are not merged + if self.r > 0: + self.weight.data -= T(self.lora_B @ self.lora_A) * self.scaling + self.merged = False + else: + if self.merge_weights and not self.merged: + # Merge the weights and mark it + if self.r > 0: + self.weight.data += T(self.lora_B @ self.lora_A) * self.scaling + self.merged = True + + def forward(self, x: torch.Tensor): + def T(w): + return w.transpose(0, 1) if self.fan_in_fan_out else w + if self.r > 0 and not self.merged: + result = F.linear(x, T(self.weight), bias=self.bias) + if self.r > 0: + result += (self.lora_dropout(x) @ self.lora_A.transpose(0, 1) @ self.lora_B.transpose(0, 1)) * self.scaling + return result + else: + return F.linear(x, T(self.weight), bias=self.bias) + + +class LoRA: + + def __init__(self, model, r, alpha, float16): + """ + Input: + r, alpha: LoRA hyperparameters + float16: Whether the model parameters are float16 or not + """ + + self.model = model + self.hidden_dim = model.config.hidden_size + self.float16 = float16 + + if model.config.model_type == "opt": + attention_name = "attn" + elif model.config.model_type == "roberta": + attention_name = "attention" + else: + raise NotImplementedError + + # Insert LoRA + for key, _ in model.named_modules(): + if key[-len(attention_name):] == attention_name: + logger.info(f"Inject lora to: {key}") + _, _, attn = find_module(model, key) + + if model.config.model_type == "opt": + original_q_weight = attn.q_proj.weight.data + original_q_bias = attn.q_proj.bias.data + original_v_weight= attn.v_proj.weight.data + original_v_bias = attn.v_proj.bias.data + attn.q_proj = LoRALinear(model.config.hidden_size, model.config.hidden_size, r=r, lora_alpha=alpha, bias=model.config.enable_bias).to(original_q_weight.device) + attn.v_proj = LoRALinear(model.config.hidden_size, model.config.hidden_size, r=r, lora_alpha=alpha, bias=model.config.enable_bias).to(original_v_weight.device) + if float16: + attn.q_proj.half() + attn.v_proj.half() + attn.q_proj.weight.data = original_q_weight + attn.q_proj.bias.data = original_q_bias + attn.v_proj.weight.data = original_v_weight + attn.v_proj.bias.data = original_v_bias + else: + raise NotImplementedError + + # Freeze non-LoRA parameters + for n, p in model.named_parameters(): + if "lora" not in n: + p.requires_grad = False \ No newline at end of file diff --git a/baselines/mezo/large_models/metrics.py b/baselines/mezo/large_models/metrics.py new file mode 100644 index 0000000..0e0a282 --- /dev/null +++ b/baselines/mezo/large_models/metrics.py @@ -0,0 +1,78 @@ +import numpy as np +import collections +import re +import string +from collections import Counter + +def normalize_answer(s): + """Lower text and remove punctuation, articles and extra whitespace.""" + + def remove_articles(text): + return re.sub(r'\b(a|an|the)\b', ' ', text) + + def white_space_fix(text): + return ' '.join(text.split()) + + def remove_punc(text): + exclude = set(string.punctuation) + return ''.join(ch for ch in text if ch not in exclude) + + def lower(text): + return text.lower() + + return white_space_fix(remove_articles(remove_punc(lower(s)))) + + +def calculate_metric(predictions, metric_name): + if metric_name == "accuracy": + if isinstance(predictions[0].correct_candidate, list): + return np.mean([pred.predicted_candidate in pred.correct_candidate for pred in predictions]) + else: + return np.mean([pred.correct_candidate == pred.predicted_candidate for pred in predictions]) + elif metric_name == "em": + # For question answering + return np.mean([any([normalize_answer(ans) == normalize_answer(pred.predicted_candidate) for ans in pred.correct_candidate]) for pred in predictions]) + elif metric_name == "f1": + # For question answering + f1 = [] + for pred in predictions: + all_f1s = [] + if pred.correct_candidate[0] == "CANNOTANSWER" or pred.correct_candidate[0] == "no answer": + f1.append(int(normalize_answer(pred.correct_candidate[0]) == normalize_answer(pred.predicted_candidate))) + else: + for ans in pred.correct_candidate: + prediction_tokens = normalize_answer(pred.predicted_candidate).split() + ground_truth_tokens = normalize_answer(ans).split() + common = Counter(prediction_tokens) & Counter(ground_truth_tokens) + num_same = sum(common.values()) + if num_same == 0: + all_f1s.append(0) + else: + precision = 1.0 * num_same / len(prediction_tokens) + recall = 1.0 * num_same / len(ground_truth_tokens) + all_f1s.append((2 * precision * recall) / (precision + recall)) + f1.append(max(all_f1s)) + + return np.mean(f1) + + +def f1(pred, gold): + """ + This separate F1 function is used as non-differentiable metric for SQuAD + """ + if gold[0] == "CANNOTANSWER" or gold[0] == "no answer": + return int(normalize_answer(gold[0]) == normalize_answer(pred)) + else: + all_f1s = [] + for ans in gold: + prediction_tokens = normalize_answer(pred).split() + ground_truth_tokens = normalize_answer(ans).split() + common = Counter(prediction_tokens) & Counter(ground_truth_tokens) + num_same = sum(common.values()) + if num_same == 0: + all_f1s.append(0) + else: + precision = 1.0 * num_same / len(prediction_tokens) + recall = 1.0 * num_same / len(ground_truth_tokens) + all_f1s.append((2 * precision * recall) / (precision + recall)) + return np.max(all_f1s) \ No newline at end of file diff --git a/baselines/mezo/large_models/prefix.py b/baselines/mezo/large_models/prefix.py new file mode 100644 index 0000000..40d10b9 --- /dev/null +++ b/baselines/mezo/large_models/prefix.py @@ -0,0 +1,200 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import torch +from torch import nn + +def find_module(root_module: nn.Module, key: str): + """ + Find a module with a specific name in a Transformer model + From OpenDelta https://github.com/thunlp/OpenDelta + """ + sub_keys = key.split(".") + parent_module = root_module + for sub_key in sub_keys[:-1]: + parent_module = getattr(parent_module, sub_key) + module = getattr(parent_module, sub_keys[-1]) + return parent_module, sub_keys[-1], module + + +def attn_forward_hook(self, *args, **kwargs): + """ + Replace the original attention forward with this to enable prefix + """ + + def _expand_bsz(x, bsz): + x = x.reshape(x.size(0), self.num_heads, -1).transpose(0,1) # (num_prefix, hidden) -> (num_head, num_prefix, hidden/num_head) + x = x.unsqueeze(0).expand(bsz, *x.shape) # -> (bsz, num_head, num_prefix, hidden/num_head) + return x + + if "hidden_states" in kwargs: + hidden_states = kwargs["hidden_states"] + else: + hidden_states = args[0] + bsz = hidden_states.size(0) + + if 'past_key_value' not in kwargs or kwargs['past_key_value'] is None: + if self.reparam: + prefix_keys = self.prefix_mlp_keys(self.prefix_input_embeds) + prefix_values = self.prefix_mlp_values(self.prefix_input_embeds) + else: + prefix_keys, prefix_values = self.prefix_keys, self.prefix_values + kwargs['past_key_value'] = (_expand_bsz(prefix_keys, bsz), _expand_bsz(prefix_values, bsz)) + + if 'attention_mask' in kwargs and kwargs['attention_mask'] is not None: + am = kwargs['attention_mask'] + kwargs['attention_mask'] = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1) + elif len(args) > 1: # attention mask is passed via positional argument + am = args[1] + am = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1) + args = (args[0], am) + args[2:] + + return self.original_forward(*args, **kwargs) + + +def prepare_inputs_for_generation( + self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs): + """ + Replace the original "prepare_inputs_for_generation" with this to pass prefix correctly + """ + original_input_len = input_ids.size(-1) + if past_key_values: + input_ids = input_ids[:, -1:] + + # if `inputs_embeds` are passed, we only want to use them in the 1st generation step + if inputs_embeds is not None and past_key_values is None: + model_inputs = {"inputs_embeds": inputs_embeds} + else: + model_inputs = {"input_ids": input_ids} + + if past_key_values is not None: + # Check if we should add extra to attention mask + if past_key_values[0][0].size(2) != attention_mask.size(1) - 1: + num_prefix = past_key_values[0][0].size(2) - (attention_mask.size(1) - 1) + attention_mask = torch.cat([torch.ones((attention_mask.size(0), num_prefix), dtype=attention_mask.dtype, device=attention_mask.device), attention_mask], dim=-1) + + model_inputs.update( + { + "past_key_values": past_key_values, + "use_cache": kwargs.get("use_cache"), + "attention_mask": attention_mask, + } + ) + return model_inputs + + +class PrefixTuning: + + def __init__(self, model, num_prefix, reparam=True, embed_dim=512, mid_dim=512, float16=False, init_by_real_act=False): + """ + Inputs: + num_prefix: number of prefix tokens + reparam: use reparameterization trick (not used in MeZO) + embed_dim, mid_dim: hyperparameters for reparameterization trick (not used in MeZO) + float15: whether the model parameters are float15 + init_by_real_act: init prefix tokens by real activations + """ + + self.model = model + self.num_prefix = num_prefix + self.hidden_dim = model.config.hidden_size + self.float16 = float16 + + # Reparameterization + self.reparam = reparam + self.embed_dim = embed_dim + self.mid_dim = mid_dim + + input_embeds = None # For reparameterization + if model.config.model_type == "opt": + attention_name = "attn" + first_layer_name = "layers.0" + layer_name = "layers." + elif model.config.model_type == "roberta": + attention_name = "attention" + first_layer_name = "layer.0" + layer_name = "layer." + elif model.config.model_type == "llama": + attention_name = "self_attn" + first_layer_name = "layers.0" + layer_name = "layers." + else: + raise NotImplementedError + + if init_by_real_act: + # Initialize prefix with real words' activations + assert not reparam + + # Randomly sample input tokens + input_tokens = torch.randint(low=0, high=model.config.vocab_size, size=(1, num_prefix), dtype=torch.long).cuda() + if model.config.model_type in ["opt", "llama"]: + with torch.no_grad(): + # Get the real activations + real_key_values = model(input_ids=input_tokens, use_cache=True).past_key_values + else: + raise NotImplementedError + + # Insert prefix + for key, _ in model.named_modules(): + if key[-len(attention_name):] == attention_name: + layer_id = int(key.split(layer_name)[1].split(".")[0]) + logger.info(f"Inject prefix to: {key}") + _, _, attn = find_module(model, key) + + # Replace the old forward functions + attn.original_forward = attn.forward + attn.forward = attn_forward_hook.__get__(attn, type(attn)) + if not hasattr(attn, "num_heads"): + attn.num_heads = model.config.num_attention_heads + first = first_layer_name in key + self.add_prefix(attn, first=first, input_embeds=input_embeds) + + if first and self.reparam: + input_embeds = attn.prefix_input_embeds + if init_by_real_act: + logger.info(f"Reinitialize with actual activation: {key} (layer {layer_id})") + keys = real_key_values[layer_id][0].squeeze(0).transpose(0, 1).reshape(num_prefix, -1) + values = real_key_values[layer_id][1].squeeze(0).transpose(0, 1).reshape(num_prefix, -1) + attn.prefix_keys.data = keys.to(attn.prefix_keys.data.device) + attn.prefix_values.data = values.to(attn.prefix_values.data.device) + + # Freeze non-prefix parameters + for n, p in model.named_parameters(): + if "prefix" not in n: + p.requires_grad = False + + # Replace the old prepare_inputs_for_generation function + model.prepare_inputs_for_generation = prepare_inputs_for_generation.__get__(model, type(model)) + + + def add_prefix(self, module, first, input_embeds=None): + device = module.k_proj.weight.data.device + module.num_prefix = self.num_prefix + module.reparam = self.reparam + if self.reparam: + if first: + # For the first layer we inject the embeddings + logger.info("For prefix+reparameterization, inject the embeddings in the first layer.") + module.prefix_input_embeds = nn.Parameter(torch.randn(self.num_prefix, self.embed_dim, device=device, dtype=self.model.dtype), requires_grad=True) + else: + assert input_embeds is not None + module.prefix_input_embeds = input_embeds + module.prefix_mlp_keys = nn.Sequential( + nn.Linear(self.embed_dim, self.mid_dim), + nn.Tanh(), + nn.Linear(self.mid_dim, self.hidden_dim) + ).to(device) + module.prefix_mlp_values = nn.Sequential( + nn.Linear(self.embed_dim, self.mid_dim), + nn.Tanh(), + nn.Linear(self.mid_dim, self.hidden_dim) + ).to(device) + if self.float16: + module.prefix_mlp_keys = module.prefix_mlp_keys.half() + module.prefix_mlp_values = module.prefix_mlp_values.half() + else: + module.prefix_keys = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=device, dtype=self.model.dtype), requires_grad=True) + module.prefix_values = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=device, dtype=self.model.dtype), requires_grad=True) diff --git a/baselines/mezo/large_models/run.py b/baselines/mezo/large_models/run.py new file mode 100644 index 0000000..8069c2d --- /dev/null +++ b/baselines/mezo/large_models/run.py @@ -0,0 +1,527 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import argparse +import time +import tasks +from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM, Trainer, HfArgumentParser, Trainer, TrainingArguments, DataCollatorWithPadding, DataCollatorForTokenClassification +from typing import Union, Optional +import torch +from torch.nn.parameter import Parameter +import numpy as np +from dataclasses import dataclass, is_dataclass, asdict +from tqdm import tqdm +from tasks import get_task +import json +import torch.nn.functional as F +from torch.utils.data import Dataset +from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP +from metrics import calculate_metric +from utils import * +from trainer import OurTrainer +import random + +@dataclass +class OurArguments(TrainingArguments): + # dataset and sampling strategy + task_name: str = "SST2" # task name should match the string before Dataset in the Dataset class name. We support the following task_name: SST2, RTE, CB, BoolQ, WSC, WIC, MultiRC, Copa, ReCoRD, SQuAD, DROP + + # Number of examples + num_train: int = 0 # ICL mode: number of demonstrations; training mode: number of training samples + num_dev: int = None # (only enabled with training) number of development samples + num_eval: int = None # number of evaluation samples + num_train_sets: int = None # how many sets of training samples/demos to sample; if None and train_set_seed is None, then we will sample one set for each evaluation sample + train_set_seed: int = None # designated seed to sample training samples/demos + result_file: str = None # file name for saving performance; if None, then use the task name, model name, and config + + # Model loading + model_name: str = "facebook/opt-125m" # HuggingFace model name + load_float16: bool = False # load model parameters as float16 + load_bfloat16: bool = False # load model parameters as bfloat16 + load_int8: bool = False # load model parameters as int8 + max_length: int = 2048 # max length the model can take + no_auto_device: bool = False # do not load model by auto device; should turn this on when using FSDP + + # Calibration + sfc: bool = False # whether to use SFC calibration + icl_sfc: bool = False # whether to use SFC calibration for ICL samples + + # Training + trainer: str = "none" + ## options + ## - none: no training -- for zero-shot or in-context learning (ICL) + ## - regular: regular huggingface trainer -- for fine-tuning + ## - zo: zeroth-order (MeZO) training + only_train_option: bool = True # whether to only train the option part of the input + train_as_classification: bool = False # take the log likelihood of all options and train as classification + + # MeZO + zo_eps: float = 1e-3 # eps in MeZO + + # Prefix tuning + prefix_tuning: bool = False # whether to use prefix tuning + num_prefix: int = 5 # number of prefixes to use + no_reparam: bool = True # do not use reparameterization trick + prefix_init_by_real_act: bool = True # initialize prefix by real activations of random words + + # LoRA + lora: bool = False # whether to use LoRA + lora_alpha: int = 16 # alpha in LoRA + lora_r: int = 8 # r in LoRA + + # Generation + sampling: bool = False # whether to use sampling + temperature: float = 1.0 # temperature for generation + num_beams: int = 1 # number of beams for generation + top_k: int = None # top-k for generation + top_p: float = 0.95 # top-p for generation + max_new_tokens: int = 50 # max number of new tokens to generate + eos_token: str = "\n" # end of sentence token + + # Saving + save_model: bool = False # whether to save the model + no_eval: bool = False # whether to skip evaluation + tag: str = "" # saving tag + + # Linear probing + linear_probing: bool = False # whether to do linear probing + lp_early_stopping: bool = False # whether to do early stopping in linear probing + head_tuning: bool = False # head tuning: only tune the LM head + + # Untie emb/lm_head weights + untie_emb: bool = False # untie the embeddings and LM head + + # Display + verbose: bool = False # verbose output + + # Non-diff objective + non_diff: bool = False # use non-differentiable objective (only support F1 for SQuAD for now) + + # Auto saving when interrupted + save_on_interrupt: bool = False # save model when interrupted (useful for long training) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser = HfArgumentParser(OurArguments) + args = parser.parse_args_into_dataclasses()[0] + print(args) + return args + + +def set_seed(seed: int): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +class Framework: + + def __init__(self, args, task): + self.args = args + self.task = task + self.model, self.tokenizer = self.load_model() + + + def load_model(self): + """ + Load HuggingFace models + """ + with count_time("Loading model with FP%d" % (16 if self.args.load_float16 else 32)): + free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) + config = AutoConfig.from_pretrained(self.args.model_name) + if self.args.untie_emb: + # Untie embeddings/LM head + logger.warn("Untie embeddings and LM head") + config.tie_word_embeddings = False + if self.args.head_tuning: + # Head tuning + from ht_opt import OPTForCausalLM + model = OPTForCausalLM.from_pretrained( + self.args.model_name, + config=config, + ) + elif self.args.no_auto_device: + # No auto device (use for FSDP) + model = AutoModelForCausalLM.from_pretrained( + self.args.model_name, + config=config, + ) + else: + # Auto device loading + torch_dtype = torch.float32 + if self.args.load_float16: + torch_dtype = torch.float16 + elif self.args.load_bfloat16: + torch_dtype = torch.bfloat16 + model = AutoModelForCausalLM.from_pretrained( + self.args.model_name, + config=config, + device_map='auto', + torch_dtype=torch_dtype, + max_memory={i: f'{free_in_GB-5}GB' for i in range(torch.cuda.device_count())}, + load_in_8bit=self.args.load_int8, + ) + model.eval() + + # Load tokenizer + tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast=False) + + # HF tokenizer bug fix + if "opt" in self.args.model_name: + tokenizer.bos_token_id = 0 + + if "llama" in self.args.model_name: + # LLaMA padding token + tokenizer.pad_token_id = 0 # technically + + # Prefix tuning/LoRA + if self.args.prefix_tuning: + from prefix import PrefixTuning + PrefixTuning(model, num_prefix=self.args.num_prefix, reparam=not self.args.no_reparam, float16=self.args.load_float16, init_by_real_act=self.args.prefix_init_by_real_act) + if self.args.lora: + from lora import LoRA + LoRA(model, r=self.args.lora_r, alpha=self.args.lora_alpha, float16=self.args.load_float16) + + if self.args.head_tuning: + if model.config.model_type == "opt": + head_name = "lm_head" if self.args.untie_emb else "embed_tokens" + else: + raise NotImplementedError + for n, p in model.named_parameters(): + if head_name not in n: + p.requires_grad = False + else: + logger.info(f"Only tuning {n}") + + return model, tokenizer + + + def forward(self, input_ids, option_len=None, generation=False): + """ + Given input_ids and the length of the option, return the log-likelihood of each token in the option. + For generation tasks, return the generated text. + This function is only for inference + """ + input_ids = torch.tensor([input_ids]).to(self.model.device) + + if generation: + args = self.args + # Autoregressive generation + outputs = self.model.generate( + input_ids, do_sample=args.sampling, temperature=args.temperature, + num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - input_ids.size(1)), + num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id], + ) + # For generation, directly return the text output + output_text = self.tokenizer.decode(outputs[0][input_ids.size(1):], skip_special_tokens=True).strip() + return output_text + else: + with torch.inference_mode(): + self.model.eval() + logits = self.model(input_ids=input_ids).logits + labels = input_ids[0, 1:] + logits = logits[0, :-1] + log_probs = F.log_softmax(logits, dim=-1) + + selected_log_probs = log_probs[torch.arange(len(labels)).to(labels.device), labels] + selected_log_probs = selected_log_probs.cpu().detach() + # Only return the option (candidate) part + return selected_log_probs[-option_len:] + + + def one_step_pred(self, train_samples, eval_sample, verbose=False): + """ + Return the prediction on the eval sample. In ICL, use train_samples as demonstrations + """ + verbose = verbose or self.args.verbose + if verbose: + logger.info("========= Example =========") + logger.info(f"Candidate: {eval_sample.candidates}") + logger.info(f"Correct candidate: {eval_sample.correct_candidate}") + + + # Encode (add prompt and tokenize) the sample; if multiple-choice/classification, encode all candidates (options) + encoded_candidates, option_lens = encode_prompt( + self.task, self.task.get_template(), train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length, + generation=self.task.generation, max_new_tokens=self.args.max_new_tokens + ) + + # Calibration + if self.args.sfc or self.args.icl_sfc: + sfc_encoded_candidates, sfc_option_lens = encode_prompt(self.task, self.task.get_template(), + train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length, + sfc=self.args.sfc, icl_sfc=self.args.icl_sfc, generation=self.task.generation, + max_new_tokens=self.args.max_new_tokens + ) + + outputs = [] + if self.task.generation: + # For generation tasks, return the autoregressively-generated text + output_text = self.forward(encoded_candidates[0], generation=True) + if verbose: + logger.info("=== Prompt ===") + logger.info(self.tokenizer.decode(encoded_candidates[0])) + logger.info(f"Output: {output_text}") + return Prediction(correct_candidate=eval_sample.correct_candidate, predicted_candidate=output_text) + else: + # For classification/multiple-choice, calculate the probabilities of all candidates + for candidate_id, encoded_candidate in enumerate(encoded_candidates): + selected_log_probs = self.forward(encoded_candidate, option_len=option_lens[candidate_id]) + if verbose: + if candidate_id == 0: + logger.info("=== Candidate %d ===" % candidate_id) + logger.info(self.tokenizer.decode(encoded_candidate)) + else: + logger.info("=== Candidate %d (without context)===" % candidate_id) + logger.info(self.tokenizer.decode(encoded_candidate).split(self.task.train_sep)[-1]) + logger.info(f"Log probabilities of the option tokens: {selected_log_probs}") + + if self.args.sfc or self.args.icl_sfc: + sfc_selected_log_probs = self.forward(sfc_encoded_candidates[candidate_id], option_len=sfc_option_lens[candidate_id]) + if verbose: + logger.info("=== Candidate %d (without context) SFC ===" % candidate_id) + logger.info(self.tokenizer.decode(sfc_encoded_candidates[candidate_id]).split(self.task.train_sep)[-1]) + logger.info(f"Log probabilities of the option tokens: {sfc_selected_log_probs}") + + outputs.append({"log_probs": selected_log_probs, "sfc_log_probs": sfc_selected_log_probs if self.args.sfc or self.args.icl_sfc else None}) + + if self.args.sfc or self.args.icl_sfc: + # Calibrated probabilities (surface form competition; https://arxiv.org/pdf/2104.08315.pdf) + # log p(candidate | input) = log p_lm(candidate | input) - log p_lm(candidate | sfc prompt) + scores = [x['log_probs'].sum().item() - x['sfc_log_probs'].sum().item() for x in outputs] + else: + # (Default) length-normalized log probabilities + # log p(candidate | input) = log p_lm(candidate | input) / |candidate #tokens| + scores = [x['log_probs'].mean().item() for x in outputs] + + if verbose: + logger.info(f"Prediction scores: {scores}") + + if isinstance(eval_sample.correct_candidate, list): + # For some datasets there are multiple correct answers + correct_candidate_id = [eval_sample.candidates.index(c) for c in eval_sample.correct_candidate] + else: + correct_candidate_id = eval_sample.candidates.index(eval_sample.correct_candidate) + + return Prediction(correct_candidate=correct_candidate_id, predicted_candidate=int(np.argmax(scores))) + + + def evaluate(self, train_samples, eval_samples, one_train_set_per_eval_sample=False): + """ + Evaluate function. If one_train_set_per_eval_sample is True, then each eval sample has its own training (demonstration) set. + """ + if one_train_set_per_eval_sample: + logger.info(f"There are {len(eval_samples)} validation samples and one train set per eval sample") + else: + logger.info(f"There are {len(train_samples)} training samples and {len(eval_samples)} validation samples") + + # Prediction loop + predictions = [] + for eval_id, eval_sample in enumerate(tqdm(eval_samples)): + predictions.append( + self.one_step_pred(train_samples[eval_id] if one_train_set_per_eval_sample else train_samples, eval_sample, verbose=(eval_id < 3)) + ) + + # Calculate metrics + metric_name = getattr(self.task, "metric_name", "accuracy") + metrics = {metric_name: calculate_metric(predictions, metric_name)} + return metrics + + + def train(self, train_samples, eval_samples): + """ + Training function + """ + # Set tokenizer to left padding (so that all the options are right aligned) + self.tokenizer.padding_side = "left" + + class HFDataset(Dataset): + + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __getitem__(self, idx): + return self.data[idx] + + + def _convert(samples): + """ + Convert samples to HF-compatible dataset + """ + data = [] + for sample in samples: + encoded_candidates, option_lens = encode_prompt( + self.task, self.task.get_template(), [], sample, self.tokenizer, + max_length=self.args.max_length, generation=self.task.generation, generation_with_gold=True, + max_new_tokens=self.args.max_new_tokens + ) + if self.task.generation: + correct_candidate_id = 0 + elif isinstance(sample.correct_candidate, list): + correct_candidate_id = sample.candidates.index(sample.correct_candidate[0]) + else: + correct_candidate_id = sample.candidates.index(sample.correct_candidate) + + if self.args.non_diff: + # For non-differentiable objective, there is no teacher forcing thus the + # current answer part is removed + encoded_candidates[correct_candidate_id] = encoded_candidates[correct_candidate_id][:-option_lens[correct_candidate_id]] + + if self.args.train_as_classification: + # For classification, we provide the label as the correct candidate id + data.append([{"input_ids": encoded_candidates[_i], "labels": correct_candidate_id, "option_len": option_lens[_i], "num_options": len(sample.candidates)} for _i in range(len(encoded_candidates))]) + elif self.args.only_train_option: + # Otherwise, it is just LM-style teacher forcing + if self.args.non_diff: + # For non-differentiable objective, we need to provide the gold answer to calculate F1/acc + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id], "gold": sample.correct_candidate}) + else: + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id]}) + else: + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id]}) + return data + + with count_time("Tokenizing training samples"): + train_dataset = HFDataset(_convert(train_samples)) + eval_dataset = HFDataset(_convert(eval_samples)) + + if self.args.only_train_option and not self.args.non_diff: + # If --only_train_option and not with a non-differentiable objective, we wrap the forward function + self.model.original_forward = self.model.forward + self.model.forward = forward_wrap_with_option_len.__get__(self.model, type(self.model)) + + if self.args.non_diff: + collator = NondiffCollator + else: + collator = DataCollatorForTokenClassification + + trainer = OurTrainer( + model=self.model, + args=self.args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + tokenizer=self.tokenizer, + data_collator=DataCollatorWithPaddingAndNesting(self.tokenizer, pad_to_multiple_of=8) if self.args.train_as_classification else collator(self.tokenizer, pad_to_multiple_of=8), + ) + if self.args.save_on_interrupt: + trainer.add_callback(SIGUSR1Callback()) + + # Resume training from a last checkpoint + last_checkpoint = None + from transformers.trainer_utils import get_last_checkpoint + if os.path.isdir(self.args.output_dir) and not self.args.overwrite_output_dir: + last_checkpoint = get_last_checkpoint(self.args.output_dir) + if last_checkpoint is not None and self.args.resume_from_checkpoint is None: + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + if self.args.resume_from_checkpoint is not None: + last_checkpoint = self.args.resume_from_checkpoint + + trainer.train(resume_from_checkpoint=last_checkpoint) + + # Explicitly save the model + if self.args.save_model: + logger.warn("Save model..") + trainer.save_model() + + # FSDP compatibility + self.model = trainer.model + + # Reset the forward function for evaluation + if self.args.only_train_option and not self.args.non_diff: + if type(self.model) == FSDP: + logger.info("This is an FSDP model now. Be careful when assigning back the original forward function") + self.model._fsdp_wrapped_module.forward = self.model._fsdp_wrapped_module.original_forward + else: + self.model.forward = self.model.original_forward + + +def result_file_tag(args): + """ + Get the result file tag + """ + save_model_name = args.model_name.split("/")[-1] + sfc_tag = "-sfc" if args.sfc else "" + icl_sfc_tag = "-icl_sfc" if args.icl_sfc else "" + sample_eval_tag = "-sampleeval%d" % args.num_eval if args.num_eval is not None else "" + sample_train_tag = "-ntrain%d" % args.num_train if args.num_train > 0 else "" + sample_dev_tag = "-ndev%d" % args.num_dev if args.num_dev is not None else "" + customized_tag = f"-{args.tag}" if len(args.tag) > 0 else "" + return f"{args.task_name}-{save_model_name}" + sfc_tag + icl_sfc_tag + sample_eval_tag + sample_train_tag + sample_dev_tag + customized_tag + + +def main(): + args = parse_args() + + set_seed(args.seed) + task = get_task(args.task_name) + train_sets = task.sample_train_sets(num_train=args.num_train, num_dev=args.num_dev, num_eval=args.num_eval, num_train_sets=args.num_train_sets, seed=args.train_set_seed) + + # Initialize trainer and load model + framework = Framework(args, task) + + if args.train_set_seed is not None or args.num_train_sets is not None: + # Eval samples share one (or multiple) training set(s) + for train_set_id, train_samples in enumerate(train_sets): + train_set_seed = train_set_id if args.train_set_seed is None else args.train_set_seed + + # Sample eval samples + if args.num_eval is not None: + eval_samples = task.sample_subset(data_split="valid", seed=train_set_seed, num=args.num_eval) + else: + eval_samples = task.valid_samples + + if args.trainer != "none": + if args.num_dev is not None: + # Dev samples + dev_samples = train_samples[-args.num_dev:] + train_samples = train_samples[:-args.num_dev] + else: + dev_samples = None + + # Training + framework.train(train_samples, dev_samples if dev_samples is not None else eval_samples) + + if not args.no_eval: + metrics = framework.evaluate([], eval_samples) # No in-context learning if there is training + if dev_samples is not None: + dev_metrics = framework.evaluate([], dev_samples) + for m in dev_metrics: + metrics["dev_" + m] = dev_metrics[m] + else: + assert args.num_dev is None + # Zero-shot / in-context learning + metrics = framework.evaluate(train_samples, eval_samples) + + if not args.no_eval: + logger.info("===== Train set %d =====" % train_set_seed) + logger.info(metrics) + if args.local_rank <= 0: + write_metrics_to_file(metrics, "result/" + result_file_tag(args) + f"-trainset{train_set_id}.json" if args.result_file is None else args.result_file) + + else: + # For each eval sample, there is a training set. no training is allowed + # This is for in-context learning (ICL) + assert args.trainer == "none" + if args.num_eval is not None: + eval_samples = task.sample_subset(data_split="valid", seed=0, num=args.num_eval) + else: + eval_samples = task.valid_samples + + metrics = framework.evaluate(train_sets, eval_samples, one_train_set_per_eval_sample=True) + logger.info(metrics) + if args.local_rank <= 0: + write_metrics_to_file(metrics, "result/" + result_file_tag(args) + "-onetrainpereval.json" if args.result_file is None else args.result_file) + +if __name__ == "__main__": + main() diff --git a/baselines/mezo/large_models/tasks.py b/baselines/mezo/large_models/tasks.py new file mode 100644 index 0000000..4d482c4 --- /dev/null +++ b/baselines/mezo/large_models/tasks.py @@ -0,0 +1,425 @@ +from templates import * +from utils import temp_seed +import json +import os +from datasets import load_dataset +from dataclasses import dataclass +from typing import List, Union +import string +import random +import datasets +import sys +import numpy as np +import logging + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +def get_task(task_name): + aa = task_name.split("__") + if len(aa) == 2: + task_group, subtask = aa + else: + task_group = aa[0] + subtask = None + class_ = getattr(sys.modules[__name__], f"{task_group}Dataset") + instance = class_(subtask) + return instance + + +@dataclass +class Sample: + id: int = None + data: dict = None + correct_candidate: Union[str, List[str]] = None + candidates: List[str] = None + + +class Dataset: + mixed_set = False + train_sep = "\n\n" + generation = False # whether this is a generation task + + def __init__(self, subtask=None, **kwargs) -> None: + self.subtask = subtask + + def get_task_name(self): + return self.subtask + + def load_dataset(): + raise NotImplementedError + + def get_template(self, template_version=0): + templates = {0: Template} + return templates[template_version] + + def build_sample(self, example): + return + + def sample_train_sets(self, num_train=32, num_dev=None, num_eval=None, num_train_sets=None, seed=None): + if seed is not None: + # one train/demo set using the designated seed + seeds = [seed] + elif num_train_sets is not None: + # num_train_sets train/demo sets + seeds = list(range(num_train_sets)) + else: + # one train/demo set per evaluation sample + assert num_dev is None # not supported + len_valid_samples = len(self.samples["valid"]) if num_eval is None else num_eval + with temp_seed(0): + seeds = np.random.randint(0, 10000, len_valid_samples) + + train_samples = [] + for i, set_seed in enumerate(seeds): + if self.mixed_set: + raise NotImplementedError + train_samples.append(self.sample_subset(data_split="valid", seed=set_seed, num=num_train, exclude=i)) + else: + if num_dev is not None: + train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train+num_dev)) # dev set is included at the end of train set + if num_train + num_dev > len(self.samples["train"]): + logger.warn("num_train + num_dev > available training examples") + else: + train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train)) + if num_dev is not None: + logger.info(f"Sample train set {len(train_samples[-1])}/{len(self.samples['train'])}") + logger.info(f"... including dev set {num_dev} samples") + return train_samples + + def sample_subset(self, data_split="train", seed=0, num=100, exclude=None): + with temp_seed(seed): + samples = self.samples[data_split] + lens = len(samples) + index = np.random.permutation(lens).tolist()[:num if exclude is None else num+1] + if exclude is not None and exclude in index: + index.remove(exclude) + else: + index = index[:num] + return [samples[i] for i in index] + + @property + def valid_samples(self): + return self.samples["valid"] + + +class SST2Dataset(Dataset): + train_sep = "\n\n" + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset('glue', 'sst2') + train_d = d["train"] + validation_d = d["validation"] + + train_samples = [self.build_sample(example) for example in train_d] + valid_samples = [self.build_sample(example) for example in validation_d] + + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example): + label = int(example["label"]) + return Sample(id=example["idx"], data=example, correct_candidate=label, candidates=[0, 1]) + + def get_template(self, template_version=0): + return {0: SST2Template}[template_version]() + + +class CopaDataset(Dataset): + train_sep = "\n\n" + mixed_set = False + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + train_examples = load_dataset('super_glue', "copa")["train"] + valid_examples = load_dataset('super_glue', "copa")["validation"] + + train_samples = [self.build_sample(example) for example in train_examples] + valid_samples = [self.build_sample(example) for example in valid_examples] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example): + sample = \ + Sample( + id=example["idx"], + data=example, + candidates=[example["choice1"], example["choice2"]], + correct_candidate=example[f"choice{example['label'] + 1}"], + ) + + return sample + + def get_template(self, template_version=0): + return {0: CopaTemplate}[template_version]() + + +class BoolQDataset(Dataset): + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("boolq") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=["Yes", "No"], + correct_candidate="Yes" if example["answer"] else "No", + ) + + return sample + + def get_template(self, template_version=2): + return {0: BoolQTemplate, 1: BoolQTemplateV2, 2: BoolQTemplateV3}[template_version]() + + +class MultiRCDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "multirc") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: MultiRCTemplate}[template_version]() + + +class CBDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "cb") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1, 2], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: CBTemplate}[template_version]() + + +class WICDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "wic") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: WICTemplate}[template_version]() + + +class WSCDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "wsc.fixed") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: WSCTemplate}[template_version]() + + +class ReCoRDDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "record") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=example['entities'], + correct_candidate=example['answers'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: ReCoRDTemplateGPT3}[template_version]() + + +class RTEDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "rte") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: RTETemplate}[template_version]() + + +class SQuADDataset(Dataset): + metric_name = "f1" + generation = True + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset() + + def load_dataset(self): + dataset = load_dataset("squad") + train_examples = dataset["train"] + valid_examples = dataset["validation"] + + train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)] + valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example, idx): + answers = example['answers']['text'] + assert len(answers) > 0 + return Sample( + id=idx, + data={ + "title": example['title'], + "context": example['context'], + "question": example['question'], + "answers": answers + }, + candidates=None, + correct_candidate=answers + ) + + def get_template(self, template_version=0): + return {0: SQuADv2Template}[template_version]() + + +class DROPDataset(Dataset): + metric_name = "f1" + generation = True + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset() + + def load_dataset(self): + dataset = load_dataset("drop") + train_examples = dataset["train"] + valid_examples = dataset["validation"] + + train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)] + valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example, idx): + answers = example['answers_spans']['spans'] + assert len(answers) > 0 + return Sample( + id=idx, + data={ + "context": example['passage'], + "question": example['question'], + "answers": answers + }, + candidates=None, + correct_candidate=answers + ) + + def get_template(self, template_version=0): + return {0: DROPTemplate}[template_version]() diff --git a/baselines/mezo/large_models/templates.py b/baselines/mezo/large_models/templates.py new file mode 100644 index 0000000..4a07fb2 --- /dev/null +++ b/baselines/mezo/large_models/templates.py @@ -0,0 +1,379 @@ +class Template: + def encode(self, sample): + """ + Return prompted version of the example (without the answer/candidate) + """ + raise NotImplementedError + + def verbalize(self, sample, candidate): + """ + Return the prompted version of the example (with the answer/candidate) + """ + return candidate + + def encode_sfc(self, sample): + """ + Same as encode, but for SFC (calibration) -- this usually means the input is not included + """ + return "" + + def verbalize_sfc(self, sample, candidate): + """ + Same as verbalize, but for SFC (calibration) -- this usually means the input is not included + """ + return candidate + + +class SST2Template(Template): + verbalizer = {0: "terrible", 1: "great"} + def encode(self, sample): + text = sample.data["sentence"].strip() + return f"{text} It was" + + def verbalize(self, sample, candidate): + text = sample.data["sentence"].strip() + return f"{text} It was {self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f" It was" + + def verbalize_sfc(self, sample, candidate): + return f" It was {self.verbalizer[candidate]}" + + +class CopaTemplate(Template): + capitalization: str = "correct" + effect_conj: str = " so " + cause_conj: str = " because " + + def get_conjucture(self, sample): + if sample.data["question"] == "effect": + conjunction = self.effect_conj + elif sample.data["question"] == "cause": + conjunction = self.cause_conj + else: + raise NotImplementedError + return conjunction + + def get_prompt(self, sample): + premise = sample.data["premise"].rstrip() + if premise.endswith("."): # TODO Add other scripts with different punctuation + premise = premise[:-1] + conjunction = self.get_conjucture(sample) + prompt = premise + conjunction + if self.capitalization == "upper": + prompt = prompt.upper() + elif self.capitalization == "lower": + prompt = prompt.lower() + return prompt + + def encode(self, sample): + prompt = self.get_prompt(sample) + return prompt + + def capitalize(self, c): + if self.capitalization == "correct": + words = c.split(" ") + if words[0] != "I": + words[0] = words[0].lower() + return " ".join(words) + elif self.capitalization == "bug": + return c + elif self.capitalization == "upper": + return c.upper() + elif self.capitalization == "lower": + return c.lower() + else: + raise NotImplementedError + + def verbalize(self, sample, candidate): + prompt = self.get_prompt(sample) + return prompt + self.capitalize(candidate) + + def encode_sfc(self, sample): + conjunction = self.get_conjucture(sample) + return conjunction.strip() + + def verbalize_sfc(self, sample, candidate): + conjunction = self.get_conjucture(sample) + sfc_prompt = conjunction.strip() + " " + self.capitalize(candidate) + return sfc_prompt + + +class BoolQTemplate(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question} {candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class BoolQTemplateV2(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\\n\\n" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\\n\\n{candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class BoolQTemplateV3(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\n" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\n{candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class MultiRCTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + paragraph = sample.data["paragraph"] + question = sample.data["question"] + answer = sample.data["answer"] + return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n" + + def verbalize(self, sample, candidate): + paragraph = sample.data["paragraph"] + question = sample.data["question"] + answer = sample.data["answer"] + return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class CBTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "Yes", 1: "No", 2: "Maybe"} + + def encode(self, sample): + premise = sample.data["premise"] + hypothesis = sample.data["hypothesis"] + return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n" + + def verbalize(self, sample, candidate): + premise = sample.data["premise"] + hypothesis = sample.data["hypothesis"] + return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class WICTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + sent1 = sample.data["sentence1"] + sent2 = sample.data["sentence2"] + word = sample.data["word"] + return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n" + + def verbalize(self, sample, candidate): + sent1 = sample.data["sentence1"] + sent2 = sample.data["sentence2"] + word = sample.data["word"] + return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class WSCTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + text = sample.data['text'] + span1 = sample.data['span1_text'] + span2 = sample.data['span2_text'] + return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n" + + def verbalize(self, sample, candidate): + text = sample.data['text'] + span1 = sample.data['span1_text'] + span2 = sample.data['span2_text'] + return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class ReCoRDTemplate(Template): + # From PromptSource 1 but modified + + def encode(self, sample): + passage = sample.data['passage'] + query = sample.data['query'] + return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer:" + + def verbalize(self, sample, candidate): + passage = sample.data['passage'] + query = sample.data['query'] + return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}" + + def encode_sfc(self, sample): + return f"Answer:" + + def verbalize_sfc(self, sample, candidate): + return f"Answer: {candidate}" + + +class ReCoRDTemplateGPT3(Template): + # From PromptSource 1 but modified + + def encode(self, sample): + passage = sample.data['passage'].replace("@highlight\n", "- ") + return f"{passage}\n-" + + def verbalize(self, sample, candidate): + passage = sample.data['passage'].replace("@highlight\n", "- ") + query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate) + return f"{passage}\n- {query}" + + # passage = sample.data['passage'] + # query = sample.data['query'] + # return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}" + + def encode_sfc(self, sample): + return f"-" + + def verbalize_sfc(self, sample, candidate): + query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate) + return f"- {query}" + + +class RTETemplate(Template): + # From PromptSource 1 + verbalizer={0: "Yes", 1: "No"} + + def encode(self, sample): + premise = sample.data['premise'] + hypothesis = sample.data['hypothesis'] + return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n" + + def verbalize(self, sample, candidate): + premise = sample.data['premise'] + hypothesis = sample.data['hypothesis'] + return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class SQuADv2Template(Template): + + def encode(self, sample): + question = sample.data['question'].strip() + title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer:" + + def verbalize(self, sample, candidate): + question = sample.data['question'].strip() + title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer: {answer}\n" + + + def encode_sfc(self, sample): + raise NotImplementedError + + def verbalize_sfc(self, sample, candidate): + raise NotImplementedError + + +class DROPTemplate(Template): + + def encode(self, sample): + question = sample.data['question'].strip() + # title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Passage: {context}\nQuestion: {question}\nAnswer:" + + def verbalize(self, sample, candidate): + question = sample.data['question'].strip() + # title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Passage: {context}\nQuestion: {question}\nAnswer: {answer}\n" + + + def encode_sfc(self, sample): + raise NotImplementedError + + def verbalize_sfc(self, sample, candidate): + raise NotImplementedError diff --git a/baselines/mezo/large_models/trainer.py b/baselines/mezo/large_models/trainer.py new file mode 100644 index 0000000..304ec18 --- /dev/null +++ b/baselines/mezo/large_models/trainer.py @@ -0,0 +1,893 @@ +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. +""" + +import contextlib +import functools +import glob +import inspect +import math +import os +import random +import re +import shutil +import sys +import time +import warnings +from collections.abc import Mapping +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union +import copy +from metrics import f1 +import numpy as np + +from tqdm.auto import tqdm +from transformers import Trainer +from sklearn.linear_model import LinearRegression, LogisticRegression, LogisticRegressionCV + +# Integrations must be imported before ML frameworks: +from transformers.integrations import ( # isort: split + default_hp_search_backend, + get_reporting_integration_callbacks, + hp_params, + is_fairscale_available, + is_optuna_available, + is_ray_tune_available, + is_sigopt_available, + is_wandb_available, + run_hp_search_optuna, + run_hp_search_ray, + run_hp_search_sigopt, + run_hp_search_wandb, +) + +import numpy as np +import torch +import torch.distributed as dist +from packaging import version +from torch import nn +from torch.utils.data import DataLoader, Dataset, RandomSampler, SequentialSampler +from torch.utils.data.distributed import DistributedSampler + +from huggingface_hub import Repository + +from transformers import __version__ +from transformers.configuration_utils import PretrainedConfig +from transformers.data.data_collator import DataCollator, DataCollatorWithPadding, default_data_collator +from transformers.debug_utils import DebugOption, DebugUnderflowOverflow +from transformers.deepspeed import deepspeed_init, is_deepspeed_zero3_enabled +from transformers.dependency_versions_check import dep_version_check +from transformers.modelcard import TrainingSummary +from transformers.modeling_utils import PreTrainedModel, load_sharded_checkpoint, unwrap_model +from transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_MAPPING_NAMES +from transformers.optimization import Adafactor, get_scheduler +from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_10, is_torch_less_than_1_11 +from transformers.tokenization_utils_base import PreTrainedTokenizerBase +from transformers.trainer_callback import ( + CallbackHandler, + DefaultFlowCallback, + PrinterCallback, + ProgressCallback, + TrainerCallback, + TrainerControl, + TrainerState, +) +from transformers.trainer_pt_utils import ( + DistributedLengthGroupedSampler, + DistributedSamplerWithLoop, + DistributedTensorGatherer, + IterableDatasetShard, + LabelSmoother, + LengthGroupedSampler, + SequentialDistributedSampler, + ShardSampler, + distributed_broadcast_scalars, + distributed_concat, + find_batch_size, + get_module_class_from_name, + get_parameter_names, + nested_concat, + nested_detach, + nested_numpify, + nested_truncate, + nested_xla_mesh_reduce, + reissue_pt_warnings, +) +from transformers.trainer_utils import ( + PREFIX_CHECKPOINT_DIR, + BestRun, + EvalLoopOutput, + EvalPrediction, + FSDPOption, + HPSearchBackend, + HubStrategy, + IntervalStrategy, + PredictionOutput, + RemoveColumnsCollator, + ShardedDDPOption, + TrainerMemoryTracker, + TrainOutput, + default_compute_objective, + default_hp_space, + denumpify_detensorize, + enable_full_determinism, + find_executable_batch_size, + get_last_checkpoint, + has_length, + number_of_arguments, + seed_worker, + set_seed, + speed_metrics, +) +from transformers.training_args import OptimizerNames, ParallelMode, TrainingArguments +from transformers.utils import ( + CONFIG_NAME, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, + find_labels, + get_full_repo_name, + is_apex_available, + is_datasets_available, + is_in_notebook, + is_ipex_available, + is_sagemaker_dp_enabled, + is_sagemaker_mp_enabled, + is_torch_tensorrt_fx_available, + is_torch_tpu_available, + is_torchdynamo_available, + logging, +) +from transformers.utils.generic import ContextManagers + + +_is_native_cpu_amp_available = is_torch_greater_or_equal_than_1_10 + +DEFAULT_CALLBACKS = [DefaultFlowCallback] +DEFAULT_PROGRESS_CALLBACK = ProgressCallback + +if is_in_notebook(): + from .utils.notebook import NotebookProgressCallback + + DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback + +if is_apex_available(): + from apex import amp + +if is_datasets_available(): + import datasets + +if is_torch_tpu_available(check_device=False): + import torch_xla.core.xla_model as xm + import torch_xla.debug.metrics as met + import torch_xla.distributed.parallel_loader as pl + +if is_fairscale_available(): + dep_version_check("fairscale") + import fairscale + from fairscale.nn.data_parallel import FullyShardedDataParallel as FullyShardedDDP + from fairscale.nn.data_parallel import ShardedDataParallel as ShardedDDP + from fairscale.nn.wrap import auto_wrap + from fairscale.optim import OSS + from fairscale.optim.grad_scaler import ShardedGradScaler + + +if is_sagemaker_mp_enabled(): + import smdistributed.modelparallel.torch as smp + from smdistributed.modelparallel import __version__ as SMP_VERSION + + IS_SAGEMAKER_MP_POST_1_10 = version.parse(SMP_VERSION) >= version.parse("1.10") + + from .trainer_pt_utils import smp_forward_backward, smp_forward_only, smp_gather, smp_nested_concat +else: + IS_SAGEMAKER_MP_POST_1_10 = False + + +if TYPE_CHECKING: + import optuna + +logger = logging.get_logger(__name__) + + +# Name of the files used for checkpointing +TRAINING_ARGS_NAME = "training_args.bin" +TRAINER_STATE_NAME = "trainer_state.json" +OPTIMIZER_NAME = "optimizer.pt" +SCHEDULER_NAME = "scheduler.pt" +SCALER_NAME = "scaler.pt" + + +class OurTrainer(Trainer): + + from transformers.trainer_pt_utils import _get_learning_rate, log_metrics, metrics_format, save_metrics, save_state + + def _inner_training_loop( + self, batch_size=None, args=None, resume_from_checkpoint=None, trial=None, ignore_keys_for_eval=None + ): + """ + We overload the original training loop to add linear probing and MeZO. Search key word "MeZO added" + for those updates. + """ + self._train_batch_size = batch_size + # Data loader and number of training steps + train_dataloader = self.get_train_dataloader() + + # MeZO added: Linear probing + if self.args.linear_probing: + + def _get_token_prediction_layer(model): + if model.config.model_type == "opt": + return model.lm_head + else: + raise NotImplementedError(model.config.model_type) + + def _extract_features(model, *args, **kwargs): + """some magic for getting features pre last layer""" + features = {} + def __hook(model_, input_, output_): + features["features"] = input_[0].detach() + + _get_token_prediction_layer(model).register_forward_hook(__hook) + model.forward(*args, **kwargs) + return features["features"] + + logger.info("Linear probing") + logger.info("Starting to get features for training dataset") + targets = [] + features = [] + with torch.inference_mode(): + for step, inputs in enumerate(tqdm(train_dataloader)): + for k, v in inputs.items(): + if isinstance(v, torch.Tensor): + inputs[k] = v.to(self.model.device) + + feature = _extract_features(self.model, **inputs) + target = inputs["labels"] + + # Shift the target (bc it's autoregressive LM) and add the corresponding part + assert not self.args.train_as_classification and self.args.only_train_option + feature, target = feature[:, :-1], target[:, 1:] + for _i, _len in enumerate(inputs["option_len"]): + features.append(feature[_i, -_len:]) + targets.append(target[_i, -_len:]) + + logger.info("Finished getting features for training dataset") + + features = torch.cat(features, dim=0).cpu().numpy() + targets = torch.cat(targets, dim=0).cpu().numpy() + # Whether to use bias + if self.model.config.model_type in ["opt", "gpt2"]: + use_bias = False + else: + raise NotImplementedError + # Set early stopping + tol = 0.01 if self.args.lp_early_stopping else 1e-4 # 1e-4 is scipy default + max_iter = 1000 if self.args.lp_early_stopping else 5000 + + logger.info("Fitting logistic regression...") + reg = LogisticRegressionCV(max_iter=max_iter, fit_intercept=use_bias, multi_class="multinomial", random_state=0, tol=tol, n_jobs=-1).fit(features, targets) + logger.info("Done") + + logger.info("Assigning weights to model") + decoder = _get_token_prediction_layer(self.model) + coef_torch = torch.tensor(reg.coef_, device=decoder.weight.device, dtype=decoder.weight.dtype) + if use_bias: + bias_torch = torch.tensor(reg.intercept_, device=decoder.weight.device, dtype=decoder.weight.dtype) + if coef_torch.shape[0] == 1: # The regressor only detects two classes + assert len(reg.classes_) == 2 + coef_torch = torch.cat([-coef_torch / 2, coef_torch / 2], dim=0) + if use_bias: + bias_torch = torch.cat([-bias_torch / 2, bias_torch / 2], dim=0) + + for _i, token_id in enumerate(reg.classes_): + decoder.weight.data[token_id] = coef_torch[_i] + if use_bias: + decoder.bias.data[token_id] = bias_torch[_i] + + return None + + # Setting up training control variables: + # number of training epochs: num_train_epochs + # number of training steps per epoch: num_update_steps_per_epoch + # total number of training steps to execute: max_steps + total_train_batch_size = args.train_batch_size * args.gradient_accumulation_steps * args.world_size + + len_dataloader = None + if has_length(train_dataloader): + len_dataloader = len(train_dataloader) + num_update_steps_per_epoch = len_dataloader // args.gradient_accumulation_steps + num_update_steps_per_epoch = max(num_update_steps_per_epoch, 1) + num_examples = self.num_examples(train_dataloader) + if args.max_steps > 0: + max_steps = args.max_steps + num_train_epochs = args.max_steps // num_update_steps_per_epoch + int( + args.max_steps % num_update_steps_per_epoch > 0 + ) + # May be slightly incorrect if the last batch in the training dataloader has a smaller size but it's + # the best we can do. + num_train_samples = args.max_steps * total_train_batch_size + else: + max_steps = math.ceil(args.num_train_epochs * num_update_steps_per_epoch) + num_train_epochs = math.ceil(args.num_train_epochs) + num_train_samples = self.num_examples(train_dataloader) * args.num_train_epochs + elif args.max_steps > 0: # Rely on max_steps when dataloader does not have a working size + max_steps = args.max_steps + # Setting a very large number of epochs so we go as many times as necessary over the iterator. + num_train_epochs = sys.maxsize + num_update_steps_per_epoch = max_steps + num_examples = total_train_batch_size * args.max_steps + num_train_samples = args.max_steps * total_train_batch_size + else: + raise ValueError( + "args.max_steps must be set to a positive value if dataloader does not have a length, was" + f" {args.max_steps}" + ) + + if DebugOption.UNDERFLOW_OVERFLOW in self.args.debug: + if self.args.n_gpu > 1: + # nn.DataParallel(model) replicates the model, creating new variables and module + # references registered here no longer work on other gpus, breaking the module + raise ValueError( + "Currently --debug underflow_overflow is not supported under DP. Please use DDP" + " (torch.distributed.launch)." + ) + else: + debug_overflow = DebugUnderflowOverflow(self.model) # noqa + + delay_optimizer_creation = ( + self.sharded_ddp is not None + and self.sharded_ddp != ShardedDDPOption.SIMPLE + or is_sagemaker_mp_enabled() + or self.fsdp is not None + ) + if args.deepspeed: + deepspeed_engine, optimizer, lr_scheduler = deepspeed_init( + self, num_training_steps=max_steps, resume_from_checkpoint=resume_from_checkpoint + ) + self.model = deepspeed_engine.module + self.model_wrapped = deepspeed_engine + self.deepspeed = deepspeed_engine + self.optimizer = optimizer + self.lr_scheduler = lr_scheduler + elif not delay_optimizer_creation: + self.create_optimizer_and_scheduler(num_training_steps=max_steps) + + self.state = TrainerState() + self.state.is_hyper_param_search = trial is not None + + # Activate gradient checkpointing if needed + if args.gradient_checkpointing: + self.model.gradient_checkpointing_enable() + + model = self._wrap_model(self.model_wrapped) + + if is_sagemaker_mp_enabled() and resume_from_checkpoint is not None: + self._load_from_checkpoint(resume_from_checkpoint, model) + + # for the rest of this function `model` is the outside model, whether it was wrapped or not + if model is not self.model: + self.model_wrapped = model + + if delay_optimizer_creation: + self.create_optimizer_and_scheduler(num_training_steps=max_steps) + + # Check if saved optimizer or scheduler states exist + self._load_optimizer_and_scheduler(resume_from_checkpoint) + + # important: at this point: + # self.model is the Transformers Model + # self.model_wrapped is DDP(Transformers Model), Deepspeed(Transformers Model), etc. + + # Train! + logger.info("***** Running training *****") + logger.info(f" Num examples = {num_examples}") + logger.info(f" Num Epochs = {num_train_epochs}") + logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") + logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_train_batch_size}") + logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") + logger.info(f" Total optimization steps = {max_steps}") + logger.info( + f" Number of trainable parameters = {sum(p.numel() for p in model.parameters() if p.requires_grad)}" + ) + + self.state.epoch = 0 + start_time = time.time() + epochs_trained = 0 + steps_trained_in_current_epoch = 0 + steps_trained_progress_bar = None + + # Check if continuing training from a checkpoint + if resume_from_checkpoint is not None and os.path.isfile( + os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME) + ): + self.state = TrainerState.load_from_json(os.path.join(resume_from_checkpoint, TRAINER_STATE_NAME)) + epochs_trained = self.state.global_step // num_update_steps_per_epoch + if not args.ignore_data_skip: + steps_trained_in_current_epoch = self.state.global_step % (num_update_steps_per_epoch) + steps_trained_in_current_epoch *= args.gradient_accumulation_steps + else: + steps_trained_in_current_epoch = 0 + + logger.info(" Continuing training from checkpoint, will skip to saved global_step") + logger.info(f" Continuing training from epoch {epochs_trained}") + logger.info(f" Continuing training from global step {self.state.global_step}") + if not args.ignore_data_skip: + logger.info( + f" Will skip the first {epochs_trained} epochs then the first {steps_trained_in_current_epoch} " + "batches in the first epoch. If this takes a lot of time, you can add the `--ignore_data_skip` " + "flag to your launch command, but you will resume the training on data already seen by your model." + ) + if self.is_local_process_zero() and not args.disable_tqdm: + steps_trained_progress_bar = tqdm(total=steps_trained_in_current_epoch) + steps_trained_progress_bar.set_description("Skipping the first batches") + + # Update the references + self.callback_handler.model = self.model + self.callback_handler.optimizer = self.optimizer + self.callback_handler.lr_scheduler = self.lr_scheduler + self.callback_handler.train_dataloader = train_dataloader + if self.hp_name is not None and self._trial is not None: + # use self._trial because the SigOpt/Optuna hpo only call `_hp_search_setup(trial)` instead of passing trial + # parameter to Train when using DDP. + self.state.trial_name = self.hp_name(self._trial) + if trial is not None: + assignments = trial.assignments if self.hp_search_backend == HPSearchBackend.SIGOPT else trial + self.state.trial_params = hp_params(assignments) + else: + self.state.trial_params = None + # This should be the same if the state has been saved but in case the training arguments changed, it's safer + # to set this after the load. + self.state.max_steps = max_steps + self.state.num_train_epochs = num_train_epochs + self.state.is_local_process_zero = self.is_local_process_zero() + self.state.is_world_process_zero = self.is_world_process_zero() + + # tr_loss is a tensor to avoid synchronization of TPUs through .item() + tr_loss = torch.tensor(0.0).to(args.device) + # _total_loss_scalar is updated everytime .item() has to be called on tr_loss and stores the sum of all losses + self._total_loss_scalar = 0.0 + self._globalstep_last_logged = self.state.global_step + model.zero_grad() + + self.control = self.callback_handler.on_train_begin(args, self.state, self.control) + + # Skip the first epochs_trained epochs to get the random state of the dataloader at the right point. + if not args.ignore_data_skip: + for epoch in range(epochs_trained): + is_random_sampler = hasattr(train_dataloader, "sampler") and isinstance( + train_dataloader.sampler, RandomSampler + ) + if is_torch_less_than_1_11 or not is_random_sampler: + # We just need to begin an iteration to create the randomization of the sampler. + # That was before PyTorch 1.11 however... + for _ in train_dataloader: + break + else: + # Otherwise we need to call the whooooole sampler cause there is some random operation added + # AT THE VERY END! + _ = list(train_dataloader.sampler) + + for epoch in range(epochs_trained, num_train_epochs): + if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): + train_dataloader.sampler.set_epoch(epoch) + elif hasattr(train_dataloader, "dataset") and isinstance(train_dataloader.dataset, IterableDatasetShard): + train_dataloader.dataset.set_epoch(epoch) + + if is_torch_tpu_available(): + parallel_loader = pl.ParallelLoader(train_dataloader, [args.device]).per_device_loader(args.device) + epoch_iterator = parallel_loader + else: + epoch_iterator = train_dataloader + + # Reset the past mems state at the beginning of each epoch if necessary. + if args.past_index >= 0: + self._past = None + + steps_in_epoch = ( + len(epoch_iterator) + if len_dataloader is not None + else args.max_steps * args.gradient_accumulation_steps + ) + self.control = self.callback_handler.on_epoch_begin(args, self.state, self.control) + + if epoch == epochs_trained and resume_from_checkpoint is not None and steps_trained_in_current_epoch == 0: + self._load_rng_state(resume_from_checkpoint) + + step = -1 + for step, inputs in enumerate(epoch_iterator): + + # Skip past any already trained steps if resuming training + if steps_trained_in_current_epoch > 0: + steps_trained_in_current_epoch -= 1 + if steps_trained_progress_bar is not None: + steps_trained_progress_bar.update(1) + if steps_trained_in_current_epoch == 0: + self._load_rng_state(resume_from_checkpoint) + continue + elif steps_trained_progress_bar is not None: + steps_trained_progress_bar.close() + steps_trained_progress_bar = None + + if step % args.gradient_accumulation_steps == 0: + self.control = self.callback_handler.on_step_begin(args, self.state, self.control) + + # MeZO added: estimate gradient + if args.trainer == "zo": + tr_loss_step = self.zo_step(model, inputs) + else: + if ( + ((step + 1) % args.gradient_accumulation_steps != 0) + and args.local_rank != -1 + and args._no_sync_in_gradient_accumulation + ): + # Avoid unnecessary DDP synchronization since there will be no backward pass on this example. + with model.no_sync(): + tr_loss_step = self.training_step(model, inputs) + else: + tr_loss_step = self.training_step(model, inputs) + + if ( + args.logging_nan_inf_filter + and not is_torch_tpu_available() + and (torch.isnan(tr_loss_step) or torch.isinf(tr_loss_step)) + ): + # if loss is nan or inf simply add the average of previous logged losses + tr_loss += tr_loss / (1 + self.state.global_step - self._globalstep_last_logged) + else: + tr_loss += tr_loss_step + + self.current_flos += float(self.floating_point_ops(inputs)) + + # Optimizer step for deepspeed must be called on every step regardless of the value of gradient_accumulation_steps + if self.deepspeed: + self.deepspeed.step() + + if (step + 1) % args.gradient_accumulation_steps == 0 or ( + # last step in epoch but step is always smaller than gradient_accumulation_steps + steps_in_epoch <= args.gradient_accumulation_steps + and (step + 1) == steps_in_epoch + ): + # MeZO added: update model with the estimated gradient + if args.trainer == "zo": + self.zo_update(model) + else: + # Gradient clipping + if args.max_grad_norm is not None and args.max_grad_norm > 0 and not self.deepspeed: + # deepspeed does its own clipping + + if self.do_grad_scaling: + # Reduce gradients first for XLA + if is_torch_tpu_available(): + gradients = xm._fetch_gradients(self.optimizer) + xm.all_reduce("sum", gradients, scale=1.0 / xm.xrt_world_size()) + # AMP: gradients need unscaling + self.scaler.unscale_(self.optimizer) + + if is_sagemaker_mp_enabled() and args.fp16: + self.optimizer.clip_master_grads(args.max_grad_norm) + elif hasattr(self.optimizer, "clip_grad_norm"): + # Some optimizers (like the sharded optimizer) have a specific way to do gradient clipping + self.optimizer.clip_grad_norm(args.max_grad_norm) + elif hasattr(model, "clip_grad_norm_"): + # Some models (like FullyShardedDDP) have a specific way to do gradient clipping + model.clip_grad_norm_(args.max_grad_norm) + else: + # Revert to normal clipping otherwise, handling Apex or full precision + nn.utils.clip_grad_norm_( + amp.master_params(self.optimizer) if self.use_apex else model.parameters(), + args.max_grad_norm, + ) + + # Optimizer step + optimizer_was_run = True + if self.deepspeed: + pass # called outside the loop + elif is_torch_tpu_available(): + if self.do_grad_scaling: + self.scaler.step(self.optimizer) + self.scaler.update() + else: + xm.optimizer_step(self.optimizer) + elif self.do_grad_scaling: + scale_before = self.scaler.get_scale() + self.scaler.step(self.optimizer) + self.scaler.update() + scale_after = self.scaler.get_scale() + optimizer_was_run = scale_before <= scale_after + else: + self.optimizer.step() + + if optimizer_was_run and not self.deepspeed: + self.lr_scheduler.step() + model.zero_grad() + + self.state.global_step += 1 + self.state.epoch = epoch + (step + 1) / steps_in_epoch + self.control = self.callback_handler.on_step_end(args, self.state, self.control) + + self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval) + else: + self.control = self.callback_handler.on_substep_end(args, self.state, self.control) + + if self.control.should_epoch_stop or self.control.should_training_stop: + break + if step < 0: + logger.warning( + "There seems to be not a single sample in your epoch_iterator, stopping training at step" + f" {self.state.global_step}! This is expected if you're using an IterableDataset and set" + f" num_steps ({max_steps}) higher than the number of available samples." + ) + self.control.should_training_stop = True + + self.control = self.callback_handler.on_epoch_end(args, self.state, self.control) + self._maybe_log_save_evaluate(tr_loss, model, trial, epoch, ignore_keys_for_eval) + + if DebugOption.TPU_METRICS_DEBUG in self.args.debug: + if is_torch_tpu_available(): + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + else: + logger.warning( + "You enabled PyTorch/XLA debug metrics but you don't have a TPU " + "configured. Check your training configuration if this is unexpected." + ) + if self.control.should_training_stop: + break + + if args.past_index and hasattr(self, "_past"): + # Clean the state at the end of training + delattr(self, "_past") + + logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") + if args.load_best_model_at_end and self.state.best_model_checkpoint is not None: + # Wait for everyone to get here so we are sur the model has been saved by process 0. + if is_torch_tpu_available(): + xm.rendezvous("load_best_model_at_end") + elif args.local_rank != -1: + dist.barrier() + elif is_sagemaker_mp_enabled(): + smp.barrier() + + self._load_best_model() + + # add remaining tr_loss + self._total_loss_scalar += tr_loss.item() + train_loss = self._total_loss_scalar / self.state.global_step + + metrics = speed_metrics("train", start_time, num_samples=num_train_samples, num_steps=self.state.max_steps) + self.store_flos() + metrics["total_flos"] = self.state.total_flos + metrics["train_loss"] = train_loss + + self.is_in_train = False + + self._memory_tracker.stop_and_update_metrics(metrics) + + self.log(metrics) + + run_dir = self._get_output_dir(trial) + checkpoints_sorted = self._sorted_checkpoints(use_mtime=False, output_dir=run_dir) + + # Delete the last checkpoint when save_total_limit=1 if it's different from the best checkpoint. + if self.state.best_model_checkpoint is not None and self.args.save_total_limit == 1: + for checkpoint in checkpoints_sorted: + if checkpoint != self.state.best_model_checkpoint: + logger.info(f"Deleting older checkpoint [{checkpoint}] due to args.save_total_limit") + shutil.rmtree(checkpoint) + + self.control = self.callback_handler.on_train_end(args, self.state, self.control) + + return TrainOutput(self.state.global_step, train_loss, metrics) + + + ############## MeZO ############## + + + def zo_perturb_parameters(self, random_seed=None, scaling_factor=1): + """ + Perturb the parameters with random vector z. + Input: + - random_seed: random seed for MeZO in-place perturbation (if it's None, we will use self.zo_random_seed) + - scaling_factor: theta = theta + scaling_factor * z * eps + """ + + # Set the random seed to ensure that we sample the same z for perturbation/update + torch.manual_seed(random_seed if random_seed is not None else self.zo_random_seed) + + for name, param in self.named_parameters_to_optim: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * self.args.zo_eps + + + def zo_forward(self, model, inputs): + """ + Get (no gradient) loss from the model. Dropout is turned off too. + """ + model.eval() + if self.args.non_diff: + # Non-differentiable objective (may require autoregressive generation) + return self.zo_forward_nondiff(model, inputs) + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + # Warning: this is copied from the original Huggingface Trainer. Untested. + loss = loss.mean() # mean() to average on multi-gpu parallel training + return loss.detach() + + + def zo_forward_nondiff(self, model, inputs): + """ + Get (no gradient) non-diffiable loss from the model. + """ + model.eval() + assert self.args.task_name == "SQuAD", "Non differentiable objective only supports SQuAD for now." + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + args = self.args + outputs = self.model.generate( + inputs["input_ids"], do_sample=args.sampling, temperature=args.temperature, + num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - inputs["input_ids"].size(1)), + num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id], + ) + output_text = [] + for i in range(len(outputs)): + output_text.append(self.tokenizer.decode(outputs[i][inputs["input_ids"].size(1):], skip_special_tokens=True).strip()) + f1s = [f1(output_text[i], inputs['gold'][i]) for i in range(len(output_text))] + + return -torch.tensor(np.mean(f1s), dtype=torch.float32) + + + def zo_step(self, model, inputs): + """ + Estimate gradient by MeZO. Return the loss from f(theta + z) + """ + args = self.args + + # What parameters to optimize + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if param.requires_grad: + self.named_parameters_to_optim.append((name, param)) + + # Sample the random seed for sampling z + self.zo_random_seed = np.random.randint(1000000000) + + # First function evaluation + self.zo_perturb_parameters(scaling_factor=1) + loss1 = self.zo_forward(model, inputs) + + # Second function evaluation + self.zo_perturb_parameters(scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + + self.projected_grad = ((loss1 - loss2) / (2 * self.args.zo_eps)).item() + + # No gradient accumulation support + assert self.args.gradient_accumulation_steps == 1 + + # Reset model back to its parameters at start of step + self.zo_perturb_parameters(scaling_factor=1) + + return loss1 + + + def zo_update(self, model): + """ + Update the parameters with the estimated gradients. + """ + args = self.args + + # Reset the random seed for sampling zs + torch.manual_seed(self.zo_random_seed) + + for name, param in self.named_parameters_to_optim: + # Resample z + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + if "bias" not in name and "layer_norm" not in name and "layernorm" not in name: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * z + args.weight_decay * param.data) + else: + param.data = param.data - self._get_learning_rate() * (self.projected_grad * z) + + self.lr_scheduler.step() + + + ############## Misc overload functions ############## + + + def _set_signature_columns_if_needed(self): + """ + We overload this function for non-differentiable objective training to pass "gold" -- the gold text for the task + """ + if self._signature_columns is None: + # Inspect model forward signature to keep only the arguments it accepts. + signature = inspect.signature(self.model.forward) + self._signature_columns = list(signature.parameters.keys()) + # Labels may be named label or label_ids, the default data collator handles that. + self._signature_columns += list(set(["label", "label_ids"] + self.label_names)) + self._signature_columns += ["gold"] + + + def save_model(self, output_dir: Optional[str] = None, _internal_call: bool = False): + """ + We overload this function to fix an FSDP saving bug (before fix, it will likely cause OOM) + """ + + if output_dir is None: + output_dir = self.args.output_dir + + if is_torch_tpu_available(): + self._save_tpu(output_dir) + elif is_sagemaker_mp_enabled(): + # Calling the state_dict needs to be done on the wrapped model and on all processes. + os.makedirs(output_dir, exist_ok=True) + state_dict = self.model_wrapped.state_dict() + if self.args.should_save: + self._save(output_dir, state_dict=state_dict) + if IS_SAGEMAKER_MP_POST_1_10: + # 'user_content.pt' indicates model state_dict saved with smp >= 1.10 + Path(os.path.join(output_dir, "user_content.pt")).touch() + elif ( + ShardedDDPOption.ZERO_DP_2 in self.args.sharded_ddp + or ShardedDDPOption.ZERO_DP_3 in self.args.sharded_ddp + or self.fsdp is not None + ): + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP, StateDictType, FullStateDictConfig + full_state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) + + # Fix the FSDP loading bug + with FSDP.state_dict_type(self.model, StateDictType.FULL_STATE_DICT, full_state_dict_config): + state_dict = self.model.state_dict() + # state_dict = self.model.state_dict() + + if self.args.should_save: + self._save(output_dir, state_dict=state_dict) + elif self.deepspeed: + # this takes care of everything as long as we aren't under zero3 + if self.args.should_save: + self._save(output_dir) + + if is_deepspeed_zero3_enabled(): + # It's too complicated to try to override different places where the weights dump gets + # saved, so since under zero3 the file is bogus, simply delete it. The user should + # either user deepspeed checkpoint to resume or to recover full weights use + # zero_to_fp32.py stored in the checkpoint. + if self.args.should_save: + file = os.path.join(output_dir, WEIGHTS_NAME) + if os.path.isfile(file): + # logger.info(f"deepspeed zero3: removing {file}, see zero_to_fp32.py to recover weights") + os.remove(file) + + # now save the real model if stage3_gather_16bit_weights_on_model_save=True + # if false it will not be saved. + # This must be called on all ranks + if not self.deepspeed.save_16bit_model(output_dir, WEIGHTS_NAME): + logger.warning( + "deepspeed.save_16bit_model didn't save the model, since" + " stage3_gather_16bit_weights_on_model_save=false. Saving the full checkpoint instead, use" + " zero_to_fp32.py to recover weights" + ) + self.deepspeed.save_checkpoint(output_dir) + + elif self.args.should_save: + self._save(output_dir) + + # Push to the Hub when `save_model` is called by the user. + if self.args.push_to_hub and not _internal_call: + self.push_to_hub(commit_message="Model save") diff --git a/baselines/mezo/large_models/utils.py b/baselines/mezo/large_models/utils.py new file mode 100644 index 0000000..317c039 --- /dev/null +++ b/baselines/mezo/large_models/utils.py @@ -0,0 +1,355 @@ +import json +import os +import contextlib +from typing import Optional, Union +import numpy as np +from dataclasses import dataclass, is_dataclass, asdict +import logging +import time +from torch.nn import CrossEntropyLoss +import torch.nn.functional as F +from transformers.modeling_outputs import CausalLMOutputWithPast +import torch +from transformers.utils import PaddingStrategy +from transformers import PreTrainedTokenizerBase +from transformers.data.data_collator import DataCollatorMixin +import transformers +from typing import Optional, Union, List, Dict, Any +import signal +from subprocess import call +from collections.abc import Mapping +from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union +InputDataClass = NewType("InputDataClass", Any) +from dataclasses import dataclass +from transformers.tokenization_utils_base import PreTrainedTokenizerBase + + + +logger = logging.getLogger(__name__) + + +def forward_wrap_with_option_len(self, input_ids=None, labels=None, option_len=None, num_options=None, return_dict=None, **kwargs): + """ + This is to replace the original forward function of Transformer models to enable: + (1) Partial target sequence: loss will only be calculated on part of the sequence + (2) Classification-style training: a classification loss (CE) will be calculated over several options + Input: + - input_ids, labels: same as the original forward function + - option_len: a list of int indicating the option lengths, and loss will be calculated only on the + last option_len tokens + - num_options: a list of int indicating the number of options for each example (this will be #label + words for classification tasks and #choices for multiple choice tasks), and a classification loss + will be calculated. + """ + outputs = self.original_forward(input_ids=input_ids, **kwargs) + if labels is None: + return outputs + logits = outputs.logits + + loss = None + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + # Here we use input_ids (which should always = labels) bc sometimes labels are correct candidate IDs + shift_labels = torch.clone(input_ids)[..., 1:].contiguous() + shift_labels[shift_labels == self.config.pad_token_id] = -100 + + # Apply option len (do not calculate loss on the non-option part) + for _i, _len in enumerate(option_len): + shift_labels[_i, :-_len] = -100 + + # Calculate the loss + loss_fct = CrossEntropyLoss(ignore_index=-100) + if num_options is not None: + # Train as a classification tasks + log_probs = F.log_softmax(shift_logits, dim=-1) + mask = shift_labels != -100 # Option part + shift_labels[~mask] = 0 # So that it doesn't mess up with indexing + + selected_log_probs = torch.gather(log_probs, dim=-1, index=shift_labels.unsqueeze(-1)).squeeze(-1) # (bsz x num_options, len) + selected_log_probs = (selected_log_probs * mask).sum(-1) / mask.sum(-1) # (bsz x num_options) + + if any([x != num_options[0] for x in num_options]): + # Multi choice tasks with different number of options + loss = 0 + start_id = 0 + count = 0 + while start_id < len(num_options): + end_id = start_id + num_options[start_id] + _logits = selected_log_probs[start_id:end_id].unsqueeze(0) # (1, num_options) + _labels = labels[start_id:end_id][0].unsqueeze(0) # (1) + loss = loss_fct(_logits, _labels) + loss + count += 1 + start_id = end_id + loss = loss / count + else: + num_options = num_options[0] + selected_log_probs = selected_log_probs.view(-1, num_options) # (bsz, num_options) + labels = labels.view(-1, num_options)[:, 0] # Labels repeat so we only take the first one + loss = loss_fct(selected_log_probs, labels) + else: + loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +def encode_prompt(task, template, train_samples, eval_sample, tokenizer, max_length, sfc=False, icl_sfc=False, generation=False, generation_with_gold=False, max_new_tokens=None): + """ + Encode prompts for eval_sample + Input: + - task, template: task and template class + - train_samples, eval_sample: demonstrations and the actual sample + - tokenizer, max_length: tokenizer and max length + - sfc: generate prompts for calibration (surface form competition; https://arxiv.org/abs/2104.08315) + - icl_sfc: generate prompts for ICL version calibration + - generation: whether it is an generation task + - generation_with_gold: whether to include the generation-task gold answers (for training) + - max_new_tokens: max number of new tokens to generate so that we can save enough space + (only for generation tasks) + Output: + - encodings: a list of N lists of tokens. N is the number of options for classification/multiple-choice. + - option_lens: a list of N integers indicating the number of option tokens. + """ + + # Demonstrations for ICL + train_prompts = [template.verbalize(sample, sample.correct_candidate).strip() for sample in train_samples] + train_prompts = task.train_sep.join(train_prompts).strip() + + # sfc or icl_sfc indicates that this example is used for calibration + if sfc or icl_sfc: + encode_fn = template.encode_sfc; verbalize_fn = template.verbalize_sfc + else: + encode_fn = template.encode; verbalize_fn = template.verbalize + + unverbalized_eval_prompt = encode_fn(eval_sample).strip(' ') + if not generation: + # We generate one prompt for each candidate (different classes in classification) + # or different choices in multiple-choice tasks + verbalized_eval_prompts = [verbalize_fn(eval_sample, cand).strip(' ') for cand in eval_sample.candidates] + unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt)) + option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts] + + if sfc: + # Without demonstrations + final_prompts = verbalized_eval_prompts + else: + # With demonstrations + final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts] + else: + assert not sfc and not icl_sfc, "Generation tasks do not support SFC" + if generation_with_gold: + verbalized_eval_prompts = [verbalize_fn(eval_sample, eval_sample.correct_candidate)] + unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt)) + option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts] + final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts] + else: + option_lens = [0] + final_prompts = [(train_prompts + task.train_sep + unverbalized_eval_prompt).lstrip().strip(' ')] + + # Tokenize + encodings = [tokenizer.encode(final_prompt) for final_prompt in final_prompts] + + # Truncate (left truncate as demonstrations are less important) + if generation and max_new_tokens is not None: + max_length = max_length - max_new_tokens + + if any([len(encoding) > max_length for encoding in encodings]): + logger.warn("Exceed max length") + if tokenizer.add_bos_token: + encodings = [encoding[0:1] + encoding[1:][-(max_length-1):] for encoding in encodings] + else: + encodings = [encoding[-max_length:] for encoding in encodings] + + return encodings, option_lens + + + +@dataclass +class ICLCollator: + """ + Collator for ICL + """ + tokenizer: PreTrainedTokenizerBase + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + if not isinstance(features[0], Mapping): + features = [vars(f) for f in features] + first = features[0] + batch = {} + + pad_id = self.tokenizer.pad_token_id + + pad_ids = {"input_ids": pad_id, "attention_mask": 0, "sfc_input_ids": pad_id, "sfc_attention_mask": 0, "labels": pad_id} + for key in first: + pp = pad_ids[key] + lens = [len(f[key]) for f in features] + max_len = max(lens) + feature = np.stack([np.pad(f[key], (0, max_len - lens[i]), "constant", constant_values=(0, pp)) for i, f in enumerate(features)]) + padded_feature = torch.from_numpy(feature).long() + batch[key] = padded_feature + + return batch + + +@dataclass +class DataCollatorWithPaddingAndNesting: + """ + Collator for training + """ + + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str, PaddingStrategy] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + return_tensors: str = "pt" + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + features = [ff for f in features for ff in f] + batch = self.tokenizer.pad( + features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors=self.return_tensors, + ) + if "label" in batch: + batch["labels"] = batch["label"] + del batch["label"] + if "label_ids" in batch: + batch["labels"] = batch["label_ids"] + del batch["label_ids"] + return batch + + +@dataclass +class NondiffCollator(DataCollatorMixin): + """ + Collator for non-differentiable objectives + """ + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str, PaddingStrategy] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + label_pad_token_id: int = -100 + return_tensors: str = "pt" + + def torch_call(self, features): + import torch + + label_name = "label" if "label" in features[0].keys() else "labels" + labels = [feature[label_name] for feature in features] if label_name in features[0].keys() else None + + no_labels_features = [{k: v for k, v in feature.items() if k != label_name and k != "gold"} for feature in features] + + batch = self.tokenizer.pad( + no_labels_features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors="pt", + ) + + if labels is None: + return batch + + sequence_length = batch["input_ids"].shape[1] + padding_side = self.tokenizer.padding_side + + def to_list(tensor_or_iterable): + if isinstance(tensor_or_iterable, torch.Tensor): + return tensor_or_iterable.tolist() + return list(tensor_or_iterable) + + if padding_side == "right": + batch[label_name] = [ + to_list(label) + [self.label_pad_token_id] * (sequence_length - len(label)) for label in labels + ] + else: + batch[label_name] = [ + [self.label_pad_token_id] * (sequence_length - len(label)) + to_list(label) for label in labels + ] + + batch[label_name] = torch.tensor(batch[label_name], dtype=torch.int64) + if "gold" in features[0]: + batch["gold"] = [feature["gold"] for feature in features] + + return batch + + +class SIGUSR1Callback(transformers.TrainerCallback): + """ + This callback is used to save the model when a SIGUSR1 signal is received + (SLURM stop signal or a keyboard interruption signal). + """ + + def __init__(self) -> None: + super().__init__() + self.signal_received = False + signal.signal(signal.SIGUSR1, self.handle_signal) + signal.signal(signal.SIGINT, self.handle_signal) + logger.warn("Handler registered") + + def handle_signal(self, signum, frame): + self.signal_received = True + logger.warn("Signal received") + + def on_step_end(self, args, state, control, **kwargs): + if self.signal_received: + control.should_save = True + control.should_training_stop = True + + def on_train_end(self, args, state, control, **kwargs): + if self.signal_received: + exit(0) + + +@dataclass +class Prediction: + correct_candidate: Union[int, str] + predicted_candidate: Union[int, str] + + +@contextlib.contextmanager +def count_time(name): + logger.info("%s..." % name) + start_time = time.time() + try: + yield + finally: + logger.info("Done with %.2fs" % (time.time() - start_time)) + + +@contextlib.contextmanager +def temp_seed(seed): + state = np.random.get_state() + np.random.seed(seed) + try: + yield + finally: + np.random.set_state(state) + + +class EnhancedJSONEncoder(json.JSONEncoder): + def default(self, o): + if is_dataclass(o): + return asdict(o) + return super().default(o) + + +def write_predictions_to_file(final_preds, output): + with open(output, "w") as f: + for pred in final_preds: + f.write(json.dumps(pred, cls=EnhancedJSONEncoder) + "\n") + + +def write_metrics_to_file(metrics, output): + json.dump(metrics, open(output, "w"), cls=EnhancedJSONEncoder, indent=4) \ No newline at end of file diff --git a/baselines/mezo/medium_models/README.md b/baselines/mezo/medium_models/README.md new file mode 100644 index 0000000..6d15b39 --- /dev/null +++ b/baselines/mezo/medium_models/README.md @@ -0,0 +1,81 @@ +# MeZO on Medium-sized Masked Language Models + +This part of the code is for MeZO experiments on RoBERTa-large. It is based on [LM-Kernel-FT](https://github.com/princeton-nlp/LM-Kernel-FT) and [LM-BFF](https://github.com/princeton-nlp/LM-BFF). + +## Installation + +Please install the latest versions of PyTorch (`pytorch` following [https://pytorch.org](https://pytorch.org)) and Transformers (`transformers`). This code is tested on `torch==2.1.0.dev20230514+cu118` and `transformers==4.28.1` with Python 3.9.7, but should work with older/later versions of these packages too. + +## Prepare the data + +We pack the datasets [here](https://nlp.cs.princeton.edu/projects/lm-bff/datasets.tar). Please download it and extract the files to `./data/original`, or run the following commands: + +```bash +cd data +bash download_dataset.sh +``` + +Then use the following command (in the `medium_models` folder) to generate the data we need: + +```bash +for K in 16 512; do + # Generate k-shot splits for seeds 13,21,42,87,100 with a maximum of 1k test examples in data/k-shot-1k-test, + # where k is the number of training/validation examples per label + python tools/generate_k_shot_data.py --mode k-shot-1k-test --k $K +done +``` + +See `tools/generate_k_shot_data.py` for more options. For results in the paper, we use the default options: we take `K=16` and `K=512` and take 5 different seeds of 13, 21, 42, 87, 100. The few-shot data will be generated to `data/k-shot-1k-test`. In the directory of each dataset, there will be folders named as `$K-$SEED` indicating different dataset samples. + +## Usage + +Use `run.py` for all functions and refer to `run.py` for the usage of all arguments. +```bash +python run.py {ARGUMENTS} +``` + +To reproduce our results in the paper, we also provide two example files `finetune.sh` (for all fine-tuning experiments) and `mezo.sh` (for all MeZO experiments). You can run them directly with the following commands (we use the following six datasets in our experiments -- `SST-2`, `sst-5`, `SNLI`, `MNLI`, `RTE`, and `trec`): +```bash +# Adam fine-tuning +TASK=SST-2 K=16 SEED=42 BS=8 LR=1e-5 MODEL=roberta-large bash finetune.sh + +# Adam fine-tuning + prefix-tuning +TASK=SST-2 K=16 SEED=42 BS=8 LR=1e-2 MODEL=roberta-large EXTRA_TAG=prefix bash finetune.sh --prefix_tuning --num_prefix 5 --no_reparam --prefix_init_by_real_act + +# Adam fine-tuning + LoRA +TASK=SST-2 K=16 SEED=42 BS=8 LR=1e-4 MODEL=roberta-large EXTRA_TAG=lora bash finetune.sh --apply_lora --lora_r 8 --lora_alpha 16 + +# MeZO +TASK=SST-2 K=16 SEED=42 BS=64 LR=1e-6 EPS=1e-3 MODEL=roberta-large bash mezo.sh + +# MeZO + prefix-tuning +TASK=SST-2 K=16 SEED=42 BS=64 LR=1e-2 EPS=1e-1 MODEL=roberta-large EXTRA_TAG=prefix bash mezo.sh --prefix_tuning --num_prefix 5 --no_reparam --prefix_init_by_real_act + +# MeZO + LoRA +TASK=SST-2 K=16 SEED=42 BS=64 LR=1e-4 EPS=1e-3 MODEL=roberta-large EXTRA_TAG=lora bash mezo.sh --apply_lora --lora_r 8 --lora_alpha 16 +``` +You can designate different hyperparameters by passing different environment variables as shown above. You can also directly add arguments at the end of the command to override the default ones. For all the hyperparameters you can control via environment variables, please refer to `finetune.sh` and `mezo.sh`. For the hyperparameters we used in our experiments, please refer to Appendix D of our paper. + + +## Gather results + +All the results will be stored in `./log`. To analyze the results (for example, examine the grid search), use the following command +```bash +python tools/gather_result.py --condition "{'tag': 'k16-roberta-large-ft', 'task_name': 'sst-2'}" +``` + +Then the program will find all the trials that satisfy the condition in `./log`, and print the mean/std of the final results. Note that the task names are all lower-cased here. + + +## Ablations + +RoBERTa-large models can be fine-tuned on most single GPUs, so we did not yet implement all of the memory-efficient ZO variants discussed in Appendix B. For now, if you want to run ablations other ZO ablations, you can add the flag `--zero_order_use_trainer_optim`, which will store the ZO gradients in the `param.grad` buffer and then use a PyTorch optimizer as usual. This causes the total memory consumption for ZO to be twice that of inference, which is still substantially less than that of backpropagation. The ablations can then be run with the additional following flags: +- ZO-Adam: `--optimizer "adam"` +- ZO-Momentum: `--momentum ` +- $n$-SPSA with $n>1$: `--zero_order_sample ` and you can add a linear or constant scheduler on it with `--zero_order_sample_scheduler {"linear", "constant"}` +- No prompt: `--few_shot_type finetune` + +Appendix B discusses variants of ZO that modify the expectation and the variance. To run those one can use the following flags. +- Modify variance: `--zo_variant {"grad_norm", "param_norm"}` +- Recompute the control variate at the start of each epoch: `--recmopute_norms` +- Modify expectation: `--change_grad_estimate` diff --git a/baselines/mezo/medium_models/run.py b/baselines/mezo/medium_models/run.py new file mode 100644 index 0000000..c7afccd --- /dev/null +++ b/baselines/mezo/medium_models/run.py @@ -0,0 +1,1126 @@ +"""Finetuning the library models for sequence classification on GLUE.""" + +import dataclasses +import logging +import os +import sys +from dataclasses import dataclass, field +from typing import Callable, Dict, Optional, Union, List +import torch +import torch.nn.functional as F + +import numpy as np + +from transformers import AutoConfig, AutoModelForSequenceClassification, AutoTokenizer, EvalPrediction, PreTrainedTokenizerBase +from src.modeling_roberta import RobertaConfig +from src.modeling_opt import OPTConfig +from transformers import GlueDataTrainingArguments as DataTrainingArguments +from transformers import HfArgumentParser, TrainingArguments, set_seed + +from src.linearhead_trainer import LinearHeadTrainer +from src.dataset import FewShotDataset, OurInputFeatures +from src.models import MODEL_TYPES, resize_token_type_embeddings, convert_opt_model +from src.trainer import Trainer +from src.processors import processors_mapping, num_labels_mapping, output_modes_mapping, compute_metrics_mapping, bound_mapping + +from filelock import FileLock +from datetime import datetime + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. + """ + model_name_or_path: str = field( + metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} + ) + config_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} + ) + tokenizer_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} + ) + cache_dir: Optional[str] = field( + default=None, metadata={"help": "Where do you want to store the pretrained models downloaded from s3"} + ) + # Few-shot type + # - finetune: standard fine-tuning + # - prompt: prompt-based fine-tuning + # - prompt-demo: prompt-based fine-tuning with demonstrations + few_shot_type: str = field( + default='prompt-demo', + metadata={"help": "Few-shot learning model type. Choice: finetune, prompt, prompt-demo"} + ) + + # Only for BERT-type model + random_segment: bool = field( + default=False, + metadata={"help": "Whether to reinitialize the token type embeddings (only for BERT)."} + ) + l2_loss: bool = field( + default=False, + metadata={"help": "Whether to use L2 loss (only makes a difference in standard FT)."} + ) + use_task_word: bool = field( + default=False, + metadata={'help': 'uses the task words MLM logit for kernel computation'} + ) + + # LoRA arguments: only for BERT-type model + apply_lora: bool = field( + default=False, + metadata={'help': 'use LoRA for finetuning'} + ) + lora_alpha: int = field( + default=None, + metadata={'help': 'initialization scale for one of the low rank matrices in lora'} + ) + lora_r: int = field( + default=None, + metadata={'help': 'inner rank for lora matrices'} + ) + + # Calibration + sfc: bool = field( + default=False, + metadata={"help": "Whether to use surface form calibration."} + ) + + icl_sfc: bool = field( + default=False, + metadata={"help": "Use in-context learning demos in sfc."} + ) + + +@dataclass +class DynamicDataTrainingArguments(DataTrainingArguments): + """ + Arguments for dynamic training. + """ + num_k: Optional[int] = field( + default=16, + metadata={"help": "Number of training instances per class"} + ) + + num_sample: Optional[int] = field( + default=16, + metadata={"help": "Number of samples (for inference) in fine-tuning with demonstrations"} + ) + + num_demo: Optional[int] = field( + default=1, + metadata={"help": "Number of demonstrations from each class"} + ) + + auto_demo: bool = field( + default=True, + metadata={"help": "Automatically generate template for using demonstrations"} + ) + + # For prompting + sfc_prompt: str = field( + default=None, + metadata={"help": "SFC prompt"} + ) + + template: str = field( + default=None, + metadata={"help": "Template"} + ) + + mapping: str = field( + default=None, + metadata={"help": "Label word mapping"} + ) + + template_path: str = field( + default=None, + metadata={"help": "Path to a txt file that stores all the templates, one per line. Do not set this when prompt_path is used"} + ) + + mapping_path: str = field( + default=None, + metadata={"help": "Path to a txt file that stores all the label word mappings, one per line. Do not set this when prompt_path is used"} + ) + + prompt_path: str = field( + default=None, + metadata={"help": "Path to a txt file that stores all the prompts (templates and mappings), one per line"} + ) + + template_id: int = field( + default=None, + metadata={"help": "Template id if using template_path"} + ) + + mapping_id: int = field( + default=None, + metadata={"help": "Mapping id if using template_path"} + ) + + prompt_id: int = field( + default=None, + metadata={"help": "Prompt id if using prompt_path"} + ) + + top_n_template: int = field( + default=None, + metadata={"help": "Use top-n template in the template path"} + ) + + # For logging + tag: str = field( + default='', + metadata={"help": "Set the tag and find the result easier in the log."} + ) + + # For filtering when using demonstrations + demo_filter: bool = field( + default=False, + metadata={"help": "Only use similar instances in demonstrations"} + ) + + demo_filter_rate: float = field( + default=0.5, + metadata={"help": "Only use top-x\% similar instances in demonstrations"} + ) + + demo_filter_model: str = field( + default=None, + metadata={"help": "Model name for demonstration filter embeddings. Will load embeddings based on the model name."} + ) + + debug_mode: bool = field( + default=False, + metadata={"help": "Debug mode"} + ) + + # For max length + double_demo: bool = field( + default=False, + metadata={"help": "Use double length for using demonstrations"} + ) + + first_sent_limit: int = field( + default=None, + metadata={"help": "Limit the length of the first sentence (i.e., sent_0)"} + ) + + other_sent_limit: int = field( + default=None, + metadata={"help": "Limit the length of sentences other than the first sentence"} + ) + + use_full_length: bool = field( + default=None, + metadata={"help": "Use the full length (512)"} + ) + + # GPT-3's in-context learning + gpt3_in_context_head: bool = field( + default=False, + metadata={"help": "GPT-3's in-context learning (context at the beginning)"} + ) + + gpt3_in_context_tail: bool = field( + default=False, + metadata={"help": "GPT-3's in-context learning (context at the end)"} + ) + + gpt3_in_context_num: int = field( + default=32, + metadata={"help": "Number of context examples"} + ) + + gpt3_demo_separator: str = field( + default="\n\n\n", + metadata={"help": "Separator between demonstrations"} + ) + + truncate_head: bool = field( + default=False, + metadata={"help": "When exceeding the maximum length, truncate the head instead of the tail."} + ) + + # Do not set up the following fields. They are set up automatically. + prompt: bool = field( + default=False, + metadata={"help": "Whether to use prompt-based fine-tuning"} + ) + template_list: List[str] = field( + default=None, + metadata={"help": "(DO NOT List of templates (only initialized after the program starts."}, + + ) + + +@dataclass +class DynamicTrainingArguments(TrainingArguments): + evaluate_during_training: bool = field( + default=False, + metadata={"help": "Whether to run evaluation during training or at the."} + ) + log_file: str = field( + default='log' + ) + + # For ensemble + array_id: int = field( + default=-1, + metadata={"help": "Array ID (contains seed and hyper-parameter search) to idenfity the model"} + ) + + model_id: int = field( + default=-1, + metadata={"help": "Model ID (contains template information) to identify the model"} + ) + + save_logit: bool = field( + default=False, + metadata={"help": "Save test file logit with name $TASK-$MODEL_ID-$ARRAY_ID.npy"} + ) + + save_logit_dir: str = field( + default=None, + metadata={"help": "Where to save the prediction result"} + ) + + # Regularization + fix_layers: int = field( + default=0, + metadata={"help": "Fix bottom-n layers when optimizing"} + ) + + # Training + save_at_last: bool = field( + default=False, + metadata={"help": "Instead of saving the best (dev performance) checkpoint, save the last checkpoint"} + ) + + # Turn off train/test + no_train: bool = field( + default=False, + metadata={"help": "No training"} + ) + no_predict: bool = field( + default=False, + metadata={"help": "No test"} + ) + optimizer: str = field( + default='adam', + metadata={'help': 'choose sgd or adam. default is adam'} + ) + optimizer_variant: str = field( + default='', + metadata={'help': 'define variants on optimizer: signgd'} + ) + + trainer: str = field( + default="standard", + metadata={"help": "Pick from {standard, kernel, linearhead}"} + ) + from_linearhead: bool = field( + default=False, + metadata={"help": "Whether to initialize head with the linearhead solution. Works for both normal and kernel trainer."} + ) + lp_early_stopping: bool = field( + default=False, + metadata={"help": "When on, increases the tolerance and lowers max_iter in scikit LogisticRegression solver to encourage early stopping."} + ) + random_model_init: bool = field( + default=False, + metadata={'help': 'reinit the model randomly'} + ) + sweep: bool = field( + default=False, + metadata={'help': 'configures the output directories to be informative when running W&B sweep'} + ) + kernel_formula: str = field( + default='sgd', + metadata={"help": "choose kernel formula from {sgd, signgd, asymmetric_signgd}"} + ) + kernel_solver: str = field( + default="logistic", + metadata={"help": "choose kernel solver from {lstsq, logistic, svr, svc, asym (only for asymmetric_signgd)}"} + ) + load_kernels: str = field( + default=None, + metadata={'help': 'when specified, loads the kernels from the folder given here'} + ) + overwrite_kernels: bool = field( + default=False, + metadata={'help': 'when specified, overwrites the kernels in the output_dir and computes them from scratch'} + ) + + exclude_embeddings: bool = field( + default=False, + metadata={"help": "Don't use embeddings for kernel computation "} + ) + exclude_head: bool = field( + default=False, + metadata={"help": "Don't use head for kernel computation "} + ) + only_biases: bool = field( + default=False, + metadata={"help": "Only use bias parameters for kernel computation for BitFit-style kernel"} + ) + exclude_first_layers: int = field( + default=-1, + metadata={'help': 'excludes the first N layers from kernel computation'} + ) + sync_embedding_layers: bool = field( + default=False, + metadata={'help': 'sync the input embedding to match output embedding (use with --exclude_first_layers)'} + ) + + kernel_regularization: float = field( + default=0.0, + metadata={"help": "Regularization constant for kernel"} + ) + kernel_gamma: float = field( + default=1.0, + metadata={"help": "Gamma for asymmetric kernel solver"} + ) + binary_classification: bool = field( + default=False, + metadata={"help": "If num_classes=2, convert two softmax logits to single sigmoid logit"} + ) + adjust_for_init: bool = field( + default=False, + metadata={'help': 'when on, trains kernel on y-f0 and adds f0 at test time'} + ) + f0_scaling: float = field( + default=1.0, + metadata={'help': 'adjust label scaling, might help with --adjust_for_init perf'} + ) + zero_order_optim: bool = field( + default=False, + metadata={'help': 'when on, trains the model by zero-order optimization'} + ) + zero_order_eps: float = field( + default=1e-3, + metadata={'help': 'eps for zero order optim'} + ) + prob_as_feature: bool = field( + default=False, + metadata={'help': 'in linear head, use log prob as feature'} + ) + zero_order_use_trainer_optim: bool = field( + default=False, + metadata={"help": "Use trainer optimizer for zero order optimization"} + ) + efficient_zero_order: bool = field( + default=False, + metadata={"help": "Efficient zero-order: resample noise vectors instead of saving them. enable different model loading using --hf_inference_model"} + ) + hf_inference_model: bool = field( + default=False, + metadata={"help": "loads the HF model in inference mode across many GPUs. incompatible with --zero_order_use_trainer_optim."} + ) + efficient_zero_order_fp16: bool = field( + default=False, + metadata={"help": "Use fp16 for efficient zero order"} + ) + zero_order_sample_scheduler: str = field( + default=None, + metadata={"help": "Have a sample scheduler. None, 'linear', 'power', or 'constant."} + ) + scale_lr_with_samples: bool = field( + default=False, + metadata={"help": "Scales the LR proportionally to the number of z samples. --learning_rate will be the LR for one z sample."} + ) + zero_order_sample: int = field( + default=1, + metadata={"help": "Sample times for zero-order estimate. If scheduler is 'linear', this number is the max sample number."} + ) + zero_order_clip_grad: bool = field( + default=False, + metadata={"help": "Clip the norm of the gradient for zero order (only when using trainer optimizer)"} + ) + + # MeZO variants + zo_by_layer: bool = field( + default=False, + metadata={"help": "For ZO: estimate the gradients on each layer individually, scales number of forward passes per grad step by a factor of L"} + ) + zo_variant: str = field( + default=None, + metadata={"help": "Choose the MeZO variant: grad_norm or param_norm (see documentation)"} + ) + use_zo_grad_est: bool = field( + default=False, + metadata={"help": "Use zero-order estimate of the gradient for zo variants"} + ) + recompute_norms: bool = field( + default=False, + metadata={'help': 'Recompute the grad or parameter norm (whichever was specified as --zo_variant) at the start of each epoch.'} + ) + scale_norm_by_num_params: bool = field( + default=False, + metadata={'help': 'Scale grad or param norm by 1 / sqrt(num params)'} + ) + norm_running_update: bool = field( + default=False, + metadata={"help": "When performing --zo_by_layer and using --zo_variant 'grad_norm', update the layer grad norms as they are recomputed at each step"} + ) + change_grad_estimate: bool = field( + default=False, + metadata={"help": "Changes the expectation of the ZO gradient estimate according to zo_variant, instead of just modifying the variance"} + ) + + # prefix tuning hyperparameters + prefix_tuning: bool = field( + default=False, + metadata={"help": "Prefix tuning"} + ) + num_prefix: int = field( + default=10, + metadata={"help": "How many prefix tokens to use"} + ) + no_reparam: bool = field( + default=False, + metadata={"help": "No reparameterization trick"} + ) + prefix_init_by_real_act: bool = field( + default=False, + metadata={"help": "For no_reparam case, randomly sample words and take their actual key/value pairs as initialization"} + ) + layer_wise_optim: bool = field( + default=False, + metadata={'help': 'Optimize layer-by-layer (only for prefix + ZO)'} + ) + + max_zo_forward_steps: int = field( + default=0, + metadata={'help': 'Stop at this number of ZO forward steps. The trainer will take whichever is reached first, max_steps or max_zo_forward_steps.'} + ) + + untie_emb: bool = field( + default=False, + metadata={"help": "Untie embeddings from lm head. Only work for OPT!!"} + ) + tie_emb: bool = field( + default=False, + metadata={"help": "Tie embeddings from lm head. Only work for RoBERTa!!"} + ) + + optimize_acc: bool = field( + default=False, + metadata={"help": "Maximize accuracy instead of minimizing loss"} + ) + + + ## hessian trainer args + num_hvp_vecs: int = field( + default=128, + metadata={"help": "Number of vectors to use to estimate HVPs"} + ) + mc_tol: float = field( + default=0.1, + metadata={"help": "Tolerance (on std dev) after which MC estimate is deemed converged"} + ) + + head_tuning: bool = field( + default=False, + metadata={"help": "Tune the head only"} + ) + + +@dataclass +class MyDataCollatorWithPadding: + """ + Implements padding for LM-BFF inputs. + Args: + tokenizer ([`PreTrainedTokenizer`] or [`PreTrainedTokenizerFast`]): + The tokenizer used for encoding the data. + padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `True`): + Select a strategy to pad the returned sequences (according to the model's padding side and padding index) + among: + - `True` or `'longest'` (default): Pad to the longest sequence in the batch (or no padding if only a single + sequence is provided). + - `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum + acceptable input length for the model if that argument is not provided. + - `False` or `'do_not_pad'`: No padding (i.e., can output a batch with sequences of different lengths). + max_length (`int`, *optional*): + Maximum length of the returned list and optionally padding length (see above). + pad_to_multiple_of (`int`, *optional*): + If set will pad the sequence to a multiple of the provided value. + This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability >= + 7.5 (Volta). + return_tensors (`str`): + The type of Tensor to return. Allowable values are "np", "pt" and "tf". + """ + + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + return_tensors: str = "pt" + + def __call__(self, features): + mask_pos = [] + standard_features = [] + if features[0].sfc_input_ids is not None: + sfc_batch = self.__call__([OurInputFeatures(input_ids=x.sfc_input_ids, attention_mask=x.sfc_attention_mask, mask_pos=x.sfc_mask_pos) for x in features]) + + for item in features: + standard_item = {} + for field in ["input_ids", "label", "attention_mask", "token_type_ids"]: + if getattr(item, field) is not None: + standard_item[field] = getattr(item, field) + standard_features.append(standard_item) + mask_pos.append(item.mask_pos) + + batch = self.tokenizer.pad( + standard_features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors=self.return_tensors, + ) + + if any(mask_pos): + batch["mask_pos"] = torch.tensor(mask_pos) + + if "label" in batch: + batch["labels"] = batch["label"] + del batch["label"] + if "label_ids" in batch: + batch["labels"] = batch["label_ids"] + del batch["label_ids"] + + if features[0].sfc_input_ids is not None: + batch["sfc_input_ids"] = sfc_batch["input_ids"] + batch["sfc_attention_mask"] = sfc_batch["attention_mask"] + batch["sfc_mask_pos"] = sfc_batch["mask_pos"] + return batch + + +def main(): + parser = HfArgumentParser((ModelArguments, DynamicDataTrainingArguments, DynamicTrainingArguments)) + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + # If we pass only one argument to the script and it's the path to a json file, + # let's parse it to get our arguments. + model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + if training_args.sweep: + now = datetime.now() + dt_str = now.strftime('%m_%d_%H_%M_%S') + training_args.output_dir = os.path.join(training_args.output_dir, dt_str) + + #if model_args.apply_lora: + # assert 'roberta' in model_args.model_name_or_path, 'LoRA only implemented for RoBERTa models' + + if training_args.kernel_formula == 'asymmetric_signgd': + assert training_args.binary_classification, 'asymmetric solver not implemented for multi-class setting, use --binary_classification' + + if training_args.optimizer_variant != '': + assert training_args.optimizer == 'sgd', 'variants on optimizer are only implemented for SGD' + + if 'prompt' in model_args.few_shot_type: + data_args.prompt = True + + + if training_args.no_train: + training_args.do_train = False + if training_args.no_predict: + training_args.do_predict = False + + # Setup logging + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN, + ) + + # Load prompt/template/mapping file + if data_args.prompt: + if data_args.prompt_path is not None: + assert data_args.prompt_id is not None + prompt_list = [] + with open(data_args.prompt_path) as f: + for line in f: + line = line.strip() + template, mapping = line.split('\t') + prompt_list.append((template, mapping)) + + data_args.template, data_args.mapping = prompt_list[data_args.prompt_id] + logger.info("Specify load the %d-th prompt: %s | %s" % (data_args.prompt_id, data_args.template, data_args.mapping)) + else: + if data_args.template_path is not None: + with open(data_args.template_path) as f: + data_args.template_list = [] + for line in f: + line = line.strip() + if len(line) > 0: + data_args.template_list.append(line) + + # Load top-n templates + if data_args.top_n_template is not None: + data_args.template_list = data_args.template_list[:data_args.top_n_template] + logger.info("Load top-%d templates from %s" % (len(data_args.template_list), data_args.template_path)) + + # ... or load i-th template + if data_args.template_id is not None: + data_args.template = data_args.template_list[data_args.template_id] + data_args.template_list = None + logger.info("Specify load the %d-th template: %s" % (data_args.template_id, data_args.template)) + + if data_args.mapping_path is not None: + assert data_args.mapping_id is not None # Only can use one label word mapping + with open(data_args.mapping_path) as f: + mapping_list = [] + for line in f: + line = line.strip() + mapping_list.append(line) + + data_args.mapping = mapping_list[data_args.mapping_id] + logger.info("Specify using the %d-th mapping: %s" % (data_args.mapping_id, data_args.mapping)) + + # Check save path + if ( + os.path.exists(training_args.output_dir) + and os.listdir(training_args.output_dir) + and training_args.do_train + and not training_args.overwrite_output_dir + ): + raise ValueError(f"Output directory ({training_args.output_dir}) already exists.") + + logger.warning( + "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s", + training_args.local_rank, + training_args.device, + training_args.n_gpu, + bool(training_args.local_rank != -1), + training_args.fp16, + ) + logger.info("Training/evaluation parameters %s", training_args) + + # Set seed + set_seed(training_args.seed) + + try: + num_labels = num_labels_mapping[data_args.task_name] + output_mode = output_modes_mapping[data_args.task_name] + logger.info("Task name: {}, number of labels: {}, output mode: {}".format(data_args.task_name, num_labels, output_mode)) + except KeyError: + raise ValueError("Task not found: %s" % (data_args.task_name)) + + # Automatically generate template for using demonstrations + if data_args.auto_demo and model_args.few_shot_type == 'prompt-demo': + # GPT-3's in-context learning + if data_args.gpt3_in_context_head or data_args.gpt3_in_context_tail: + logger.info("Automatically convert the template to GPT-3's in-context learning.") + assert data_args.template_list is None + + old_template = data_args.template + new_template = old_template + '' + new_sfc_template = data_args.sfc_prompt + '' + old_template = old_template.replace('*cls*', '') + old_template = old_template.replace('*bos*', '') + if data_args.gpt3_in_context_head: + new_template = new_template.replace('*cls*', '') + new_template = new_template.replace('*bos*', '') + + # Single sentence or sentence pair? + sent_num = 1 + if "_1" in old_template: + sent_num = 2 + for instance_id in range(data_args.gpt3_in_context_num): + sub_template = old_template + '' + # Replace sent_id + for sent_id in range(sent_num): + sub_template = sub_template.replace("_{}*".format(sent_id), "_{}*".format(sent_num + sent_num * instance_id + sent_id)) + # Replace mask + if "opt" in model_args.model_name_or_path or "gpt" in model_args.model_name_or_path: + sub_template = sub_template + "*labelx_{}*".format(instance_id) + else: + sub_template = sub_template.replace("*mask*", "*labelx_{}*".format(instance_id)) + if data_args.gpt3_in_context_tail: + new_template = new_template + data_args.gpt3_demo_separator + sub_template # Put context at the end + new_sfc_template = new_sfc_template + data_args.gpt3_demo_separator + sub_template + else: + new_template = sub_template + data_args.gpt3_demo_separator + new_template # Put context at the beginning + new_sfc_template = sub_template + data_args.gpt3_demo_separator + new_sfc_template + if data_args.gpt3_in_context_head: + new_template = "*bos*" + new_template + new_sfc_template = "*bos*" + new_sfc_template + logger.info("| {} => {}".format(data_args.template, new_template)) + logger.info("New SFC template (in-context learning): {}".format(new_sfc_template)) + data_args.template = new_template + if model_args.icl_sfc: + data_args.icl_sfc_prompt = new_sfc_template + else: + logger.info("Automatically convert the template to using demonstrations.") + if data_args.template_list is not None: + for i in range(len(data_args.template_list)): + old_template = data_args.template_list[i] + new_template = old_template + '' + old_template = old_template.replace('*cls*', '') + # Single sentence or sentence pair? + sent_num = 1 + if "_1" in old_template: + sent_num = 2 + for label_id in range(num_labels): + sub_template = old_template + '' + # Replace sent id + for sent_id in range(sent_num): + sub_template = sub_template.replace("_{}*".format(sent_id), "_{}*".format(sent_num + sent_num * label_id + sent_id)) + # Replace mask + sub_template = sub_template.replace("*mask*", "*label_{}*".format(label_id)) + new_template = new_template + sub_template + logger.info("| {} => {}".format(data_args.template_list[i], new_template)) + data_args.template_list[i] = new_template + else: + old_template = data_args.template + new_template = old_template + '' + old_template = old_template.replace('*cls*', '') + # Single sentence or sentence pair? + sent_num = 1 + if "_1" in old_template: + sent_num = 2 + for label_id in range(num_labels): + sub_template = old_template + '' + # Replace sent id + for sent_id in range(sent_num): + sub_template = sub_template.replace("_{}".format(sent_id), "_{}".format(sent_num + sent_num * label_id + sent_id)) + # Replace mask + sub_template = sub_template.replace("*mask*", "*label_{}*".format(label_id)) + new_template = new_template + sub_template + logger.info("| {} => {}".format(data_args.template, new_template)) + data_args.template = new_template + + # Create config + config_kwargs = {'apply_lora': model_args.apply_lora, + 'lora_alpha': model_args.lora_alpha, + 'lora_r': model_args.lora_r} + if model_args.apply_lora: + if 'roberta' in model_args.model_name_or_path: + config = RobertaConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir, + **config_kwargs) + else: + config = OPTConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir, + **config_kwargs + ) + else: + config = AutoConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir + ) + + if training_args.untie_emb: + logger.warn("Untie embeddings and lm head") + logger.warn("NOTE that this only works for OPT. By default RoBERTa model embeddings are already untied.") + config.tie_word_embeddings = False + + if 'prompt' in model_args.few_shot_type: + model_fn = MODEL_TYPES[config.model_type] + elif model_args.few_shot_type == 'finetune': + if training_args.from_linearhead: + model_fn = MODEL_TYPES[config.model_type] + else: + model_fn = AutoModelForSequenceClassification + else: + raise NotImplementedError + special_tokens = [] + + # Create tokenizer + tokenizer = AutoTokenizer.from_pretrained( + model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, + additional_special_tokens=special_tokens, + cache_dir=model_args.cache_dir, + ) + if "opt" in model_args.model_name_or_path: + # Set SEP token + tokenizer.sep_token_id = tokenizer.eos_token_id + tokenizer.bos_token_id = 0 + if "gpt2" in model_args.model_name_or_path: + tokenizer.sep_token_id = tokenizer.eos_token_id + tokenizer.pad_token_id = tokenizer.eos_token_id + + + if training_args.hf_inference_model: + free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) + max_memory = f'{free_in_GB-5}GB' + n_gpus = torch.cuda.device_count() + max_memory = {i: max_memory for i in range(n_gpus)} + + model = model_fn.from_pretrained( + model_args.model_name_or_path, + config=config, + device_map='auto', + torch_dtype=torch.float16 if training_args.efficient_zero_order_fp16 else torch.float32, + max_memory=max_memory, + ) + else: + model = model_fn.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + ) + + if training_args.tie_emb: + logger.warn("Tie embeddings. Only work for RoBERTa (in our code by default they are not tied)") + model.tie_emb() + + if training_args.head_tuning: + if model.config.model_type == "roberta": + head_name = "lm_head" + + for n, p in model.named_parameters(): + if head_name not in n: + p.requires_grad = False + else: + logger.info(f"Only tuning {n}") + + tokenizer.model_type = model.config.model_type + + if training_args.exclude_first_layers != -1: + model = convert_opt_model(model, config, training_args.exclude_first_layers) + + if training_args.prefix_tuning: + from src.prefix import PrefixTuning + PrefixTuning(model, num_prefix=training_args.num_prefix, reparam=not training_args.no_reparam, float16=training_args.efficient_zero_order_fp16, init_by_real_act=training_args.prefix_init_by_real_act) + + # Get our special datasets. + train_dataset = ( + FewShotDataset(data_args, tokenizer=tokenizer, mode="train", use_demo=("demo" in model_args.few_shot_type)) + if training_args.do_train + else None + ) + eval_dataset = ( + FewShotDataset(data_args, tokenizer=tokenizer, mode="dev", use_demo=("demo" in model_args.few_shot_type)) + if training_args.do_eval + else None + ) + test_dataset = ( + FewShotDataset(data_args, tokenizer=tokenizer, mode="test", use_demo=("demo" in model_args.few_shot_type)) + if training_args.do_predict + else None + ) + + set_seed(training_args.seed) + + if training_args.random_model_init: + model.init_weights() # reinit weights to random + + # For BERT, increase the size of the segment (token type) embeddings + if config.model_type == 'bert': + model.resize_token_embeddings(len(tokenizer)) + resize_token_type_embeddings(model, new_num_types=10, random_segment=model_args.random_segment) + + # Pass dataset and argument information to the model + if eval_dataset.label_word_list is not None: + model.label_word_list = torch.tensor(eval_dataset.label_word_list).long().to(training_args.device) + if output_modes_mapping[data_args.task_name] == 'regression': + # lower / upper bounds + model.lb, model.ub = bound_mapping[data_args.task_name] + model.model_args = model_args + model.data_args = data_args + model.tokenizer = tokenizer + + if model_args.apply_lora: + for name, param in model.named_parameters(): + if (name.startswith('roberta') and "lora" not in name) or (name.startswith('opt') and "lora" not in name): + param.requires_grad_(False) + + # Build metric + def build_compute_metrics_fn(task_name: str) -> Callable[[EvalPrediction], Dict]: + def compute_metrics_fn(p: EvalPrediction): + # Note: the eval dataloader is sequential, so the examples are in order. + # We average the logits over each sample for using demonstrations. + predictions = p.predictions + num_logits = predictions.shape[-1] + + num_sample = test_dataset.num_sample if eval_dataset is None else eval_dataset.num_sample + logits = predictions.reshape([num_sample, -1, num_logits]) + logits = logits.mean(axis=0) + + if num_logits == 1: + preds = np.squeeze(logits) + else: + preds = np.argmax(logits, axis=1) + + # Just for sanity, assert label ids are the same. + label_ids = p.label_ids.reshape([num_sample, -1]) + label_ids_avg = label_ids.mean(axis=0) + label_ids_avg = label_ids_avg.astype(p.label_ids.dtype) + assert (label_ids_avg - label_ids[0]).mean() < 1e-2 + label_ids = label_ids[0] + + return compute_metrics_mapping[task_name](task_name, preds, label_ids) + + return compute_metrics_fn + + # Initialize our Trainer + trainer_classes = { + "standard": Trainer, + "linearhead": LinearHeadTrainer, + } + trainer_class = trainer_classes[training_args.trainer] + trainer_kwargs = {} + trainer = trainer_class( + model=model, + args=training_args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + compute_metrics=build_compute_metrics_fn(data_args.task_name), + data_collator=MyDataCollatorWithPadding(tokenizer), + **trainer_kwargs + ) + + # Calibration + if model_args.sfc: + inputs = tokenizer([data_args.sfc_prompt.replace("_", " ")], return_tensors="pt") + logger.info(f"Calibrating SFC with prompt: {data_args.sfc_prompt}") + logger.info("Inputs: {}".format(inputs.input_ids)) + inputs = inputs.to(model.device) + with torch.no_grad(): + model.eval() + logits = model(**inputs)[0] + model.sfc_bias = F.log_softmax(logits.squeeze(0).detach()) + logger.info("SFC bias: {}".format(model.sfc_bias)) + + + # Training + if training_args.do_train: + train_result = trainer.train(model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path) else None) + + if training_args.trainer == "hessian": + # Write the result to log + with FileLock('log_hessian.lock'): + with open('log_hessian', 'a') as f: + train_result.update(vars(model_args)) + train_result.update(vars(training_args)) + train_result.update(vars(data_args)) + if 'evaluation_strategy' in train_result: + train_result.pop('evaluation_strategy') + f.write(str(train_result) + '\n') + exit() + + # Use the early stop, so do not save the model in the end (unless specify save_at_last) + + if training_args.trainer == "standard" or training_args.trainer == "linearhead": + if training_args.save_at_last: + trainer.save_model(training_args.output_dir) + + if trainer.is_world_process_zero(): + tokenizer.save_pretrained(training_args.output_dir) + torch.save(model_args, os.path.join(training_args.output_dir, "model_args.bin")) + torch.save(data_args, os.path.join(training_args.output_dir, "data_args.bin")) + + if training_args.evaluate_during_training: + # Reload the best checkpoint (for eval) + # model.load_state_dict(trainer.best_model_ckpt) + # if training_args.prefix_tuning: + # # We can load prefix by directly using load_state_dict + # model.load_state_dict(torch.load(os.path.join(training_args.output_dir, "pytorch_model.bin"))) + # else: + # model = model_fn.from_pretrained(training_args.output_dir) + # if training_args.exclude_first_layers != -1: + # model = convert_opt_model(model, config, training_args.exclude_first_layers) + + # model = model.to(training_args.device) + + # Now we just reload this from memory instead of disk <-- much faster + trainer.model.load_state_dict(trainer.best_model_ckpt) + + # Evaluation + final_result = { + 'time': str(datetime.today()), + 'output_dir': training_args.output_dir + } + + eval_results = {} + if training_args.do_eval: + logger.info("*** Validate ***") + + eval_datasets = [eval_dataset] + + for eval_dataset in eval_datasets: + trainer.compute_metrics = build_compute_metrics_fn(eval_dataset.args.task_name) + output = trainer.evaluate(eval_dataset=eval_dataset) + eval_result = output.metrics + + output_eval_file = os.path.join( + training_args.output_dir, f"eval_results_{eval_dataset.args.task_name}.txt" + ) + if trainer.is_world_process_zero(): + with open(output_eval_file, "w") as writer: + logger.info("***** Eval results {} *****".format(eval_dataset.args.task_name)) + for key, value in eval_result.items(): + logger.info(" %s = %s", key, value) + writer.write("%s = %s\n" % (key, value)) + final_result[eval_dataset.args.task_name + '_dev_' + key] = value + eval_results.update(eval_result) + + test_results = {} + if training_args.do_predict: + logging.info("*** Test ***") + test_datasets = [test_dataset] + ### Don't evaluate on mnli-mm for our purposes + # if data_args.task_name == "mnli": + # mnli_mm_data_args = dataclasses.replace(data_args, task_name="mnli-mm") + # test_datasets.append( + # FewShotDataset(mnli_mm_data_args, tokenizer=tokenizer, mode="test", use_demo=('demo' in model_args.few_shot_type)) + # ) + + for test_dataset in test_datasets: + trainer.compute_metrics = build_compute_metrics_fn(test_dataset.args.task_name) + output = trainer.evaluate(eval_dataset=test_dataset) + test_result = output.metrics + + output_test_file = os.path.join( + training_args.output_dir, f"test_results_{test_dataset.args.task_name}.txt" + ) + if trainer.is_world_process_zero(): + with open(output_test_file, "w") as writer: + logger.info("***** Test results {} *****".format(test_dataset.args.task_name)) + for key, value in test_result.items(): + logger.info(" %s = %s", key, value) + writer.write("%s = %s\n" % (key, value)) + final_result[test_dataset.args.task_name + '_test_' + key] = value + + if training_args.save_logit: + predictions = output.predictions + num_logits = predictions.shape[-1] + logits = predictions.reshape([test_dataset.num_sample, -1, num_logits]).mean(axis=0) + np.save(os.path.join(training_args.save_logit_dir, "{}-{}-{}.npy".format(test_dataset.task_name, training_args.model_id, training_args.array_id)), logits) + + test_results.update(test_result) + + + if trainer.is_world_process_zero(): + with FileLock('log.lock'): + with open(training_args.log_file, 'a') as f: + final_result.update(vars(model_args)) + final_result.update(vars(training_args)) + final_result.update(vars(data_args)) + if 'evaluation_strategy' in final_result: + final_result.pop('evaluation_strategy') + f.write(str(final_result) + '\n') + + logger.info('****** Output Dir *******') + logger.info(training_args.output_dir) + + return eval_results + +if __name__ == "__main__": + main() diff --git a/baselines/mezo/medium_models/src/dataset.py b/baselines/mezo/medium_models/src/dataset.py new file mode 100644 index 0000000..f770dea --- /dev/null +++ b/baselines/mezo/medium_models/src/dataset.py @@ -0,0 +1,695 @@ +"""Dataset utils for different data settings for GLUE.""" + +import os +import logging +import torch +import numpy as np +import time +from filelock import FileLock +import json +from src.processors import processors_mapping, num_labels_mapping, output_modes_mapping, compute_metrics_mapping, median_mapping +from transformers.data.processors.utils import InputFeatures +import dataclasses +from dataclasses import dataclass +from typing import List, Optional, Union +import pandas as pd + +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +@dataclass(frozen=True) +class OurInputFeatures(InputFeatures): + """ + Inherit from Transformers' InputFeatuers. + """ + + input_ids: List[int] + attention_mask: Optional[List[int]] = None + token_type_ids: Optional[List[int]] = None + label: Optional[Union[int, float]] = None + mask_pos: Optional[List[int]] = None # Position of the mask token + label_word_list: Optional[List[int]] = None # Label word mapping (dynamic) + + # For icl sfc + sfc_input_ids: List[int] = None + sfc_attention_mask: Optional[List[int]] = None + sfc_mask_pos: Optional[List[int]] = None + + def to_json_string(self): + """Serializes this instance to a JSON string.""" + return json.dumps(dataclasses.asdict(self)) + "\n" + +def input_example_to_string(example, sep_token): + if example.text_b is None: + return example.text_a + else: + # Warning: very simple hack here + return example.text_a + ' ' + sep_token + ' ' + example.text_b + +def input_example_to_tuple(example): + if example.text_b is None: + if pd.isna(example.text_a) or example.text_a is None: + return [''] + logger.warn("Empty input") + else: + return [example.text_a] + else: + return [example.text_a, example.text_b] + +def tokenize_multipart_input( + input_text_list, + max_length, + tokenizer, + task_name=None, + prompt=False, + template=None, + label_word_list=None, + first_sent_limit=None, + other_sent_limit=None, + gpt3=False, + truncate_head=False, + support_labels=None, +): + def enc(text): + return tokenizer.encode(text, add_special_tokens=False) + + input_ids = [] + attention_mask = [] + token_type_ids = [] # Only for BERT + mask_pos = None # Position of the mask token + + if prompt: + """ + Concatenate all sentences and prompts based on the provided template. + Template example: '*cls*It was*mask*.*sent_0***label_0:*sent_1****label_1*:*sent_2***' + *xx* represent variables: + *cls*: cls_token + *mask*: mask_token + *sep*: sep_token + *sep+*: sep_token, also means +1 for segment id + *sent_i*: sentence i (input_text_list[i]) + *sent-_i*: same as above, but delete the last token + *sentl_i*: same as above, but use lower case for the first word + *sentl-_i*: same as above, but use lower case for the first word and delete the last token + *+sent_i*: same as above, but add a space before the sentence + *+sentl_i*: same as above, but add a space before the sentence and use lower case for the first word + *label_i*: label_word_list[i] + *label_x*: label depends on the example id (support_labels needed). this is only used in GPT-3's in-context learning + + Use "_" to replace space. + PAY ATTENTION TO SPACE!! DO NOT leave space before variables, for this will lead to extra space token. + """ + assert template is not None + + special_token_mapping = { + 'bos': tokenizer.bos_token_id, 'cls': tokenizer.cls_token_id, 'eos': tokenizer.eos_token_id, 'mask': tokenizer.mask_token_id, 'sep': tokenizer.sep_token_id, 'sep+': tokenizer.sep_token_id, + } + template_list = template.split('*') # Get variable list in the template + segment_id = 0 # Current segment id. Segment id +1 if encountering sep+. + + for part_id, part in enumerate(template_list): + new_tokens = [] + segment_plus_1_flag = False + if part in special_token_mapping: + if (part == 'cls' or part == 'bos') and ('T5' in type(tokenizer).__name__ or tokenizer.model_type == "gpt2"): + # T5 or GPT-2 do not have cls token + continue + new_tokens.append(special_token_mapping[part]) + if part == 'sep+': + segment_plus_1_flag = True + elif part[:6] == 'label_': + # Note that label_word_list already has extra space, so do not add more space ahead of it. + label_id = int(part.split('_')[1]) + label_word = label_word_list[label_id] + new_tokens.append(label_word) + elif part[:7] == 'labelx_': + instance_id = int(part.split('_')[1]) + label_id = support_labels[instance_id] + label_word = label_word_list[label_id] + new_tokens.append(label_word) + elif part[:5] == 'sent_': + sent_id = int(part.split('_')[1]) + new_tokens += enc(input_text_list[sent_id]) + elif part[:6] == '+sent_': + # Add space + sent_id = int(part.split('_')[1]) + new_tokens += enc(' ' + input_text_list[sent_id]) + elif part[:6] == 'sent-_': + # Delete the last token + sent_id = int(part.split('_')[1]) + new_tokens += enc(input_text_list[sent_id][:-1]) + elif part[:6] == 'sentl_': + # Lower case the first token + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].lower() + text[1:] + new_tokens += enc(text) + elif part[:7] == '+sentl_': + # Lower case the first token and add space + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].lower() + text[1:] + new_tokens += enc(' ' + text) + elif part[:7] == 'sentl-_': + # Lower case the first token and discard the last token + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].lower() + text[1:] + new_tokens += enc(text[:-1]) + elif part[:6] == 'sentu_': + # Upper case the first token + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].upper() + text[1:] + new_tokens += enc(text) + elif part[:7] == '+sentu_': + # Upper case the first token and add space + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].upper() + text[1:] + new_tokens += enc(' ' + text) + elif part[:8] == '+sentu-_': + # Upper case the first token and add space + sent_id = int(part.split('_')[1]) + text = input_text_list[sent_id] + text = text[:1].upper() + text[1:] + new_tokens += enc(' ' + text[:-1]) + else: + # Just natural language prompt + part = part.replace('_', ' ') + # handle special case when T5 tokenizer might add an extra space + if len(part) == 1: + new_tokens.append(tokenizer.convert_tokens_to_ids(part)) + else: + new_tokens += enc(part) + + if part[:4] == 'sent' or part[1:5] == 'sent': + # If this part is the sentence, limit the sentence length + sent_id = int(part.split('_')[1]) + if sent_id == 0: + if first_sent_limit is not None: + new_tokens = new_tokens[:first_sent_limit] + else: + if other_sent_limit is not None: + new_tokens = new_tokens[:other_sent_limit] + + input_ids += new_tokens + attention_mask += [1 for i in range(len(new_tokens))] + token_type_ids += [segment_id for i in range(len(new_tokens))] + + if segment_plus_1_flag: + segment_id += 1 + else: + if tokenizer.cls_token_id is not None: + input_ids = [tokenizer.cls_token_id] + attention_mask = [1] + token_type_ids = [0] + else: + input_ids = [] + attention_mask = [] + token_type_ids = [] + + for sent_id, input_text in enumerate(input_text_list): + if input_text is None: + # Do not have text_b + continue + if pd.isna(input_text) or input_text is None: + # Empty input + input_text = '' + input_tokens = enc(input_text) + [tokenizer.sep_token_id] + input_ids += input_tokens + attention_mask += [1 for i in range(len(input_tokens))] + token_type_ids += [sent_id for i in range(len(input_tokens))] + + if 'T5' in type(tokenizer).__name__: # T5 does not have CLS token + input_ids = input_ids[1:] + attention_mask = attention_mask[1:] + token_type_ids = token_type_ids[1:] + + # Padding + if first_sent_limit is not None and len(input_ids) > max_length: + # If using sentence limit, the total length still exceeds the maximum limit, report a warning + logger.warn("Input exceeds max_length limit: {}".format(tokenizer.decode(input_ids))) + + ### Code below is commented out, because we use dynamic padding rather than static padding to max_length + # while len(input_ids) < max_length: + # input_ids.append(tokenizer.pad_token_id) + # attention_mask.append(0) + # token_type_ids.append(0) + + # Truncate + if len(input_ids) > max_length: + if truncate_head: + input_ids = input_ids[-max_length:] + attention_mask = attention_mask[-max_length:] + token_type_ids = token_type_ids[-max_length:] + else: + # Default is to truncate the tail + input_ids = input_ids[:max_length] + attention_mask = attention_mask[:max_length] + token_type_ids = token_type_ids[:max_length] + + # Find mask token + if prompt and tokenizer.mask_token_id is not None: + # Make sure that the masked position is inside the max_length + assert tokenizer.mask_token_id in input_ids, \ + "Mask token not found for input: {} {}".format(input_text_list, input_ids) + mask_pos = [input_ids.index(tokenizer.mask_token_id)] + assert mask_pos[0] < max_length + elif prompt and tokenizer.mask_token_id is None: + # autoregressive model + mask_pos = [len(input_ids) - 1] + + result = {'input_ids': input_ids, 'attention_mask': attention_mask} + if 'BERT' in type(tokenizer).__name__: + # Only provide token type ids for BERT + result['token_type_ids'] = token_type_ids + + if prompt: + result['mask_pos'] = mask_pos + + return result + + + +class FewShotDataset(torch.utils.data.Dataset): + """Few-shot dataset.""" + + def __init__(self, args, tokenizer, cache_dir=None, mode="train", use_demo=False): + self.args = args + self.task_name = args.task_name + + self.processor = processors_mapping[args.task_name] + + self.tokenizer = tokenizer + self.mode = mode + + # If not using demonstrations, use use_demo=True + self.use_demo = use_demo + if self.use_demo: + logger.info("Use demonstrations") + assert mode in ["train", "dev", "test"] + + # Get label list and (for prompt) label word list + self.label_list = self.processor.get_labels() + self.num_labels = len(self.label_list) + if args.prompt and args.mapping is not None: + self.label_to_word = eval(args.mapping) + + for key in self.label_to_word: + # For RoBERTa/BART/T5, tokenization also considers space, so we use space+word as label words. + if self.label_to_word[key][0] not in ['<', '[', '.', ',']: + # Make sure space+word is in the vocabulary + assert len(tokenizer.tokenize(' ' + self.label_to_word[key])) == 1 + self.label_to_word[key] = tokenizer.convert_tokens_to_ids(tokenizer.tokenize(' ' + self.label_to_word[key])[0]) + else: + self.label_to_word[key] = tokenizer.convert_tokens_to_ids(self.label_to_word[key]) + logger.info("Label {} to word {} ({})".format(key, tokenizer.convert_ids_to_tokens(self.label_to_word[key]), self.label_to_word[key])) + + if len(self.label_list) > 1: + self.label_word_list = [self.label_to_word[label] for label in self.label_list] + else: + # Regression task + # '0' represents low polarity and '1' represents high polarity. + self.label_word_list = [self.label_to_word[label] for label in ['0', '1']] + else: + self.label_to_word = None + self.label_word_list = None + + # Multiple sampling: when using demonstrations, we sample different combinations of demonstrations during + # inference and aggregate the results by averaging the logits. The number of different samples is num_sample. + if (mode == "train") or not self.use_demo: + # We do not do multiple sampling when not using demonstrations or when it's the training mode + self.num_sample = 1 + else: + self.num_sample = args.num_sample + + # If we use multiple templates, we also need to do multiple sampling during inference. + if args.prompt and args.template_list is not None: + logger.info("There are %d templates. Multiply num_sample by %d" % (len(args.template_list), len(args.template_list))) + self.num_sample *= len(args.template_list) + + logger.info("Total num_sample for mode %s: %d" % (mode, self.num_sample)) + + # Load cache + # Cache name distinguishes mode, task name, tokenizer, and length. So if you change anything beyond these elements, make sure to clear your cache. + cached_features_file = os.path.join( + cache_dir if cache_dir is not None else args.data_dir, + "cached_{}_{}_{}_{}".format( + mode, + tokenizer.__class__.__name__ + "-" + tokenizer.model_type, + str(args.max_seq_length), + args.task_name, + ), + ) + + logger.info(f"Creating/loading examples from dataset file at {args.data_dir}") + + lock_path = cached_features_file + ".lock" + with FileLock(lock_path): + + if os.path.exists(cached_features_file) and not args.overwrite_cache: + start = time.time() + self.support_examples, self.query_examples = torch.load(cached_features_file) + logger.info( + f"Loading features from cached file {cached_features_file} [took %.3f s]", time.time() - start + ) + else: + logger.info(f"Creating features from dataset file at {args.data_dir}") + + # The support examples are sourced from the training set. + self.support_examples = self.processor.get_train_examples(args.data_dir) + + if mode == "dev": + self.query_examples = self.processor.get_dev_examples(args.data_dir) + elif mode == "test": + self.query_examples = self.processor.get_test_examples(args.data_dir) + else: + self.query_examples = self.support_examples + + start = time.time() + torch.save([self.support_examples, self.query_examples], cached_features_file) + # ^ This seems to take a lot of time so I want to investigate why and how we can improve. + logger.info( + "Saving features into cached file %s [took %.3f s]", cached_features_file, time.time() - start + ) + + # For filtering in using demonstrations, load pre-calculated embeddings + if self.use_demo and args.demo_filter: + split_name = '' + if mode == 'train': + split_name = 'train' + elif mode == 'dev': + if args.task_name == 'mnli': + split_name = 'dev_matched' + elif args.task_name == 'mnli-mm': + split_name = 'dev_mismatched' + else: + split_name = 'dev' + elif mode == 'test': + if args.task_name == 'mnli': + split_name = 'test_matched' + elif args.task_name == 'mnli-mm': + split_name = 'test_mismatched' + else: + split_name = 'test' + else: + raise NotImplementedError + + self.support_emb = np.load(os.path.join(args.data_dir, "train_{}.npy".format(args.demo_filter_model))) + self.query_emb = np.load(os.path.join(args.data_dir, "{}_{}.npy".format(split_name, args.demo_filter_model))) + logger.info("Load embeddings (for demonstration filtering) from {}".format(os.path.join(args.data_dir, "{}_{}.npy".format(split_name, args.demo_filter_model)))) + + assert len(self.support_emb) == len(self.support_examples) + assert len(self.query_emb) == len(self.query_examples) + + # Size is expanded by num_sample + self.size = len(self.query_examples) * self.num_sample + + # Prepare examples (especially for using demonstrations) + support_indices = list(range(len(self.support_examples))) + self.example_idx = [] + for sample_idx in range(self.num_sample): + for query_idx in range(len(self.query_examples)): + # If training, exclude the current example. Else keep all. + if self.use_demo and args.demo_filter: + # Need sentence_transformers for demonstrations, + # which is not included in the requirements for us, but see original LM-BFF repo. + from sentence_transformers import SentenceTransformer, util + + # Demonstration filtering + candidate = [support_idx for support_idx in support_indices + if support_idx != query_idx or mode != "train"] + sim_score = [] + for support_idx in candidate: + sim_score.append((support_idx, util.pytorch_cos_sim(self.support_emb[support_idx], self.query_emb[query_idx]))) + sim_score.sort(key=lambda x: x[1], reverse=True) + if self.num_labels == 1: + # Regression task + limit_each_label = int(len(sim_score) // 2 * args.demo_filter_rate) + count_each_label = {'0': 0, '1': 0} + context_indices = [] + + if args.debug_mode: + print("Query %s: %s" % (self.query_examples[query_idx].label, self.query_examples[query_idx].text_a)) # debug + for support_idx, score in sim_score: + if count_each_label['0' if float(self.support_examples[support_idx].label) <= median_mapping[args.task_name] else '1'] < limit_each_label: + count_each_label['0' if float(self.support_examples[support_idx].label) <= median_mapping[args.task_name] else '1'] += 1 + context_indices.append(support_idx) + if args.debug_mode: + print(" %.4f %s | %s" % (score, self.support_examples[support_idx].label, self.support_examples[support_idx].text_a)) # debug + else: + limit_each_label = int(len(sim_score) // self.num_labels * args.demo_filter_rate) + count_each_label = {label: 0 for label in self.label_list} + context_indices = [] + + if args.debug_mode: + print("Query %s: %s" % (self.query_examples[query_idx].label, self.query_examples[query_idx].text_a)) # debug + for support_idx, score in sim_score: + if count_each_label[self.support_examples[support_idx].label] < limit_each_label: + count_each_label[self.support_examples[support_idx].label] += 1 + context_indices.append(support_idx) + if args.debug_mode: + print(" %.4f %s | %s" % (score, self.support_examples[support_idx].label, self.support_examples[support_idx].text_a)) # debug + else: + # Using demonstrations without filtering + context_indices = [support_idx for support_idx in support_indices + if support_idx != query_idx or mode != "train"] + + # We'll subsample context_indices further later. + self.example_idx.append((query_idx, context_indices, sample_idx)) + + # If it is not training, we pre-process the data; otherwise, we process the data online. + if mode != "train": + self.features = [] + _ = 0 + for query_idx, context_indices, bootstrap_idx in self.example_idx: + # The input (query) example + example = self.query_examples[query_idx] + # The demonstrations + supports = self.select_context([self.support_examples[i] for i in context_indices]) + + if args.template_list is not None: + template = args.template_list[sample_idx % len(args.template_list)] # Use template in order + else: + template = args.template + self.features.append(self.convert_fn( + example=example, + supports=supports, + use_demo=self.use_demo, + label_list=self.label_list, + prompt=args.prompt, + template=template, + sfc_template=getattr(args, "icl_sfc_prompt", None), + label_word_list=self.label_word_list, + verbose=True if _ == 0 else False, + )) + + _ += 1 + else: + self.features = None + + def select_context(self, context_examples): + """ + Select demonstrations from provided examples. + """ + max_demo_per_label = 1 + counts = {k: 0 for k in self.label_list} + if len(self.label_list) == 1: + # Regression + counts = {'0': 0, '1': 0} + selection = [] + + if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail: + # For GPT-3's in-context learning, we sample gpt3_in_context_num demonstrations randomly. + order = np.random.permutation(len(context_examples)) + for i in range(min(self.args.gpt3_in_context_num, len(order))): + selection.append(context_examples[order[i]]) + else: + # Our sampling strategy + order = np.random.permutation(len(context_examples)) + + for i in order: + label = context_examples[i].label + if len(self.label_list) == 1: + # Regression + label = '0' if float(label) <= median_mapping[self.args.task_name] else '1' + if counts[label] < max_demo_per_label: + selection.append(context_examples[i]) + counts[label] += 1 + if sum(counts.values()) == len(counts) * max_demo_per_label: + break + + assert len(selection) > 0 + + return selection + + def __len__(self): + return self.size + + def __getitem__(self, i): + if self.features is None: + query_idx, context_indices, bootstrap_idx = self.example_idx[i] + # The input (query) example + example = self.query_examples[query_idx] + # The demonstrations + supports = self.select_context([self.support_examples[i] for i in context_indices]) + + if self.args.template_list is not None: + template = self.args.template_list[sample_idx % len(self.args.template_list)] + else: + template = self.args.template + + features = self.convert_fn( + example=example, + supports=supports, + use_demo=self.use_demo, + label_list=self.label_list, + prompt=self.args.prompt, + template=template, + label_word_list=self.label_word_list, + verbose=False, + ) + + else: + features = self.features[i] + + return features + + def get_labels(self): + return self.label_list + + + def convert_fn( + self, + example, + supports, + use_demo=False, + label_list=None, + prompt=False, + template=None, + sfc_template=None, + label_word_list=None, + verbose=False + ): + """ + Returns a list of processed "InputFeatures". + """ + max_length = self.args.max_seq_length + + # Prepare labels + label_map = {label: i for i, label in enumerate(label_list)} # Mapping the label names to label ids + if len(label_list) == 1: + # Regression + label_map = {'0': 0, '1': 1} + + # Get example's label id (for training/inference) + if example.label is None: + example_label = None + elif len(label_list) == 1: + # Regerssion + example_label = float(example.label) + else: + example_label = label_map[example.label] + + # Prepare other features + if not use_demo: + # No using demonstrations + inputs = tokenize_multipart_input( + input_text_list=input_example_to_tuple(example), + max_length=max_length, + tokenizer=self.tokenizer, + task_name=self.args.task_name, + prompt=prompt, + template=template, + label_word_list=label_word_list, + first_sent_limit=self.args.first_sent_limit, + other_sent_limit=self.args.other_sent_limit, + ) + features = OurInputFeatures(**inputs, label=example_label) + + else: + # Using demonstrations + + # Max length + if self.args.double_demo: + # When using demonstrations, double the maximum length + # Note that in this case, args.max_seq_length is the maximum length for a single sentence + max_length = max_length * 2 + if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail: + # When using GPT-3's in-context learning, take the maximum tokenization length of the model (512) + if self.tokenizer.model_type == "gpt2": + max_length = 1024 + elif self.tokenizer.model_type == "opt": + max_length = 2048 + else: + max_length = 512 + + # All input sentences, including the query and the demonstrations, are put into augmented_examples, + # and are numbered based on the order (starting from 0). For single sentence tasks, the input (query) + # is the sentence 0; for sentence-pair tasks, the input (query) is the sentence 0 and 1. Note that for GPT-3's + # in-context learning, the input (query) might be at the end instead of the beginning (gpt3_in_context_head) + augmented_example = [] + query_text = input_example_to_tuple(example) # Input sentence list for query + support_by_label = [[] for i in range(len(label_map))] + + if self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail: + support_labels = [] + augmented_example = query_text + for support_example in supports: + augmented_example += input_example_to_tuple(support_example) + current_label = support_example.label + if len(label_list) == 1: + current_label = '0' if float(current_label) <= median_mapping[self.args.task_name] else '1' # Regression + support_labels.append(label_map[current_label]) + else: + # Group support examples by label + for label_name, label_id in label_map.items(): + if len(label_list) == 1: + # Regression + for support_example in filter(lambda s: ('0' if float(s.label) <= median_mapping[self.args.task_name] else '1') == label_name, supports): + support_by_label[label_id] += input_example_to_tuple(support_example) + else: + for support_example in filter(lambda s: s.label == label_name, supports): + support_by_label[label_id] += input_example_to_tuple(support_example) + + augmented_example = query_text + for label_id in range(len(label_map)): + augmented_example += support_by_label[label_id] + + # Tokenization (based on the template) + inputs = tokenize_multipart_input( + input_text_list=augmented_example, + max_length=max_length, + tokenizer=self.tokenizer, + task_name=self.args.task_name, + prompt=prompt, + template=template, + label_word_list=label_word_list, + first_sent_limit=self.args.first_sent_limit, + other_sent_limit=self.args.other_sent_limit, + truncate_head=self.args.truncate_head, + gpt3=self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail, + support_labels=None if not (self.args.gpt3_in_context_head or self.args.gpt3_in_context_tail) else support_labels + ) + if sfc_template is not None: + # Process sfc example + if verbose: + logger.info("*** SFC Example ***") + sfc_feature = self.convert_fn( + example, supports, use_demo=use_demo, label_list=label_list, prompt=prompt, template=sfc_template, label_word_list=label_word_list, verbose=verbose + ) + features = OurInputFeatures(**inputs, label=example_label, sfc_input_ids=sfc_feature.input_ids, sfc_attention_mask=sfc_feature.attention_mask, sfc_mask_pos=sfc_feature.mask_pos) + else: + features = OurInputFeatures(**inputs, label=example_label) + + if verbose: + logger.info("*** Example ***") + logger.info("guid: %s" % (example.guid)) + logger.info("features: %s" % features) + logger.info("text: %s" % self.tokenizer.decode(features.input_ids)) + + return features + + + diff --git a/baselines/mezo/medium_models/src/kernel_solvers.py b/baselines/mezo/medium_models/src/kernel_solvers.py new file mode 100644 index 0000000..03dd4b9 --- /dev/null +++ b/baselines/mezo/medium_models/src/kernel_solvers.py @@ -0,0 +1,298 @@ +from transformers.utils import logging +import torch +import torch.nn.functional as F +from sklearn.svm import SVC, SVR +from sklearn.linear_model import LogisticRegressionCV +logger = logging.get_logger(__name__) + +class BaseKernelSolver: + def __init__(self, args): + self.args = args + + # initialized with fit() + self.num_labels = None + self.kernel_dtype = None + + def get_regularized_kernel(self, kernel): + if self.args.kernel_regularization: + _, S, _ = torch.svd(kernel) + op_norm = S.max() + + reg = (self.args.kernel_regularization * op_norm).to(kernel.dtype) + + identity = torch.eye(kernel.shape[1], dtype=kernel.dtype).unsqueeze(0) + return kernel + identity * reg + else: + return kernel + + def metrics(self): + return {} + + def get_target_coords(self, targets): + if self.num_labels == 1: # Regression + return targets.flatten().to(self.kernel_dtype).unsqueeze(1) + else: + return torch.nn.functional.one_hot(targets.flatten(), self.num_labels).to(self.kernel_dtype) + + def loss(self, preds, targets): + targets_coords = self.get_target_coords(targets) + return 1/targets_coords.shape[0] * ((preds - targets_coords)**2).sum().item() + + def fit(self, train_kernel, train_targets, train_logits=None): + raise NotImplementedError("BaseKernelSolver is just the abstract base class") + + def predict(self, eval_kernel, eval_targets, eval_logits=None): + raise NotImplementedError("BaseKernelSolver is just the abstract base class") + + +class LstsqKernelSolver(BaseKernelSolver): + def __init__(self, args): + super().__init__(args) + + # initialized with fit() + self.kernel_solution = None + self.residual = None + self.rank = None + + def metrics(self): + metrics_dict = super().metrics() + if self.rank is not None: + if self.rank.numel() > 1: + for i,r in enumerate(self.rank.tolist()): + metrics_dict["rank{}".format(i)] = r + else: + metrics_dict["rank0"] = self.rank.item() + return metrics_dict + + def fit(self, train_kernel, train_targets, train_logits=None): + self.num_labels = train_kernel.size(0) + self.kernel_dtype = train_kernel.dtype + + kernel = self.get_regularized_kernel(train_kernel) + train_targets_coords = self.get_target_coords(train_targets) + + if train_logits is not None and self.args.f0_scaling > 0: + train_targets_coords -= train_logits / self.args.f0_scaling + + self.kernel_solution, self.residuals, self.rank, _ = torch.linalg.lstsq(kernel, train_targets_coords.t()) + + def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs): + assert self.kernel_solution is not None, "Must call fit() before predict()" + assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()" + + eval_preds = torch.bmm( + eval_kernel.transpose(1, 2), + self.kernel_solution.unsqueeze(2) + ).squeeze(2).transpose(0, 1) # shape [#dataset_outer, #classes] + + if eval_logits is not None and self.args.f0_scaling > 0: + eval_preds += eval_logits / self.args.f0_scaling + + eval_loss = self.loss(eval_preds, eval_targets) + return eval_loss, eval_preds + + +class AsymmetricLstsqKernelSolver(LstsqKernelSolver): + def __init__(self, args): + super().__init__(args) + + self.N = None + self.train_targets = None + + def fit(self, train_kernel, train_targets, train_logits=None): + self.num_labels = train_kernel.size(0) + self.kernel_dtype = train_kernel.dtype + assert self.num_labels == 1, "SVMKernelSolver only works for regression tasks or binary_classification" + + kernel = self.get_regularized_kernel(train_kernel) + train_targets_coords = self.get_target_coords(train_targets) + + if train_logits is not None and self.args.f0_scaling > 0: + train_targets_coords -= train_logits / self.args.f0_scaling + + kernel = kernel.squeeze() + H = torch.zeros(kernel.shape) + Y = train_targets_coords.squeeze() + N = H.shape[0] + + for i in range(N): + for j in range(N): + H[i,j] = Y[i] * (kernel[i,j]* Y[j]) + + # # system with biases + # A = torch.zeros(2*N + 2, 2*N + 2, dtype=self.kernel_dtype) + # A[0, 2:2+N] = Y + # A[1, 2+N:] = Y + # A[2:2+N, 0] = Y + # A[2+N:, 1] = Y + # A[2:2+N, 2:2+N] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later + # A[2:2+N, 2+N:] = H + # A[2+N:, 2:2+N] = H.T + # A[2+N:, 2+N:] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later + + # B = torch.zeros(2*N+2, dtype=self.kernel_dtype) + # B[2:] = 1 + + # system without biases + A = torch.zeros(2*N, 2*N, dtype=self.kernel_dtype) + A[:N, :N] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later + A[:N, N:] = H + A[N:, :N] = H.T + A[N:, N:] = torch.eye(N) / self.args.kernel_gamma # scale by 1/gamma later + B = torch.ones(2*N, dtype=self.kernel_dtype) + + self.N = N + self.Y = Y + self.kernel_solution, self.residuals, self.rank, _ = torch.linalg.lstsq(A, B) + + def predict(self, eval_kernel, eval_targets, eval_logits=None, eval_kernel_flipped=None, **unused_kwargs): + assert self.kernel_solution is not None, "Must call fit() before predict()" + assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()" + + N = self.N + # beta_bias = self.kernel_solution[0] + # alpha_bias = self.kernel_solution[1] + # alpha = self.kernel_solution[2:2+N].unsqueeze(0) + # beta = self.kernel_solution[2+N:].unsqueeze(0) + alpha = self.kernel_solution[:N].unsqueeze(0) + beta = self.kernel_solution[N:].unsqueeze(0) + + omega = torch.bmm( + eval_kernel.transpose(1, 2), + (alpha*self.Y).unsqueeze(2) + ).squeeze(2).transpose(0, 1) #+ alpha_bias + nu = torch.bmm( + eval_kernel_flipped.transpose(1, 2), + (beta*self.Y).unsqueeze(2) + ).squeeze(2).transpose(0, 1) #+ beta_bias + + eval_preds = (self.args.kernel_lambda * omega + (1-self.args.kernel_lambda) * nu) + + if eval_logits is not None and self.args.f0_scaling > 0: + eval_preds += eval_logits / self.args.f0_scaling + + eval_loss = self.loss(eval_preds, eval_targets) + return eval_loss, eval_preds + + +class SVRKernelSolver(BaseKernelSolver): + def __init__(self, args): + super().__init__(args) + + self.svms = None + + def fit(self, train_kernel, train_targets, train_logits=None): + self.num_labels = train_kernel.size(0) + self.kernel_dtype = train_kernel.dtype + + kernel = self.get_regularized_kernel(train_kernel) + train_targets_coords = self.get_target_coords(train_targets) + + if train_logits is not None and self.args.f0_scaling > 0: + train_targets_coords -= train_logits / self.args.f0_scaling + + self.svms = [] + for k in range(self.num_labels): + svm = SVR(kernel='precomputed') + svm.fit(kernel[k].cpu().numpy(), train_targets_coords[:,k].cpu().t().numpy()) + self.svms.append(svm) + + def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs): + assert self.svms is not None, "Must call fit() before predict()" + assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()" + + eval_preds = [] + for k in range(self.num_labels): + predict_k = self.svms[k].predict(eval_kernel[k].cpu().t().numpy()) + eval_preds.append(torch.tensor(predict_k, dtype=self.kernel_dtype, device=eval_kernel.device)) + eval_preds = torch.stack(eval_preds, dim=1) + print(eval_preds, eval_targets) + + if eval_logits is not None and self.args.f0_scaling > 0: + eval_preds += eval_logits / self.args.f0_scaling + + eval_loss = self.loss(eval_preds, eval_targets) + return eval_loss, eval_preds + + +class SVCKernelSolver(BaseKernelSolver): + def __init__(self, args): + super().__init__(args) + + self.svms = None + + def fit(self, train_kernel, train_targets, train_logits=None): + self.num_labels = train_kernel.size(0) + self.kernel_dtype = train_kernel.dtype + assert self.num_labels == 1, "SVMKernelSolver only works for binary_classification" + assert train_logits is None, "SVMKernelSolver does not support train_logits" + + kernel = self.get_regularized_kernel(train_kernel) + train_targets = ((train_targets + 1) / 2).int() # convert back from {-1, 1} to {0, 1} + + self.svms = [] + for k in range(self.num_labels): + svm = SVC(kernel='precomputed') + svm.fit(kernel[k].cpu().numpy(), train_targets.cpu().numpy()) + self.svms.append(svm) + + def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs): + assert self.svms is not None, "Must call fit() before predict()" + assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()" + assert eval_logits is None, "SVMKernelSolver does not support train_logits" + + eval_preds = [] + for k in range(self.num_labels): + predict_k = self.svms[k].predict(eval_kernel[k].cpu().t().numpy()) + eval_preds.append(torch.tensor(predict_k, dtype=self.kernel_dtype, device=eval_kernel.device)) + eval_preds = torch.stack(eval_preds, dim=1) + + eval_preds = (eval_preds * 2 - 1) # convert back from {0, 1} to {-1, 1} + + eval_loss = self.loss(eval_preds, eval_targets) + return eval_loss, eval_preds + + +class LogisticKernelSolver(BaseKernelSolver): + def __init__(self, args): + super().__init__(args) + + self.logistic_model = None + + def fit(self, train_kernel, train_targets, train_logits=None): + self.num_labels = train_kernel.size(0) + self.kernel_dtype = train_kernel.dtype + assert self.num_labels == 1, "SVMKernelSolver only works for binary_classification" + + kernel = self.get_regularized_kernel(train_kernel).squeeze(0) + train_targets = ((train_targets + 1) / 2).int() # convert back from {-1, 1} to {0, 1} + + self.logistic_model = LogisticRegressionCV(max_iter=10000, random_state=0) + self.logistic_model.fit(kernel.cpu().numpy(), train_targets.cpu().numpy()) + + def predict(self, eval_kernel, eval_targets, eval_logits=None, **unused_kwargs): + assert self.logistic_model is not None, "Must call fit() before predict()" + assert eval_kernel.size(0) == self.num_labels, "Number of labels in eval_kernel must match fit()" + + log_proba = self.logistic_model.predict_log_proba(eval_kernel.cpu().squeeze().t().numpy()) + log_proba = torch.tensor(log_proba, dtype=self.kernel_dtype, device=eval_kernel.device) + + eval_loss = self.loss(log_proba, eval_targets) + + eval_preds = (log_proba[:,1] - log_proba[:,0]).unsqueeze(1) + + return eval_loss, eval_preds + + def loss(self, preds, targets): + targets = ((targets + 1) / 2).long() # convert back from {-1, 1} to {0, 1} + return F.cross_entropy(preds, targets).item() + + + +SOLVERS = { + "lstsq": LstsqKernelSolver, + "svr": SVRKernelSolver, + "svc": SVCKernelSolver, + "asym": AsymmetricLstsqKernelSolver, + "logistic": LogisticKernelSolver +} diff --git a/baselines/mezo/medium_models/src/kernel_trainer.py b/baselines/mezo/medium_models/src/kernel_trainer.py new file mode 100644 index 0000000..e62cd45 --- /dev/null +++ b/baselines/mezo/medium_models/src/kernel_trainer.py @@ -0,0 +1,471 @@ +########## The following part was originally copied from Transformers' trainer (3.4.0) and then changed heavily to compute eNTKs. ########## + +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +The trainer for computing eNTKs +""" + +import os +from typing import Any, Callable, Dict, List, Optional, Tuple, Union +import re + +import torch +import torch.nn as nn +from torch.utils.data.dataloader import DataLoader +from torch.utils.data.dataset import Dataset +from torch.utils.data.sampler import SequentialSampler + +from functorch import vmap, jvp, jacrev, make_functional_with_buffers + +import transformers +from transformers.data.data_collator import DataCollator +from transformers.file_utils import is_torch_tpu_available + +from transformers.modeling_utils import PreTrainedModel +from transformers.training_args import TrainingArguments +from transformers.trainer import SequentialDistributedSampler +from transformers.trainer_utils import PredictionOutput, EvalPrediction +from transformers.utils import logging +if is_torch_tpu_available(): + import torch_xla.core.xla_model as xm +import gc +from transformers.trainer_utils import TrainOutput + +from src.linearhead_trainer import varsize_tensor_all_gather, LinearHeadTrainer + +import numpy as np +from tqdm import tqdm +from src.kernel_solvers import SOLVERS + +logger = logging.get_logger(__name__) + + +class LogitModelWrapper(nn.Module): + def __init__(self, model, binary_classification): + super().__init__() + self.model = model + self.binary_classification = binary_classification + + def forward(self, input_ids, attention_mask, mask_pos): + logits = self.model(input_ids, attention_mask, mask_pos=mask_pos)[0] # don't provide labels + if self.binary_classification: + assert logits.size(1) == 2, "--binary_classification should have 2 logits" + logits = (logits[:,1] - logits[:,0]).unsqueeze(-1) + return logits + # label = (label * 2 - 1).float() # convert from {0, 1} to {-1, 1} + + +def param_to_buffer(module, module_name, predicate): + """Turns all parameters of a module into buffers.""" + modules = module.named_modules(prefix=str(module_name)) + next(modules) # Skip itself + + params = [] + for name, param in module.named_parameters(recurse=False, prefix=str(module_name)): + if predicate(name): + params.append((name.split(".")[-1], param)) + + for name, param in params: + delattr(module, name) # Unregister parameter + module.register_buffer(name, param) + for name, module in modules: + param_to_buffer(module, name, predicate) + + +class KernelTrainerFunc(LinearHeadTrainer): + """ + Adding some functions based on Transformers' Trainer class. + """ + + def __init__( + self, + model: PreTrainedModel, + args: TrainingArguments, + data_collator: Optional[DataCollator] = None, + train_dataset: Optional[Dataset] = None, + eval_dataset: Optional[Dataset] = None, + *posargs, + **kwargs + ): + super().__init__(model, args, data_collator, train_dataset, eval_dataset, *posargs, **kwargs) + + self.grad_dim = None + self.train_train_kernel = None + self.train_targets = None + self.num_labels = None + + self.kernel_formula = args.kernel_formula + + def convert_to_buffer(name): + if args.exclude_embeddings: + if "embed" in name: + logger.info("Excluding {}".format(name)) + return True + + if args.exclude_head: + if "head" in name: + logger.info("Excluding {}".format(name)) + return True + + if args.only_biases: + if "bias" not in name: + logger.info("Excluding {}".format(name)) + return True + + if args.exclude_first_layers != -1: + if 'layers' in name: + layer_num = re.search('layers.(.+?).[a-z]', name).group(1) + if int(layer_num) < args.exclude_first_layers: + return True + else: + return False + elif 'embed_tokens' in name or 'embed_positions' in name: + return True + + if model.model_args.apply_lora: + if name.startswith('roberta') and "lora" not in name: + logger.info("Excluding {}".format(name)) + return True + return False + + param_to_buffer(self.model, "", convert_to_buffer) + + + def get_unshuffled_dataloader(self, dataset: Optional[Dataset] = None, sharded: bool = False, batch_size: Optional[int] = -1): + if sharded and is_torch_tpu_available(): + sampler = SequentialDistributedSampler( + dataset, num_replicas=xm.xrt_world_size(), rank=xm.get_ordinal() + ) + elif sharded and self.args.local_rank != -1: + sampler = SequentialDistributedSampler(dataset) + else: + sampler = SequentialSampler(dataset) + + bs = self.args.per_device_eval_batch_size if batch_size == -1 else batch_size + data_loader = DataLoader( + dataset, + sampler=sampler, + batch_size=bs, + collate_fn=self.data_collator, + drop_last=self.args.dataloader_drop_last, + ) + + return data_loader + + def profile_memory(self): + import gc + for obj in gc.get_objects(): + try: + if torch.is_tensor(obj) or (hasattr(obj, 'data') and torch.is_tensor(obj.data)): + print(type(obj), obj.size()) + except: + pass + + def compute_kernel_inner(self, curried_fn, curried_jacobian_fn, grads_outer, dataset_inner): + + # Use per_device_eval_batch_size for outer loop (which is always the training dataset + dataloader_inner = self.get_unshuffled_dataloader(dataset_inner, sharded=False, batch_size=self.args.per_device_eval_batch_size) + kernel_blocks = [] + targets_inner = [] + + for inputs_inner in tqdm(dataloader_inner, desc="Computing kernel inner"): + + for k, v in inputs_inner.items(): + if isinstance(v, torch.Tensor): + inputs_inner[k] = v.to(self.args.device) + + def get_ntk_slice(tangents): + _, jvps = curried_fn(inputs_inner.get("input_ids"), inputs_inner.get("attention_mask"), inputs_inner.get("mask_pos"), tangents) + return jvps + + if self.args.kernel_formula == "signgd": + grads_inner = curried_jacobian_fn(inputs_inner.get("input_ids"), inputs_inner.get("attention_mask"), inputs_inner.get("mask_pos")) + block = sum(torch.einsum('olw,ikw->olik', j1.sign().flatten(2).to(torch.float64), j2.sign().flatten(2).to(torch.float64)).cpu() for j1, j2 in zip(grads_outer, grads_inner)) + else: + block = vmap(vmap(get_ntk_slice))(grads_outer).to(torch.float64).cpu() # N_outer x C_outer x N_inner x C_inner + + kernel_blocks.append(block.detach()) + label = inputs_inner.get("labels") + if self.args.binary_classification: + label = (label * 2 - 1).float() # convert from {0, 1} to {-1, 1} + targets_inner.append(label) + + # del grads_inner + del block + del inputs_inner + + torch.cuda.empty_cache() + gc.collect() + + return ( + torch.cat(kernel_blocks, dim=2) if kernel_blocks else torch.tensor([]), + torch.cat(targets_inner, dim=0) if targets_inner else torch.tensor([]) + ) + + def compute_kernel_outer(self, dataset_outer, dataset_inner): + # Use train_batch_size for outer loop (which is always the training dataset) + dataloader_outer = self.get_unshuffled_dataloader(dataset_outer, sharded=True, batch_size=self.args.per_device_train_batch_size) + + model_wrapper = LogitModelWrapper(self.model, self.args.binary_classification) + model_wrapper.eval() + for param in model_wrapper.parameters(): + param.requires_grad_(True) + + model_fn, params, buffers = make_functional_with_buffers(model_wrapper) + + jacobian_fn = jacrev(model_fn) + + def curried_jacobian_fn(input_ids, attention_mask, mask_pos): + return jacobian_fn(params, buffers, input_ids, attention_mask, mask_pos) + + def curried_fn(input_ids, attention_mask, mask_pos, tangent): + def curried_model_fn(params_): + return model_fn(params_, buffers, input_ids, attention_mask, mask_pos) + return jvp(curried_model_fn, (params,), (tangent,)) + + kernel_rows = [] + + inner_targets = None + + for inputs_outer in tqdm(dataloader_outer, desc="Computing kernel outer"): + for k, v in inputs_outer.items(): + if isinstance(v, torch.Tensor): + inputs_outer[k] = v.to(self.args.device) + + grads_outer = curried_jacobian_fn(inputs_outer.get("input_ids"), inputs_outer.get("attention_mask"), inputs_outer.get("mask_pos")) + if self.args.kernel_formula == 'asymmetric_signgd': + grads_outer = tuple(g.sign() for g in grads_outer) + + # assert len(tuple(model_wrapper.model.named_parameters())) == len(grads_outer) + + # for (name,param), grad in zip(model_wrapper.named_parameters(), grads_outer): + # print(name, grad[(grad != 0).all(-1)]) + # assert param.shape == grad.shape[2:], f"{name} {param.shape} {grad[2:].shape}" + # if (grad == 0).all(): + # print(name, param.numel()) + + if self.grad_dim is None: + self.grad_dim = sum(np.prod(x.shape[2:]) for x in grads_outer) + # assert self.grad_dim == num_params, "gradient dim not constant: {} and {}".format(self.grad_dim, num_params) + + kernel_blocks, inner_targets = ( + self.compute_kernel_inner(curried_fn, curried_jacobian_fn, grads_outer, dataset_inner)) + + kernel_rows.append(kernel_blocks) + + del grads_outer + del inputs_outer + del kernel_blocks + + torch.cuda.empty_cache() + gc.collect() + + + kernel = torch.cat(kernel_rows, dim=0) + + return ( + kernel, + inner_targets + ) + + def compute_kernel_sharded(self, dataset_outer, dataset_inner): + assert self.kernel_formula in ["sgd", "asymmetric_signgd", "signgd"], "only sgd and asymmetric_signgd are supported by torchfunc for now" + + with torch.no_grad(): + kernel, inner_targets = self.compute_kernel_outer(dataset_outer, dataset_inner) + + if self.args.local_rank != -1: + logger.info("Starting to gather kernel across GPUs") + kernel = varsize_tensor_all_gather(kernel.to(self.args.device), torch.distributed.get_world_size()) + logger.info("Finished gathering kernel across GPUs") + + return kernel, inner_targets + + def compute_model_logits_cached(self, eval_dataset): + if self.args.load_kernels is not None: + output_dir = self.args.load_kernels + else: + output_dir = self.args.output_dir + logit_file_name = f"{eval_dataset.mode}_logits_{eval_dataset.task_name}.pt" + logit_path = os.path.join(output_dir, logit_file_name) + + if os.path.exists(logit_path) and not self.args.overwrite_kernels: + logger.info(f"Starting to load logits from {logit_path}.") + logits, targets = torch.load(logit_path) + logger.info(f"Finished loading logits from {logit_path}.") + else: + logger.info(f"Starting to compute the {eval_dataset.mode} logits.") + dataloader = self.get_unshuffled_dataloader(eval_dataset) + + model_wrapper = LogitModelWrapper(self.model, self.args.binary_classification) + model_wrapper.eval() + + logits = [] + targets = [] + with torch.no_grad(): + for inputs in dataloader: + for k, v in inputs.items(): + if isinstance(v, torch.Tensor): + inputs[k] = v.to(self.args.device) + + label = inputs.get("labels") + if self.args.binary_classification: + label = (label * 2 - 1).float() # convert from {0, 1} to {-1, 1} + + preds = model_wrapper(inputs.get("input_ids"), inputs.get("attention_mask"), inputs.get("mask_pos")) + logits.append(preds.detach().cpu()) + targets.append(label.cpu()) + + logits = torch.cat(logits, dim=0) + targets = torch.cat(targets, dim=0) + + logger.info(f"Finished computing the {eval_dataset.mode} logits.") + + if self.is_world_process_zero(): + torch.save((logits, targets), logit_path) + return logits, targets + + def reshape_kernel_and_targets(self, kernel, targets): + # reshape kernel to previous format + if self.num_labels is None: + self.num_labels = kernel.shape[1] + assert self.num_labels == kernel.shape[1], "label dim not constant: {} and {}".format(self.num_labels, kernel.shape[1]) + assert self.num_labels == kernel.shape[3], "label dim not constant: {} and {}".format(self.num_labels, kernel.shape[3]) + + if self.num_labels > 1: # multi logit + targets = torch.nn.functional.one_hot(targets.squeeze(), self.num_labels) + + size1 = kernel.shape[0] * kernel.shape[1] + size2 = kernel.shape[2] * kernel.shape[3] + # kernel = kernel.transpose(0, 1).transpose(2, 3) + return kernel.reshape(1, size1, size2), targets.reshape(-1) + + def compute_kernel_cached(self, eval_dataset): + kernel_file_name = f"{eval_dataset.mode}_kernels_{eval_dataset.task_name}.pt" + kernel_path = os.path.join(self.args.output_dir, kernel_file_name) + + if os.path.exists(kernel_path) and not self.args.overwrite_kernels: + logger.info(f"Starting to load kernels from {kernel_path}.") + (train_eval_kernel, eval_targets) = torch.load(kernel_path) + logger.info(f"Finished loading kernels from {kernel_path}.") + else: + logger.info(f"Starting to compute the train-{eval_dataset.mode} kernel.") + train_eval_kernel, eval_targets = self.compute_kernel_sharded( + self.train_dataset, eval_dataset, + ) + logger.info(f"Finshed computing the train-{eval_dataset.mode} kernel.") + + train_eval_kernel = train_eval_kernel.cpu() + eval_targets = eval_targets.cpu() + + if self.args.kernel_formula == 'asymmetric_signgd': + logger.info(f"Starting to compute the flipped train-{eval_dataset.mode} kernel.") + if eval_dataset == self.train_dataset: + train_eval_kernel_flipped = train_eval_kernel + else: + train_eval_kernel_flipped, _ = self.compute_kernel_sharded( + eval_dataset, self.train_dataset, + ) + logger.info(f"Finshed computing the flipped train-{eval_dataset.mode} kernel.") + + train_eval_kernel_flipped = train_eval_kernel_flipped.cpu() + train_eval_kernel_flipped = train_eval_kernel_flipped.permute(2, 3, 0, 1) + train_eval_kernel = torch.stack([train_eval_kernel, train_eval_kernel_flipped], dim=0) + + if self.is_world_process_zero(): + torch.save((train_eval_kernel, eval_targets), kernel_path) + return train_eval_kernel, eval_targets + + + def train(self, model_path=None, dev_objective=None): + if self.args.from_linearhead and model_path is None: + super().train(model_path, dev_objective) # Train output layer using LinearHeadTrainer + + if self.args.load_kernels is None: + eval_dataset = self.train_dataset + self.train_train_kernel, self.train_targets = self.compute_kernel_cached(eval_dataset) + + return TrainOutput(0, 0.0, {}), None + + def evaluate(self, eval_dataset: Optional[Dataset] = None) -> Dict[str, float]: + if eval_dataset is None: + eval_dataset = self.eval_dataset + + if self.args.load_kernels is not None: + logger.info(f"Starting to load kernels from {self.args.load_kernels}.") + kernel_file_name = f"{eval_dataset.mode}_kernels_{eval_dataset.task_name}.pt" + load_kernel_path = os.path.join(self.args.load_kernels, kernel_file_name) + (train_eval_kernel, eval_targets) = torch.load(load_kernel_path) + + kernel_file_name = f"{self.train_dataset.mode}_kernels_{self.train_dataset.task_name}.pt" + load_kernel_path = os.path.join(self.args.load_kernels, kernel_file_name) + (self.train_train_kernel, self.train_targets) = torch.load(load_kernel_path) + logger.info(f"Finished loading kernels from {self.args.load_kernels}.") + else: + assert self.train_train_kernel is not None, "train_train_kernel is None, did you forget to call train()?" + train_eval_kernel, eval_targets = self.compute_kernel_cached(eval_dataset) + + if self.args.kernel_formula == 'asymmetric_signgd': + train_eval_kernel_flipped = train_eval_kernel[1] + train_eval_kernel_flipped, _ = self.reshape_kernel_and_targets(train_eval_kernel_flipped, eval_targets) + + train_eval_kernel = train_eval_kernel[0] + train_train_kernel = self.train_train_kernel[0] + else: + train_eval_kernel_flipped = None + train_train_kernel = self.train_train_kernel + + train_train_kernel, train_targets = self.reshape_kernel_and_targets(train_train_kernel, self.train_targets) + train_eval_kernel, eval_targets = self.reshape_kernel_and_targets(train_eval_kernel, eval_targets) + + # get train and test logits + if self.args.adjust_for_init: + train_logits, _ = self.compute_model_logits_cached(self.train_dataset) + eval_logits, _ = self.compute_model_logits_cached(eval_dataset) + train_logits = train_logits.reshape(-1, 1) + eval_logits = eval_logits.reshape(-1, 1) + else: + train_logits, eval_logits = None, None + + metrics = {} + + solver = SOLVERS[self.args.kernel_solver](self.args) + solver.fit(train_train_kernel, train_targets, train_logits) + eval_error, eval_preds = solver.predict(train_eval_kernel, eval_targets, eval_logits, eval_kernel_flipped=train_eval_kernel_flipped) + eval_preds = eval_preds.reshape(-1, self.num_labels) + if self.num_labels > 1: + eval_targets = eval_targets.reshape(-1, self.num_labels).argmax(-1) + + if self.args.binary_classification: # Make sure to compute loss before this transformation! + eval_preds = torch.cat([-eval_preds, eval_preds], dim=-1) # convert back to two logits + eval_targets = ((eval_targets + 1) / 2).long() # convert back from {-1, 1} to {0, 1} + + if self.compute_metrics is not None: + metrics = self.compute_metrics(EvalPrediction(predictions=eval_preds.numpy(), label_ids=eval_targets.numpy())) + + # Prefix all keys with eval_ + for key in list(metrics.keys()): + if not key.startswith("eval_"): + metrics[f"eval_{key}"] = metrics.pop(key) + metrics["eval_loss"] = eval_error + + metrics.update(solver.metrics()) + metrics["grad_dim"] = self.grad_dim + + output = PredictionOutput(predictions=eval_preds.numpy(), label_ids=eval_targets.numpy(), metrics=metrics) + self.log(output.metrics) + + return output diff --git a/baselines/mezo/medium_models/src/linearhead_trainer.py b/baselines/mezo/medium_models/src/linearhead_trainer.py new file mode 100644 index 0000000..45905bc --- /dev/null +++ b/baselines/mezo/medium_models/src/linearhead_trainer.py @@ -0,0 +1,232 @@ +########## The following part was originally copied from Transformers' trainer (3.4.0) and then changed heavily for linear head probing. ########## + +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +A trainer for finding linear probing solutions +""" + +import collections +from src.models import MODEL_TYPES +import torch +import torch.nn.functional as F +from typing import Any, Callable, Dict, List, Optional, Tuple, Union +from sklearn.linear_model import LinearRegression, LogisticRegression, LogisticRegressionCV + +import transformers +from torch.utils.data.dataset import Dataset +from transformers.trainer_utils import TrainOutput +from transformers.utils import logging + +logger = logging.get_logger(__name__) + + +def tensor_all_gather(tensor: torch.Tensor, distributed_world_size: int): + tensor_list = [torch.zeros_like(tensor) for _ in range(distributed_world_size)] + torch.distributed.all_gather(tensor_list=tensor_list, tensor=tensor) + return torch.cat(tensor_list, dim=0) + + +def varsize_tensor_all_gather(tensor: torch.Tensor, distributed_world_size: int): + tensor = tensor.contiguous() + + dim_tensor = torch.tensor([tensor.size(0)], dtype=torch.int64, device=tensor.device) + dim_tensor = tensor_all_gather(dim_tensor, distributed_world_size).cpu() + max_size = dim_tensor.max() + + padded = torch.empty(max_size, *tensor.shape[1:], + dtype=tensor.dtype, + device=tensor.device) + padded[:tensor.shape[0]] = tensor + + ag = tensor_all_gather(padded, distributed_world_size) + slices = [] + for i, sz in enumerate(dim_tensor): + start_idx = i * max_size + end_idx = start_idx + sz.item() + + if end_idx > start_idx: + slices.append(ag[start_idx:end_idx]) + + return torch.cat(slices, dim=0) + +def get_token_prediction_layer(model): + if isinstance(model, tuple(MODEL_TYPES.values())): + if model.label_word_list is not None: + lm_head = model.get_lm_head_fn() + if model.model_type == "roberta": + return lm_head.decoder + elif model.model_type == "bert": + return lm_head.predictions.decoder + elif model.model_type == "gpt2" or model.model_type == 'opt': + return lm_head # TODO: has no bias so linear regression with bias will fail right now + else: + return model.classifier + elif isinstance(model, transformers.RobertaForSequenceClassification): + return model.classifier.out_proj + elif isinstance(model, transformers.BertForSequenceClassification): + return model.classifier + else: + raise NotImplementedError(model.__class__) + +def extract_features(model, *args, **kwargs): + """some magic for getting features pre last layer""" + features = {} + def hook(model_, input_, output_): + features["features"] = input_[0].detach() + + get_token_prediction_layer(model).register_forward_hook(hook) + model.forward(*args, **kwargs) + return features["features"] + +def extract_features_prob(model, *args, **kwargs): + """some magic for getting all logits""" + output = model.forward(*args, **kwargs) + return F.softmax(output[1].detach(), -1) + + + +class LinearHeadTrainer(transformers.Trainer): + """ + Adding some functions based on Transformers' Trainer class. + """ + + def train(self, model_path=None, dev_objective=None): + """ + Main training entry point. + + The training logic is directly borrowed from transformers.Trainer (version 3.0.2). + Add early stopping. + """ + self.best_dir = None + self.objective = -float("inf") + + model = self.model + model.eval() + + train_dataloader = self.get_train_dataloader() + targets = [] + features = [] + + logger.info("Starting to get features for training dataset") + with torch.no_grad(): + for step, inputs in enumerate(train_dataloader): + for k, v in inputs.items(): + if isinstance(v, torch.Tensor): + inputs[k] = v.to(self.args.device) + if self.args.prob_as_feature: + features.append(extract_features_prob(model, **inputs)) + else: + features.append(extract_features(model, **inputs)) + targets.append(inputs["labels"]) + logger.info("Finished getting features for training dataset") + + features = torch.cat(features, dim=0) + targets = torch.cat(targets, dim=0) + + if self.args.local_rank != -1: + logger.info("Starting to gather features across workers") + features = varsize_tensor_all_gather(features, torch.distributed.get_world_size()) + targets = varsize_tensor_all_gather(targets, torch.distributed.get_world_size()) + logger.info("Finished gathering features across workers") + + features = features.cpu() + targets = targets.cpu() + + if model.num_labels == 1: # Regression + targets_coords = targets.squeeze().unsqueeze(-1).float() + reg = LinearRegression().fit(features.numpy(), targets_coords.numpy()) + else: + use_bias = (model.model_type != 'opt' and model.model_type != 'gpt2') or self.args.prob_as_feature + tol = 0.01 if self.args.lp_early_stopping else 1e-4 # 1e-4 is scipy default + max_iter = 1000 if self.args.lp_early_stopping else 5000 + reg = LogisticRegressionCV(max_iter=max_iter, fit_intercept=use_bias, multi_class="multinomial", random_state=0, tol=tol).fit(features.numpy(), targets.numpy()) + # targets_coords = torch.nn.functional.one_hot(targets.squeeze(), model.num_labels).float() + + logger.info("Fitting linear regression") + + logger.info("Assigning weights to model") + # print(head.out_proj.weight.shape, head.out_proj.bias.shape) + # print(reg.coef_.shape, reg.intercept_.shape) + decoder = get_token_prediction_layer(model) + coef_torch = torch.tensor(reg.coef_, device=decoder.weight.device, dtype=decoder.weight.dtype) + if use_bias: + bias_torch = torch.tensor(reg.intercept_, device=decoder.weight.device, dtype=decoder.weight.dtype) + + if model.num_labels == 2 and coef_torch.size(0) == 1: + coef_torch = torch.cat([-coef_torch / 2, coef_torch / 2], dim=0) + if use_bias: + bias_torch = torch.cat([-bias_torch / 2, bias_torch / 2], dim=0) + + if decoder.weight.shape[0] == model.num_labels: + decoder.weight.data = coef_torch + if use_bias: + decoder.bias.data = bias_torch + else: + if self.args.prob_as_feature: + model.lr_weight = coef_torch + if use_bias: + model.lr_bias = bias_torch + else: + decoder.weight.data[model.label_word_list,:] = coef_torch + if use_bias: + decoder.bias.data[model.label_word_list] = bias_torch + + if model.num_labels == 1: # Regression + logits = torch.tensor(reg.predict(features.numpy())) + train_loss = torch.nn.functional.mse_loss(logits, targets_coords, reduction="none") + else: + logits = torch.tensor(reg.predict_log_proba(features.numpy())) + train_loss = torch.nn.functional.cross_entropy(logits, targets.squeeze(), reduction="none") + + return TrainOutput(0, train_loss, {}), self.objective + + + + """ + Difference compared to original implementation: return output instead of output.metrics (so there is also the logits) + """ + def evaluate(self, eval_dataset: Optional[Dataset] = None) -> Dict[str, float]: + """ + Run evaluation and returns metrics. + + The calling script will be responsible for providing a method to compute metrics, as they are + task-dependent (pass it to the init :obj:`compute_metrics` argument). + + You can also subclass and override this method to inject custom behavior. + + Args: + eval_dataset (:obj:`Dataset`, `optional`): + Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, + columns not accepted by the ``model.forward()`` method are automatically removed. It must implement + the :obj:`__len__` method. + + Returns: + A dictionary containing the evaluation loss and the potential metrics computed from the predictions. + """ + if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): + raise ValueError("eval_dataset must implement __len__") + + eval_dataloader = self.get_eval_dataloader(eval_dataset) + + output = self.prediction_loop(eval_dataloader, description="Evaluation") + + self.log(output.metrics) + + if self.args.tpu_metrics_debug or self.args.debug: + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + + return output diff --git a/baselines/mezo/medium_models/src/modeling_opt.py b/baselines/mezo/medium_models/src/modeling_opt.py new file mode 100644 index 0000000..5fb5551 --- /dev/null +++ b/baselines/mezo/medium_models/src/modeling_opt.py @@ -0,0 +1,1385 @@ +# coding=utf-8 +# Copyright 2022 The Fairseq Authors and The HuggingFace Inc. team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" PyTorch OPT model.""" +import random +from typing import List, Optional, Tuple, Union + +import torch +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +from transformers.activations import ACT2FN +from transformers.modeling_outputs import ( + BaseModelOutputWithPast, + CausalLMOutputWithPast, + QuestionAnsweringModelOutput, + SequenceClassifierOutputWithPast, +) +from transformers.modeling_utils import PreTrainedModel +from transformers.utils import ( + add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, + logging, + replace_return_docstrings, +) +#from .configuration_opt import OPTConfig + +import loralib as lora + + +logger = logging.get_logger(__name__) + +_CHECKPOINT_FOR_DOC = "facebook/opt-350m" +_CONFIG_FOR_DOC = "OPTConfig" +_TOKENIZER_FOR_DOC = "GPT2Tokenizer" + +# Base model docstring +_EXPECTED_OUTPUT_SHAPE = [1, 8, 1024] + +# SequenceClassification docstring +_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION = "ArthurZ/opt-350m-dummy-sc" +_SEQ_CLASS_EXPECTED_LOSS = 1.71 +_SEQ_CLASS_EXPECTED_OUTPUT = "'LABEL_0'" + +OPT_PRETRAINED_MODEL_ARCHIVE_LIST = [ + "facebook/opt-125m", + "facebook/opt-350m", + "facebook/opt-1.3b", + "facebook/opt-2.7b", + "facebook/opt-6.7b", + "facebook/opt-13b", + "facebook/opt-30b", + # See all OPT models at https://huggingface.co/models?filter=opt +] + +from transformers import PretrainedConfig +class OPTConfig(PretrainedConfig): + r""" + This is the configuration class to store the configuration of a [`OPTModel`]. It is used to instantiate a OPT model + according to the specified arguments, defining the model architecture. Instantiating a configuration with the + defaults will yield a similar configuration to that of the OPT + [facebook/opt-350m](https://huggingface.co/facebook/opt-350m) architecture. + + Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the + documentation from [`PretrainedConfig`] for more information. + + + Args: + vocab_size (`int`, *optional*, defaults to 50272): + Vocabulary size of the OPT model. Defines the number of different tokens that can be represented by the + `inputs_ids` passed when calling [`OPTModel`] + hidden_size (`int`, *optional*, defaults to 768): + Dimensionality of the layers and the pooler layer. + num_hidden_layers (`int`, *optional*, defaults to 12): + Number of decoder layers. + ffn_dim (`int`, *optional*, defaults to 3072): + Dimensionality of the "intermediate" (often named feed-forward) layer in decoder. + num_attention_heads (`int`, *optional*, defaults to 12): + Number of attention heads for each attention layer in the Transformer decoder. + activation_function (`str` or `function`, *optional*, defaults to `"relu"`): + The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`, + `"relu"`, `"silu"` and `"gelu_new"` are supported. + max_position_embeddings (`int`, *optional*, defaults to 2048): + The maximum sequence length that this model might ever be used with. Typically set this to something large + just in case (e.g., 512 or 1024 or 2048). + do_layer_norm_before (`bool`, *optional*, defaults to `True`): + Whether to perform layer normalization before the attention block. + word_embed_proj_dim (`int`, *optional*): + `word_embed_proj_dim` can be set to down-project word embeddings, *e.g.* `opt-350m`. Defaults to + `hidden_size`. + dropout (`float`, *optional*, defaults to 0.1): + The dropout probability for all fully connected layers in the embeddings, encoder, and pooler. + attention_dropout (`float`, *optional*, defaults to 0.0): + The dropout ratio for the attention probabilities. + layerdrop: (`float`, *optional*, defaults to 0.0): + The LayerDrop probability. See the [LayerDrop paper](see https://arxiv.org/abs/1909.11556) for more + details. + init_std (`float`, *optional*, defaults to 0.02): + The standard deviation of the truncated_normal_initializer for initializing all weight matrices. + use_cache (`bool`, *optional*, defaults to `True`): + Whether or not the model should return the last key/values attentions (not used by all models). + + Example: + + ```python + >>> from transformers import OPTConfig, OPTModel + + >>> # Initializing a OPT facebook/opt-large style configuration + >>> configuration = OPTConfig() + + >>> # Initializing a model (with random weights) from the facebook/opt-large style configuration + >>> model = OPTModel(configuration) + + >>> # Accessing the model configuration + >>> configuration = model.config + ```""" + model_type = "opt" + keys_to_ignore_at_inference = ["past_key_values"] + + def __init__( + self, + vocab_size=50272, + hidden_size=768, + num_hidden_layers=12, + ffn_dim=3072, + max_position_embeddings=2048, + do_layer_norm_before=True, + _remove_final_layer_norm=False, + word_embed_proj_dim=None, + dropout=0.1, + attention_dropout=0.0, + num_attention_heads=12, + activation_function="relu", + layerdrop=0.0, + init_std=0.02, + use_cache=True, + pad_token_id=1, + bos_token_id=2, + eos_token_id=2, + apply_lora=False, + lora_r=None, + lora_alpha=None, + **kwargs + ): + super().__init__( + pad_token_id=pad_token_id, + bos_token_id=bos_token_id, + eos_token_id=eos_token_id, + **kwargs, + ) + self.vocab_size = vocab_size + self.max_position_embeddings = max_position_embeddings + self.num_attention_heads = num_attention_heads + self.word_embed_proj_dim = word_embed_proj_dim if word_embed_proj_dim is not None else hidden_size + self.ffn_dim = ffn_dim + self.hidden_size = hidden_size + self.num_hidden_layers = num_hidden_layers + self.dropout = dropout + self.attention_dropout = attention_dropout + self.activation_function = activation_function + self.init_std = init_std + self.layerdrop = layerdrop + self.use_cache = use_cache + self.do_layer_norm_before = do_layer_norm_before + + self.apply_lora = apply_lora + self.lora_r = lora_r + self.lora_alpha = lora_alpha + + # Note that the only purpose of `_remove_final_layer_norm` is to keep backward compatibility + # with checkpoints that have been fine-tuned before transformers v4.20.1 + # see https://github.com/facebookresearch/metaseq/pull/164 + self._remove_final_layer_norm = _remove_final_layer_norm + + + +def _make_causal_mask(input_ids_shape: torch.Size, dtype: torch.dtype, past_key_values_length: int = 0): + """ + Make causal mask used for bi-directional self-attention. + """ + bsz, tgt_len = input_ids_shape + mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min)) + mask_cond = torch.arange(mask.size(-1)) + mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0) + mask = mask.to(dtype) + + if past_key_values_length > 0: + mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype), mask], dim=-1) + return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length) + + +def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None): + """ + Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`. + """ + bsz, src_len = mask.size() + tgt_len = tgt_len if tgt_len is not None else src_len + + expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype) + + inverted_mask = 1.0 - expanded_mask + + return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min) + + +class OPTLearnedPositionalEmbedding(nn.Embedding): + """ + This module learns positional embeddings up to a fixed maximum size. + """ + + def __init__(self, num_embeddings: int, embedding_dim: int): + # OPT is set up so that if padding_idx is specified then offset the embedding ids by 2 + # and adjust num_embeddings appropriately. Other models don't have this hack + self.offset = 2 + super().__init__(num_embeddings + self.offset, embedding_dim) + + def forward(self, attention_mask: torch.LongTensor, past_key_values_length: int = 0): + """`input_ids_shape` is expected to be [bsz x seqlen].""" + attention_mask = attention_mask.long() + + # create positions depending on attention_mask + positions = (torch.cumsum(attention_mask, dim=1).type_as(attention_mask) * attention_mask).long() - 1 + + # cut positions if `past_key_values_length` is > 0 + positions = positions[:, past_key_values_length:] + + return super().forward(positions + self.offset) + + +class OPTAttention(nn.Module): + """Multi-headed attention from 'Attention Is All You Need' paper""" + + def __init__( + self, + embed_dim: int, + num_heads: int, + dropout: float = 0.0, + is_decoder: bool = False, + bias: bool = True, + apply_lora: bool = False, + lora_r: int = None, + lora_alpha: int = None + ): + super().__init__() + self.embed_dim = embed_dim + self.num_heads = num_heads + self.dropout = dropout + self.head_dim = embed_dim // num_heads + + if (self.head_dim * num_heads) != self.embed_dim: + raise ValueError( + f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}" + f" and `num_heads`: {num_heads})." + ) + self.scaling = self.head_dim**-0.5 + self.is_decoder = is_decoder + + if apply_lora: + self.q_proj = lora.Linear(embed_dim, embed_dim, lora_r, lora_alpha=lora_alpha, bias=bias) + else: + self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + if apply_lora: + self.v_proj = lora.Linear(embed_dim, embed_dim, lora_r, lora_alpha=lora_alpha, bias=bias) + else: + self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + # original OPT code + #self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + #self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + #self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias) + + def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): + return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous() + + def forward( + self, + hidden_states: torch.Tensor, + key_value_states: Optional[torch.Tensor] = None, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: bool = False, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: + """Input shape: Batch x Time x Channel""" + + # if key_value_states are provided this layer is used as a cross-attention layer + # for the decoder + is_cross_attention = key_value_states is not None + + bsz, tgt_len, _ = hidden_states.size() + + # get query proj + query_states = self.q_proj(hidden_states) * self.scaling + # get key, value proj + if is_cross_attention and past_key_value is not None: + # reuse k,v, cross_attentions + key_states = past_key_value[0] + value_states = past_key_value[1] + elif is_cross_attention: + # cross_attentions + key_states = self._shape(self.k_proj(key_value_states), -1, bsz) + value_states = self._shape(self.v_proj(key_value_states), -1, bsz) + elif past_key_value is not None: + # reuse k, v, self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + key_states = torch.cat([past_key_value[0], key_states], dim=2) + value_states = torch.cat([past_key_value[1], value_states], dim=2) + else: + # self_attention + key_states = self._shape(self.k_proj(hidden_states), -1, bsz) + value_states = self._shape(self.v_proj(hidden_states), -1, bsz) + + if self.is_decoder: + # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. + # Further calls to cross_attention layer can then reuse all cross-attention + # key/value_states (first "if" case) + # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of + # all previous decoder key/value_states. Further calls to uni-directional self-attention + # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) + # if encoder bi-directional self-attention `past_key_value` is always `None` + past_key_value = (key_states, value_states) + + proj_shape = (bsz * self.num_heads, -1, self.head_dim) + query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape) + key_states = key_states.view(*proj_shape) + value_states = value_states.view(*proj_shape) + + src_len = key_states.size(1) + attn_weights = torch.bmm(query_states, key_states.transpose(1, 2)) + + if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len): + raise ValueError( + f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is" + f" {attn_weights.size()}" + ) + + if attention_mask is not None: + if attention_mask.size() != (bsz, 1, tgt_len, src_len): + raise ValueError( + f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}" + ) + attn_weights = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attention_mask + attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + # upcast to fp32 if the weights are in fp16. Please see https://github.com/huggingface/transformers/pull/17437 + if attn_weights.dtype == torch.float16: + attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(torch.float16) + else: + attn_weights = nn.functional.softmax(attn_weights, dim=-1) + + if layer_head_mask is not None: + if layer_head_mask.size() != (self.num_heads,): + raise ValueError( + f"Head mask for a single layer should be of size {(self.num_heads,)}, but is" + f" {layer_head_mask.size()}" + ) + attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len) + + if output_attentions: + # this operation is a bit awkward, but it's required to + # make sure that attn_weights keeps its gradient. + # In order to do so, attn_weights have to be reshaped + # twice and have to be reused in the following + attn_weights_reshaped = attn_weights.view(bsz, self.num_heads, tgt_len, src_len) + attn_weights = attn_weights_reshaped.view(bsz * self.num_heads, tgt_len, src_len) + else: + attn_weights_reshaped = None + + attn_probs = nn.functional.dropout(attn_weights, p=self.dropout, training=self.training) + + attn_output = torch.bmm(attn_probs, value_states) + + if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim): + raise ValueError( + f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is" + f" {attn_output.size()}" + ) + + attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim) + attn_output = attn_output.transpose(1, 2) + + # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be + # partitioned aross GPUs when using tensor-parallelism. + attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim) + + attn_output = self.out_proj(attn_output) + + return attn_output, attn_weights_reshaped, past_key_value + + +class OPTDecoderLayer(nn.Module): + def __init__(self, config: OPTConfig): + super().__init__() + self.embed_dim = config.hidden_size + self.self_attn = OPTAttention( + embed_dim=self.embed_dim, + num_heads=config.num_attention_heads, + dropout=config.attention_dropout, + is_decoder=True, + apply_lora=config.apply_lora, + lora_r=config.lora_r, + lora_alpha=config.lora_alpha + ) + self.do_layer_norm_before = config.do_layer_norm_before + self.dropout = config.dropout + self.activation_fn = ACT2FN[config.activation_function] + + self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim) + self.fc1 = nn.Linear(self.embed_dim, config.ffn_dim) + self.fc2 = nn.Linear(config.ffn_dim, self.embed_dim) + self.final_layer_norm = nn.LayerNorm(self.embed_dim) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.Tensor] = None, + layer_head_mask: Optional[torch.Tensor] = None, + output_attentions: Optional[bool] = False, + use_cache: Optional[bool] = False, + past_key_value: Optional[Tuple[torch.Tensor]] = None, + ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]: + """ + Args: + hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` + attention_mask (`torch.FloatTensor`, *optional*): attention mask of size + `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values. + layer_head_mask (`torch.FloatTensor`, *optional*): mask for attention heads in a given layer of size + `(encoder_attention_heads,)`. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states + """ + + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Self Attention + hidden_states, self_attn_weights, present_key_value = self.self_attn( + hidden_states=hidden_states, + past_key_value=past_key_value, + attention_mask=attention_mask, + layer_head_mask=layer_head_mask, + output_attentions=output_attentions, + ) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + hidden_states = residual + hidden_states + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.self_attn_layer_norm(hidden_states) + + # Fully Connected + hidden_states_shape = hidden_states.shape + hidden_states = hidden_states.reshape(-1, hidden_states.size(-1)) + residual = hidden_states + + # 125m, 1.7B, ..., 175B applies layer norm BEFORE attention + if self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + hidden_states = self.fc1(hidden_states) + hidden_states = self.activation_fn(hidden_states) + + hidden_states = self.fc2(hidden_states) + hidden_states = nn.functional.dropout(hidden_states, p=self.dropout, training=self.training) + + hidden_states = (residual + hidden_states).view(hidden_states_shape) + + # 350m applies layer norm AFTER attention + if not self.do_layer_norm_before: + hidden_states = self.final_layer_norm(hidden_states) + + outputs = (hidden_states,) + + if output_attentions: + outputs += (self_attn_weights,) + + if use_cache: + outputs += (present_key_value,) + + return outputs + + +OPT_START_DOCSTRING = r""" + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`OPTConfig`]): + Model configuration class with all the parameters of the model. Initializing with a config file does not + load the weights associated with the model, only the configuration. Check out the + [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTPreTrainedModel(PreTrainedModel): + + config_class = OPTConfig + base_model_prefix = "model" + supports_gradient_checkpointing = True + _no_split_modules = ["OPTDecoderLayer"] + _keys_to_ignore_on_load_unexpected = [r"decoder\.version"] + + def _init_weights(self, module): + std = self.config.init_std + if isinstance(module, nn.Linear): + module.weight.data.normal_(mean=0.0, std=std) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=std) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, (OPTDecoder)): + module.gradient_checkpointing = value + + +OPT_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide + it. + + Indices can be obtained using [`GPT2Tokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + + Indices can be obtained using [`OPTTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see + `past_key_values`). + + If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] + and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more + information on the default strategy. + head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules in the encoder. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape + `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape + `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention + blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +class OPTDecoder(OPTPreTrainedModel): + """ + Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`OPTDecoderLayer`] + + Args: + config: OPTConfig + """ + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.dropout = config.dropout + self.layerdrop = config.layerdrop + self.padding_idx = config.pad_token_id + self.max_target_positions = config.max_position_embeddings + self.vocab_size = config.vocab_size + + self.embed_tokens = nn.Embedding(config.vocab_size, config.word_embed_proj_dim, self.padding_idx) + self.embed_positions = OPTLearnedPositionalEmbedding(config.max_position_embeddings, config.hidden_size) + + if config.word_embed_proj_dim != config.hidden_size: + self.project_out = nn.Linear(config.hidden_size, config.word_embed_proj_dim, bias=False) + else: + self.project_out = None + + if config.word_embed_proj_dim != config.hidden_size: + self.project_in = nn.Linear(config.word_embed_proj_dim, config.hidden_size, bias=False) + else: + self.project_in = None + + # Note that the only purpose of `config._remove_final_layer_norm` is to keep backward compatibility + # with checkpoints that have been fine-tuned before transformers v4.20.1 + # see https://github.com/facebookresearch/metaseq/pull/164 + if config.do_layer_norm_before and not config._remove_final_layer_norm: + self.final_layer_norm = nn.LayerNorm(config.hidden_size) + else: + self.final_layer_norm = None + + self.layers = nn.ModuleList([OPTDecoderLayer(config) for _ in range(config.num_hidden_layers)]) + + self.gradient_checkpointing = False + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embed_tokens + + def set_input_embeddings(self, value): + self.embed_tokens = value + + # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask + def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length): + # create causal mask + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + combined_attention_mask = None + if input_shape[-1] > 1: + combined_attention_mask = _make_causal_mask( + input_shape, inputs_embeds.dtype, past_key_values_length=past_key_values_length + ).to(inputs_embeds.device) + + if attention_mask is not None: + # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len] + expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to( + inputs_embeds.device + ) + combined_attention_mask = ( + expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask + ) + + return combined_attention_mask + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`OPTTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + """ + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + # embed positions + if attention_mask is None: + attention_mask = torch.ones(inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device) + pos_embeds = self.embed_positions(attention_mask, past_key_values_length) + + attention_mask = self._prepare_decoder_attention_mask( + attention_mask, input_shape, inputs_embeds, past_key_values_length + ) + + if self.project_in is not None: + inputs_embeds = self.project_in(inputs_embeds) + + hidden_states = inputs_embeds + pos_embeds + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + # check if head_mask has a correct number of layers specified if desired + for attn_mask, mask_name in zip([head_mask], ["head_mask"]): + if attn_mask is not None: + if attn_mask.size()[0] != (len(self.layers)): + raise ValueError( + f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" + f" {head_mask.size()[0]}." + ) + + for idx, decoder_layer in enumerate(self.layers): + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + if use_cache: + logger.warning( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + if self.final_layer_norm is not None: + hidden_states = self.final_layer_norm(hidden_states) + + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +@add_start_docstrings( + "The bare OPT Model outputting raw hidden-states without any specific head on top.", + OPT_START_DOCSTRING, +) +class OPTModel(OPTPreTrainedModel): + def __init__(self, config: OPTConfig): + super().__init__(config) + self.decoder = OPTDecoder(config) + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.decoder.embed_tokens = value + + def get_decoder(self): + return self.decoder + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + processor_class=_TOKENIZER_FOR_DOC, + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=BaseModelOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_EXPECTED_OUTPUT_SHAPE, + ) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn) + decoder_outputs = self.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + if not return_dict: + return decoder_outputs + + return BaseModelOutputWithPast( + last_hidden_state=decoder_outputs.last_hidden_state, + past_key_values=decoder_outputs.past_key_values, + hidden_states=decoder_outputs.hidden_states, + attentions=decoder_outputs.attentions, + ) + + +class OPTForCausalLM(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config): + super().__init__(config) + self.model = OPTModel(config) + + # the lm_head weight is automatically tied to the embed tokens weight + self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + def get_output_embeddings(self): + return self.lm_head + + def set_output_embeddings(self, new_embeddings): + self.lm_head = new_embeddings + + def set_decoder(self, decoder): + self.model.decoder = decoder + + def get_decoder(self): + return self.model.decoder + + @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, CausalLMOutputWithPast]: + r""" + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): + Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you + provide it. + + Indices can be obtained using [`OPTTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + head_mask (`torch.Tensor` of shape `(num_hidden_layers, num_attention_heads)`, *optional*): + Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`): + Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of + shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of + shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional + tensors are only required when the model is used as a decoder in a Sequence to Sequence model. + + Contains pre-computed hidden-states (key and values in the self-attention blocks and in the + cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those + that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of + all `decoder_input_ids` of shape `(batch_size, sequence_length)`. + inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. + This is useful if you want more control over how to convert `input_ids` indices into associated vectors + than the model's internal embedding lookup matrix. + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should either be in `[0, ..., + config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored + (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding + (see `past_key_values`). + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under + returned tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors + for more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. + + Returns: + + Example: + + ```python + >>> from transformers import GPT2Tokenizer, OPTForCausalLM + + >>> model = OPTForCausalLM.from_pretrained("facebook/opt-350m") + >>> tokenizer = GPT2Tokenizer.from_pretrained("facebook/opt-350m") + + >>> prompt = "Hey, are you consciours? Can you talk to me?" + >>> inputs = tokenizer(prompt, return_tensors="pt") + + >>> # Generate + >>> generate_ids = model.generate(inputs.input_ids, max_length=30) + >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] + "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you." + ```""" + + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) + outputs = self.model.decoder( + input_ids=input_ids, + attention_mask=attention_mask, + head_mask=head_mask, + past_key_values=past_key_values, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + logits = self.lm_head(outputs[0]).contiguous() + + loss = None + if labels is not None: + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + # Flatten the tokens + loss_fct = CrossEntropyLoss() + loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + def prepare_inputs_for_generation(self, input_ids, past=None, attention_mask=None, use_cache=None, **kwargs): + # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly + if attention_mask is None: + attention_mask = input_ids.new_ones(input_ids.shape) + + if past: + input_ids = input_ids[:, -1:] + # first step, decoder_cached_states are empty + return { + "input_ids": input_ids, # encoder_outputs is defined. input_ids not needed + "attention_mask": attention_mask, + "past_key_values": past, + "use_cache": use_cache, + } + + @staticmethod + def _reorder_cache(past, beam_idx): + reordered_past = () + for layer_past in past: + reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) + return reordered_past + + +@add_start_docstrings( + """ + The OPT Model transformer with a sequence classification head on top (linear layer). + + [`OPTForSequenceClassification`] uses the last token in order to do the classification, as other causal models + (e.g. GPT-2) do. + + Since it does classification on the last token, it requires to know the position of the last token. If a + `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If + no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the + padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in + each row of the batch). + """, + OPT_START_DOCSTRING, +) +class OPTForSequenceClassification(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.num_labels = config.num_labels + self.model = OPTModel(config) + self.score = nn.Linear(config.word_embed_proj_dim, self.num_labels, bias=False) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @add_code_sample_docstrings( + processor_class=_TOKENIZER_FOR_DOC, + checkpoint=_CHECKPOINT_FOR_SEQUENCE_CLASSIFICATION, + output_type=SequenceClassifierOutputWithPast, + config_class=_CONFIG_FOR_DOC, + expected_output=_SEQ_CLASS_EXPECTED_OUTPUT, + expected_loss=_SEQ_CLASS_EXPECTED_LOSS, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, SequenceClassifierOutputWithPast]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + logits = self.score(hidden_states) + + if input_ids is not None: + batch_size, sequence_length = input_ids.shape[:2] + else: + batch_size, sequence_length = inputs_embeds.shape[:2] + + if self.config.pad_token_id is None: + sequence_lengths = -1 + else: + if input_ids is not None: + sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1 + else: + sequence_lengths = -1 + logger.warning( + f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be " + "unexpected if using padding tokens in conjunction with `inputs_embeds.`" + ) + + pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths] + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(pooled_logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(pooled_logits, labels) + if not return_dict: + output = (pooled_logits,) + transformer_outputs[1:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutputWithPast( + loss=loss, + logits=pooled_logits, + past_key_values=transformer_outputs.past_key_values, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value + + +@add_start_docstrings( + """ + The OPT Model transformer with a span classification head on top for extractive question-answering tasks like SQuAD + (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + """, + OPT_START_DOCSTRING, +) +class OPTForQuestionAnswering(OPTPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"lm_head.weight"] + + def __init__(self, config: OPTConfig): + super().__init__(config) + self.model = OPTModel(config) + self.qa_outputs = nn.Linear(config.word_embed_proj_dim, 2) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(OPT_INPUTS_DOCSTRING) + @replace_return_docstrings(output_type=QuestionAnsweringModelOutput, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.Tensor]]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + start_positions: Optional[torch.LongTensor] = None, + end_positions: Optional[torch.LongTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, QuestionAnsweringModelOutput]: + r""" + start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + + Returns: + + Example: + + ```python + >>> from transformers import GPT2Tokenizer, OPTForQuestionAnswering + >>> import torch + + >>> torch.manual_seed(4) # doctest: +IGNORE_RESULT + >>> tokenizer = GPT2Tokenizer.from_pretrained("facebook/opt-350m") + + >>> # note: we are loading a OPTForQuestionAnswering from the hub here, + >>> # so the head will be randomly initialized, hence the predictions will be random + >>> model = OPTForQuestionAnswering.from_pretrained("facebook/opt-350m") + + >>> question, text = "Who was Jim Henson?", "Jim Henson was a nice puppet" + + >>> inputs = tokenizer(question, text, return_tensors="pt") + >>> with torch.no_grad(): + ... outputs = model(**inputs) + + >>> answer_start_index = outputs.start_logits.argmax() + >>> answer_end_index = outputs.end_logits.argmax() + + >>> predict_answer_tokens = inputs.input_ids[0, answer_start_index : answer_end_index + 1] + >>> predicted = tokenizer.decode(predict_answer_tokens) + >>> predicted + ' Henson?' + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + transformer_outputs = self.model( + input_ids, + past_key_values=past_key_values, + attention_mask=attention_mask, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + hidden_states = transformer_outputs[0] + + logits = self.qa_outputs(hidden_states) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + transformer_outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=transformer_outputs.hidden_states, + attentions=transformer_outputs.attentions, + ) + + def get_input_embeddings(self): + return self.model.decoder.embed_tokens + + def set_input_embeddings(self, value): + self.model.decoder.embed_tokens = value diff --git a/baselines/mezo/medium_models/src/modeling_roberta.py b/baselines/mezo/medium_models/src/modeling_roberta.py new file mode 100644 index 0000000..ed8ef85 --- /dev/null +++ b/baselines/mezo/medium_models/src/modeling_roberta.py @@ -0,0 +1,1620 @@ +# coding=utf-8 +# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. +# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""PyTorch RoBERTa model.""" + +import math +from typing import List, Optional, Tuple, Union + +import torch +import torch.utils.checkpoint +from torch import nn +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss + +from transformers.activations import ACT2FN, gelu +from transformers.modeling_outputs import ( + BaseModelOutputWithPastAndCrossAttentions, + BaseModelOutputWithPoolingAndCrossAttentions, + CausalLMOutputWithCrossAttentions, + MaskedLMOutput, + MultipleChoiceModelOutput, + QuestionAnsweringModelOutput, + SequenceClassifierOutput, + TokenClassifierOutput, +) +from transformers.modeling_utils import PreTrainedModel +from transformers.pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer +from transformers.utils import ( + add_code_sample_docstrings, + add_start_docstrings, + add_start_docstrings_to_model_forward, + logging, + replace_return_docstrings, +) +# from transformers.models.roberta.configuration_roberta import RobertaConfig + +import loralib as lora + +logger = logging.get_logger(__name__) + +_CHECKPOINT_FOR_DOC = "roberta-base" +_CONFIG_FOR_DOC = "RobertaConfig" + +ROBERTA_PRETRAINED_MODEL_ARCHIVE_LIST = [ + "roberta-base", + "roberta-large", + "roberta-large-mnli", + "distilroberta-base", + "roberta-base-openai-detector", + "roberta-large-openai-detector", + # See all RoBERTa models at https://huggingface.co/models?filter=roberta +] + +from transformers import BertConfig +class RobertaConfig(BertConfig): + r""" + This is the configuration class to store the configuration of a :class:`~transformers.RobertaModel` or a + :class:`~transformers.TFRobertaModel`. It is used to instantiate a RoBERTa model according to the specified + arguments, defining the model architecture. + Configuration objects inherit from :class:`~transformers.PretrainedConfig` and can be used to control the model + outputs. Read the documentation from :class:`~transformers.PretrainedConfig` for more information. + The :class:`~transformers.RobertaConfig` class directly inherits :class:`~transformers.BertConfig`. It reuses the + same defaults. Please check the parent class for more information. + Examples:: + >>> from transformers import RobertaConfig, RobertaModel + >>> # Initializing a RoBERTa configuration + >>> configuration = RobertaConfig() + >>> # Initializing a model from the configuration + >>> model = RobertaModel(configuration) + >>> # Accessing the model configuration + >>> configuration = model.config + """ + model_type = "roberta" + + def __init__(self, pad_token_id=1, bos_token_id=0, eos_token_id=2, apply_lora=False, lora_r=None, lora_alpha=None, **kwargs): + """Constructs RobertaConfig.""" + super().__init__(pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs) + + self.apply_lora = apply_lora + self.lora_r = lora_r + self.lora_alpha = lora_alpha + +class RobertaEmbeddings(nn.Module): + """ + Same as BertEmbeddings with a tiny tweak for positional embeddings indexing. + """ + + # Copied from transformers.models.bert.modeling_bert.BertEmbeddings.__init__ + def __init__(self, config): + super().__init__() + self.word_embeddings = nn.Embedding(config.vocab_size, config.hidden_size, padding_idx=config.pad_token_id) + self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.hidden_size) + self.token_type_embeddings = nn.Embedding(config.type_vocab_size, config.hidden_size) + + # self.LayerNorm is not snake-cased to stick with TensorFlow model variable name and be able to load + # any TensorFlow checkpoint file + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + # position_ids (1, len position emb) is contiguous in memory and exported when serialized + self.position_embedding_type = getattr(config, "position_embedding_type", "absolute") + self.register_buffer("position_ids", torch.arange(config.max_position_embeddings).expand((1, -1))) + self.register_buffer( + "token_type_ids", torch.zeros(self.position_ids.size(), dtype=torch.long), persistent=False + ) + + # End copy + self.padding_idx = config.pad_token_id + self.position_embeddings = nn.Embedding( + config.max_position_embeddings, config.hidden_size, padding_idx=self.padding_idx + ) + + def forward( + self, input_ids=None, token_type_ids=None, position_ids=None, inputs_embeds=None, past_key_values_length=0 + ): + if position_ids is None: + if input_ids is not None: + # Create the position ids from the input token ids. Any padded tokens remain padded. + position_ids = create_position_ids_from_input_ids(input_ids, self.padding_idx, past_key_values_length) + else: + position_ids = self.create_position_ids_from_inputs_embeds(inputs_embeds) + + if input_ids is not None: + input_shape = input_ids.size() + else: + input_shape = inputs_embeds.size()[:-1] + + seq_length = input_shape[1] + + # Setting the token_type_ids to the registered buffer in constructor where it is all zeros, which usually occurs + # when its auto-generated, registered buffer helps users when tracing the model without passing token_type_ids, solves + # issue #5664 + if token_type_ids is None: + if hasattr(self, "token_type_ids"): + buffered_token_type_ids = self.token_type_ids[:, :seq_length] + buffered_token_type_ids_expanded = buffered_token_type_ids.expand(input_shape[0], seq_length) + token_type_ids = buffered_token_type_ids_expanded + else: + token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=self.position_ids.device) + + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + token_type_embeddings = self.token_type_embeddings(token_type_ids) + + embeddings = inputs_embeds + token_type_embeddings + if self.position_embedding_type == "absolute": + position_embeddings = self.position_embeddings(position_ids) + embeddings += position_embeddings + embeddings = self.LayerNorm(embeddings) + embeddings = self.dropout(embeddings) + return embeddings + + def create_position_ids_from_inputs_embeds(self, inputs_embeds): + """ + We are provided embeddings directly. We cannot infer which are padded so just generate sequential position ids. + + Args: + inputs_embeds: torch.Tensor + + Returns: torch.Tensor + """ + input_shape = inputs_embeds.size()[:-1] + sequence_length = input_shape[1] + + position_ids = torch.arange( + self.padding_idx + 1, sequence_length + self.padding_idx + 1, dtype=torch.long, device=inputs_embeds.device + ) + return position_ids.unsqueeze(0).expand(input_shape) + + +# Copied from transformers.models.bert.modeling_bert.BertSelfAttention with Bert->Roberta +class RobertaSelfAttention(nn.Module): + def __init__(self, config, position_embedding_type=None): + super().__init__() + if config.hidden_size % config.num_attention_heads != 0 and not hasattr(config, "embedding_size"): + raise ValueError( + f"The hidden size ({config.hidden_size}) is not a multiple of the number of attention " + f"heads ({config.num_attention_heads})" + ) + + self.num_attention_heads = config.num_attention_heads + self.attention_head_size = int(config.hidden_size / config.num_attention_heads) + self.all_head_size = self.num_attention_heads * self.attention_head_size + + if getattr(config, "apply_lora", False): + self.query = lora.Linear(config.hidden_size, self.all_head_size, config.lora_r, lora_alpha=config.lora_alpha) + else: + self.query = nn.Linear(config.hidden_size, self.all_head_size) + + self.key = nn.Linear(config.hidden_size, self.all_head_size) + + if getattr(config, "apply_lora", False): + self.value = lora.Linear(config.hidden_size, self.all_head_size, config.lora_r, lora_alpha=config.lora_alpha) + else: + self.value = nn.Linear(config.hidden_size, self.all_head_size) + + self.dropout = nn.Dropout(config.attention_probs_dropout_prob) + self.position_embedding_type = position_embedding_type or getattr( + config, "position_embedding_type", "absolute" + ) + if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": + self.max_position_embeddings = config.max_position_embeddings + self.distance_embedding = nn.Embedding(2 * config.max_position_embeddings - 1, self.attention_head_size) + + self.is_decoder = config.is_decoder + + def transpose_for_scores(self, x: torch.Tensor) -> torch.Tensor: + new_x_shape = x.size()[:-1] + (self.num_attention_heads, self.attention_head_size) + x = x.view(new_x_shape) + return x.permute(0, 2, 1, 3) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + output_attentions: Optional[bool] = False, + output_key_value: Optional[bool] = False, + ) -> Tuple[torch.Tensor]: + mixed_query_layer = self.query(hidden_states) + + # If this is instantiated as a cross-attention module, the keys + # and values come from an encoder; the attention mask needs to be + # such that the encoder's padding tokens are not attended to. + is_cross_attention = encoder_hidden_states is not None + if is_cross_attention and past_key_value is not None: + # reuse k,v, cross_attentions + key_layer = past_key_value[0] + value_layer = past_key_value[1] + attention_mask = encoder_attention_mask + elif is_cross_attention: + key_layer = self.transpose_for_scores(self.key(encoder_hidden_states)) + value_layer = self.transpose_for_scores(self.value(encoder_hidden_states)) + attention_mask = encoder_attention_mask + elif past_key_value is not None: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + key_layer = torch.cat([past_key_value[0], key_layer], dim=2) + value_layer = torch.cat([past_key_value[1], value_layer], dim=2) + else: + key_layer = self.transpose_for_scores(self.key(hidden_states)) + value_layer = self.transpose_for_scores(self.value(hidden_states)) + + query_layer = self.transpose_for_scores(mixed_query_layer) + + use_cache = past_key_value is not None + if self.is_decoder or output_key_value: + # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states. + # Further calls to cross_attention layer can then reuse all cross-attention + # key/value_states (first "if" case) + # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of + # all previous decoder key/value_states. Further calls to uni-directional self-attention + # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case) + # if encoder bi-directional self-attention `past_key_value` is always `None` + past_key_value = (key_layer, value_layer) + + # Take the dot product between "query" and "key" to get the raw attention scores. + attention_scores = torch.matmul(query_layer, key_layer.transpose(-1, -2)) + + if self.position_embedding_type == "relative_key" or self.position_embedding_type == "relative_key_query": + query_length, key_length = query_layer.shape[2], key_layer.shape[2] + if use_cache: + position_ids_l = torch.tensor(key_length - 1, dtype=torch.long, device=hidden_states.device).view( + -1, 1 + ) + else: + position_ids_l = torch.arange(query_length, dtype=torch.long, device=hidden_states.device).view(-1, 1) + position_ids_r = torch.arange(key_length, dtype=torch.long, device=hidden_states.device).view(1, -1) + distance = position_ids_l - position_ids_r + + positional_embedding = self.distance_embedding(distance + self.max_position_embeddings - 1) + positional_embedding = positional_embedding.to(dtype=query_layer.dtype) # fp16 compatibility + + if self.position_embedding_type == "relative_key": + relative_position_scores = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) + attention_scores = attention_scores + relative_position_scores + elif self.position_embedding_type == "relative_key_query": + relative_position_scores_query = torch.einsum("bhld,lrd->bhlr", query_layer, positional_embedding) + relative_position_scores_key = torch.einsum("bhrd,lrd->bhlr", key_layer, positional_embedding) + attention_scores = attention_scores + relative_position_scores_query + relative_position_scores_key + + attention_scores = attention_scores / math.sqrt(self.attention_head_size) + if attention_mask is not None: + # Apply the attention mask is (precomputed for all layers in RobertaModel forward() function) + attention_scores = attention_scores + attention_mask + + # Normalize the attention scores to probabilities. + attention_probs = nn.functional.softmax(attention_scores, dim=-1) + + # This is actually dropping out entire tokens to attend to, which might + # seem a bit unusual, but is taken from the original Transformer paper. + attention_probs = self.dropout(attention_probs) + + # Mask heads if we want to + if head_mask is not None: + attention_probs = attention_probs * head_mask + + context_layer = torch.matmul(attention_probs, value_layer) + + context_layer = context_layer.permute(0, 2, 1, 3).contiguous() + new_context_layer_shape = context_layer.size()[:-2] + (self.all_head_size,) + context_layer = context_layer.view(new_context_layer_shape) + + outputs = (context_layer, attention_probs) if output_attentions else (context_layer,) + + if self.is_decoder or output_key_value: + outputs = outputs + (past_key_value,) + return outputs + + +# Copied from transformers.models.bert.modeling_bert.BertSelfOutput +class RobertaSelfOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertAttention with Bert->Roberta +class RobertaAttention(nn.Module): + def __init__(self, config, position_embedding_type=None): + super().__init__() + self.self = RobertaSelfAttention(config, position_embedding_type=position_embedding_type) + self.output = RobertaSelfOutput(config) + self.pruned_heads = set() + + def prune_heads(self, heads): + if len(heads) == 0: + return + heads, index = find_pruneable_heads_and_indices( + heads, self.self.num_attention_heads, self.self.attention_head_size, self.pruned_heads + ) + + # Prune linear layers + self.self.query = prune_linear_layer(self.self.query, index) + self.self.key = prune_linear_layer(self.self.key, index) + self.self.value = prune_linear_layer(self.self.value, index) + self.output.dense = prune_linear_layer(self.output.dense, index, dim=1) + + # Update hyper params and store pruned heads + self.self.num_attention_heads = self.self.num_attention_heads - len(heads) + self.self.all_head_size = self.self.attention_head_size * self.self.num_attention_heads + self.pruned_heads = self.pruned_heads.union(heads) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + output_attentions: Optional[bool] = False, + output_key_value: Optional[bool] = False, + ) -> Tuple[torch.Tensor]: + self_outputs = self.self( + hidden_states, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + output_key_value=output_key_value + ) + attention_output = self.output(self_outputs[0], hidden_states) + outputs = (attention_output,) + self_outputs[1:] # add attentions if we output them + return outputs + + +# Copied from transformers.models.bert.modeling_bert.BertIntermediate +class RobertaIntermediate(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.intermediate_size) + if isinstance(config.hidden_act, str): + self.intermediate_act_fn = ACT2FN[config.hidden_act] + else: + self.intermediate_act_fn = config.hidden_act + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.intermediate_act_fn(hidden_states) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertOutput +class RobertaOutput(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.intermediate_size, config.hidden_size) + self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + + def forward(self, hidden_states: torch.Tensor, input_tensor: torch.Tensor) -> torch.Tensor: + hidden_states = self.dense(hidden_states) + hidden_states = self.dropout(hidden_states) + hidden_states = self.LayerNorm(hidden_states + input_tensor) + return hidden_states + + +# Copied from transformers.models.bert.modeling_bert.BertLayer with Bert->Roberta +class RobertaLayer(nn.Module): + def __init__(self, config): + super().__init__() + self.chunk_size_feed_forward = config.chunk_size_feed_forward + self.seq_len_dim = 1 + self.attention = RobertaAttention(config) + self.is_decoder = config.is_decoder + self.add_cross_attention = config.add_cross_attention + if self.add_cross_attention: + if not self.is_decoder: + raise ValueError(f"{self} should be used as a decoder model if cross attention is added") + self.crossattention = RobertaAttention(config, position_embedding_type="absolute") + self.intermediate = RobertaIntermediate(config) + self.output = RobertaOutput(config) + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_value: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + output_attentions: Optional[bool] = False, + output_key_value: Optional[bool] = False, + ) -> Tuple[torch.Tensor]: + # decoder uni-directional self-attention cached key/values tuple is at positions 1,2 + self_attn_past_key_value = past_key_value[:2] if past_key_value is not None else None + self_attention_outputs = self.attention( + hidden_states, + attention_mask, + head_mask, + output_attentions=output_attentions, + past_key_value=self_attn_past_key_value, + output_key_value=output_key_value + ) + attention_output = self_attention_outputs[0] + + # if decoder, the last output is tuple of self-attn cache + if self.is_decoder or output_key_value: + outputs = self_attention_outputs[1:-1] + present_key_value = self_attention_outputs[-1] + else: + outputs = self_attention_outputs[1:] # add self attentions if we output attention weights + + cross_attn_present_key_value = None + if self.is_decoder and encoder_hidden_states is not None: + if not hasattr(self, "crossattention"): + raise ValueError( + f"If `encoder_hidden_states` are passed, {self} has to be instantiated with cross-attention layers" + " by setting `config.add_cross_attention=True`" + ) + + # cross_attn cached key/values tuple is at positions 3,4 of past_key_value tuple + cross_attn_past_key_value = past_key_value[-2:] if past_key_value is not None else None + cross_attention_outputs = self.crossattention( + attention_output, + attention_mask, + head_mask, + encoder_hidden_states, + encoder_attention_mask, + cross_attn_past_key_value, + output_attentions, + ) + attention_output = cross_attention_outputs[0] + outputs = outputs + cross_attention_outputs[1:-1] # add cross attentions if we output attention weights + + # add cross-attn cache to positions 3,4 of present_key_value tuple + cross_attn_present_key_value = cross_attention_outputs[-1] + present_key_value = present_key_value + cross_attn_present_key_value + + layer_output = apply_chunking_to_forward( + self.feed_forward_chunk, self.chunk_size_feed_forward, self.seq_len_dim, attention_output + ) + outputs = (layer_output,) + outputs + + # if decoder, return the attn key/values as the last output + if self.is_decoder or output_key_value: + outputs = outputs + (present_key_value,) + + return outputs + + def feed_forward_chunk(self, attention_output): + intermediate_output = self.intermediate(attention_output) + layer_output = self.output(intermediate_output, attention_output) + return layer_output + + +# Copied from transformers.models.bert.modeling_bert.BertEncoder with Bert->Roberta +class RobertaEncoder(nn.Module): + def __init__(self, config): + super().__init__() + self.config = config + self.layer = nn.ModuleList([RobertaLayer(config) for _ in range(config.num_hidden_layers)]) + self.gradient_checkpointing = False + + def forward( + self, + hidden_states: torch.Tensor, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = False, + output_hidden_states: Optional[bool] = False, + return_dict: Optional[bool] = True, + ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPastAndCrossAttentions]: + all_hidden_states = () if output_hidden_states else None + all_self_attentions = () if output_attentions else None + all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning_once( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + next_decoder_cache = () if use_cache else None + for i, layer_module in enumerate(self.layer): + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + layer_head_mask = head_mask[i] if head_mask is not None else None + past_key_value = past_key_values[i] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + + def create_custom_forward(module): + def custom_forward(*inputs): + return module(*inputs, past_key_value, output_attentions) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(layer_module), + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + ) + else: + layer_outputs = layer_module( + hidden_states, + attention_mask, + layer_head_mask, + encoder_hidden_states, + encoder_attention_mask, + past_key_value, + output_attentions, + output_key_value=use_cache + ) + + hidden_states = layer_outputs[0] + if use_cache: + next_decoder_cache += (layer_outputs[-1],) + if output_attentions: + all_self_attentions = all_self_attentions + (layer_outputs[1],) + if self.config.add_cross_attention: + all_cross_attentions = all_cross_attentions + (layer_outputs[2],) + + if output_hidden_states: + all_hidden_states = all_hidden_states + (hidden_states,) + + if not return_dict: + return tuple( + v + for v in [ + hidden_states, + next_decoder_cache, + all_hidden_states, + all_self_attentions, + all_cross_attentions, + ] + if v is not None + ) + return BaseModelOutputWithPastAndCrossAttentions( + last_hidden_state=hidden_states, + past_key_values=next_decoder_cache, + hidden_states=all_hidden_states, + attentions=all_self_attentions, + cross_attentions=all_cross_attentions, + ) + + +# Copied from transformers.models.bert.modeling_bert.BertPooler +class RobertaPooler(nn.Module): + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.activation = nn.Tanh() + + def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: + # We "pool" the model by simply taking the hidden state corresponding + # to the first token. + first_token_tensor = hidden_states[:, 0] + pooled_output = self.dense(first_token_tensor) + pooled_output = self.activation(pooled_output) + return pooled_output + + +class RobertaPreTrainedModel(PreTrainedModel): + """ + An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained + models. + """ + + config_class = RobertaConfig + base_model_prefix = "roberta" + supports_gradient_checkpointing = True + _no_split_modules = [] + + # Copied from transformers.models.bert.modeling_bert.BertPreTrainedModel._init_weights + def _init_weights(self, module): + """Initialize the weights""" + if isinstance(module, nn.Linear): + # Slightly different from the TF version which uses truncated_normal for initialization + # cf https://github.com/pytorch/pytorch/pull/5617 + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.bias is not None: + module.bias.data.zero_() + elif isinstance(module, nn.Embedding): + module.weight.data.normal_(mean=0.0, std=self.config.initializer_range) + if module.padding_idx is not None: + module.weight.data[module.padding_idx].zero_() + elif isinstance(module, nn.LayerNorm): + module.bias.data.zero_() + module.weight.data.fill_(1.0) + + def _set_gradient_checkpointing(self, module, value=False): + if isinstance(module, RobertaEncoder): + module.gradient_checkpointing = value + + def update_keys_to_ignore(self, config, del_keys_to_ignore): + """Remove some keys from ignore list""" + if not config.tie_word_embeddings: + # must make a new list, or the class variable gets modified! + self._keys_to_ignore_on_save = [k for k in self._keys_to_ignore_on_save if k not in del_keys_to_ignore] + self._keys_to_ignore_on_load_missing = [ + k for k in self._keys_to_ignore_on_load_missing if k not in del_keys_to_ignore + ] + + +ROBERTA_START_DOCSTRING = r""" + + This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the + library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads + etc.) + + This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. + Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage + and behavior. + + Parameters: + config ([`RobertaConfig`]): Model configuration class with all the parameters of the + model. Initializing with a config file does not load the weights associated with the model, only the + configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. +""" + +ROBERTA_INPUTS_DOCSTRING = r""" + Args: + input_ids (`torch.LongTensor` of shape `({0})`): + Indices of input sequence tokens in the vocabulary. + + Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and + [`PreTrainedTokenizer.__call__`] for details. + + [What are input IDs?](../glossary#input-ids) + attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*): + Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + [What are attention masks?](../glossary#attention-mask) + token_type_ids (`torch.LongTensor` of shape `({0})`, *optional*): + Segment token indices to indicate first and second portions of the inputs. Indices are selected in `[0,1]`: + + - 0 corresponds to a *sentence A* token, + - 1 corresponds to a *sentence B* token. + This parameter can only be used when the model is initialized with `type_vocab_size` parameter with value + >= 2. All the value in this tensor should be always < type_vocab_size. + + [What are token type IDs?](../glossary#token-type-ids) + position_ids (`torch.LongTensor` of shape `({0})`, *optional*): + Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, + config.max_position_embeddings - 1]`. + + [What are position IDs?](../glossary#position-ids) + head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*): + Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`: + + - 1 indicates the head is **not masked**, + - 0 indicates the head is **masked**. + + inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*): + Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This + is useful if you want more control over how to convert `input_ids` indices into associated vectors than the + model's internal embedding lookup matrix. + output_attentions (`bool`, *optional*): + Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned + tensors for more detail. + output_hidden_states (`bool`, *optional*): + Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for + more detail. + return_dict (`bool`, *optional*): + Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. +""" + + +@add_start_docstrings( + "The bare RoBERTa Model transformer outputting raw hidden-states without any specific head on top.", + ROBERTA_START_DOCSTRING, +) +class RobertaModel(RobertaPreTrainedModel): + """ + + The model can behave as an encoder (with only self-attention) as well as a decoder, in which case a layer of + cross-attention is added between the self-attention layers, following the architecture described in *Attention is + all you need*_ by Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz + Kaiser and Illia Polosukhin. + + To behave as an decoder the model needs to be initialized with the `is_decoder` argument of the configuration set + to `True`. To be used in a Seq2Seq model, the model needs to initialized with both `is_decoder` argument and + `add_cross_attention` set to `True`; an `encoder_hidden_states` is then expected as an input to the forward pass. + + .. _*Attention is all you need*: https://arxiv.org/abs/1706.03762 + + """ + + _keys_to_ignore_on_load_missing = [r"position_ids"] + + # Copied from transformers.models.bert.modeling_bert.BertModel.__init__ with Bert->Roberta + def __init__(self, config, add_pooling_layer=True): + super().__init__(config) + self.config = config + + self.embeddings = RobertaEmbeddings(config) + self.encoder = RobertaEncoder(config) + + self.pooler = RobertaPooler(config) if add_pooling_layer else None + + # Initialize weights and apply final processing + self.post_init() + + def get_input_embeddings(self): + return self.embeddings.word_embeddings + + def set_input_embeddings(self, value): + self.embeddings.word_embeddings = value + + def _prune_heads(self, heads_to_prune): + """ + Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base + class PreTrainedModel + """ + for layer, heads in heads_to_prune.items(): + self.encoder.layer[layer].attention.prune_heads(heads) + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=BaseModelOutputWithPoolingAndCrossAttentions, + config_class=_CONFIG_FOR_DOC, + ) + # Copied from transformers.models.bert.modeling_bert.BertModel.forward + def forward( + self, + input_ids: Optional[torch.Tensor] = None, + attention_mask: Optional[torch.Tensor] = None, + token_type_ids: Optional[torch.Tensor] = None, + position_ids: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + inputs_embeds: Optional[torch.Tensor] = None, + encoder_hidden_states: Optional[torch.Tensor] = None, + encoder_attention_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPoolingAndCrossAttentions]: + r""" + encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + """ + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # if self.config.is_decoder: + # use_cache = use_cache if use_cache is not None else self.config.use_cache + # else: + # use_cache = False + + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either input_ids or inputs_embeds") + + batch_size, seq_length = input_shape + device = input_ids.device if input_ids is not None else inputs_embeds.device + + # past_key_values_length + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + + if attention_mask is None: + attention_mask = torch.ones(((batch_size, seq_length + past_key_values_length)), device=device) + + if token_type_ids is None: + if hasattr(self.embeddings, "token_type_ids"): + buffered_token_type_ids = self.embeddings.token_type_ids[:, :seq_length] + buffered_token_type_ids_expanded = buffered_token_type_ids.expand(batch_size, seq_length) + token_type_ids = buffered_token_type_ids_expanded + else: + token_type_ids = torch.zeros(input_shape, dtype=torch.long, device=device) + + # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] + # ourselves in which case we just need to make it broadcastable to all heads. + extended_attention_mask: torch.Tensor = self.get_extended_attention_mask(attention_mask, input_shape) + + # If a 2D or 3D attention mask is provided for the cross-attention + # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] + if self.config.is_decoder and encoder_hidden_states is not None: + encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size() + encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length) + if encoder_attention_mask is None: + encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device) + encoder_extended_attention_mask = self.invert_attention_mask(encoder_attention_mask) + else: + encoder_extended_attention_mask = None + + # Prepare head mask if needed + # 1.0 in head_mask indicate we keep the head + # attention_probs has shape bsz x n_heads x N x N + # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] + # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] + head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers) + + embedding_output = self.embeddings( + input_ids=input_ids, + position_ids=position_ids, + token_type_ids=token_type_ids, + inputs_embeds=inputs_embeds, + past_key_values_length=past_key_values_length, + ) + encoder_outputs = self.encoder( + embedding_output, + attention_mask=extended_attention_mask, + head_mask=head_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_extended_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + sequence_output = encoder_outputs[0] + pooled_output = self.pooler(sequence_output) if self.pooler is not None else None + + if not return_dict: + return (sequence_output, pooled_output) + encoder_outputs[1:] + + return BaseModelOutputWithPoolingAndCrossAttentions( + last_hidden_state=sequence_output, + pooler_output=pooled_output, + past_key_values=encoder_outputs.past_key_values, + hidden_states=encoder_outputs.hidden_states, + attentions=encoder_outputs.attentions, + cross_attentions=encoder_outputs.cross_attentions, + ) + + +@add_start_docstrings( + """RoBERTa Model with a `language modeling` head on top for CLM fine-tuning.""", ROBERTA_START_DOCSTRING +) +class RobertaForCausalLM(RobertaPreTrainedModel): + _keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_unexpected = [r"pooler"] + + def __init__(self, config): + super().__init__(config) + + if not config.is_decoder: + logger.warning("If you want to use `RobertaLMHeadModel` as a standalone, add `is_decoder=True.`") + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.lm_head = RobertaLMHead(config) + + # The LM head weights require special treatment only when they are tied with the word embeddings + self.update_keys_to_ignore(config, ["lm_head.decoder.weight"]) + + # Initialize weights and apply final processing + self.post_init() + + def get_output_embeddings(self): + return self.lm_head.decoder + + def set_output_embeddings(self, new_embeddings): + self.lm_head.decoder = new_embeddings + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @replace_return_docstrings(output_type=CausalLMOutputWithCrossAttentions, config_class=_CONFIG_FOR_DOC) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + past_key_values: Tuple[Tuple[torch.FloatTensor]] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], CausalLMOutputWithCrossAttentions]: + r""" + encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): + Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention if + the model is configured as a decoder. + encoder_attention_mask (`torch.FloatTensor` of shape `(batch_size, sequence_length)`, *optional*): + Mask to avoid performing attention on the padding token indices of the encoder input. This mask is used in + the cross-attention if the model is configured as a decoder. Mask values selected in `[0, 1]`: + + - 1 for tokens that are **not masked**, + - 0 for tokens that are **masked**. + + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in + `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are + ignored (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` + past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`): + Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding. + + If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that + don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all + `decoder_input_ids` of shape `(batch_size, sequence_length)`. + use_cache (`bool`, *optional*): + If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see + `past_key_values`). + + Returns: + + Example: + + ```python + >>> from transformers import AutoTokenizer, RobertaForCausalLM, AutoConfig + >>> import torch + + >>> tokenizer = AutoTokenizer.from_pretrained("roberta-base") + >>> config = AutoConfig.from_pretrained("roberta-base") + >>> config.is_decoder = True + >>> model = RobertaForCausalLM.from_pretrained("roberta-base", config=config) + + >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + >>> outputs = model(**inputs) + + >>> prediction_logits = outputs.logits + ```""" + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + if labels is not None: + use_cache = False + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + past_key_values=past_key_values, + use_cache=use_cache, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + sequence_output = outputs[0] + prediction_scores = self.lm_head(sequence_output) + + lm_loss = None + if labels is not None: + # we are doing next-token prediction; shift prediction scores and input ids by one + shifted_prediction_scores = prediction_scores[:, :-1, :].contiguous() + labels = labels[:, 1:].contiguous() + loss_fct = CrossEntropyLoss() + lm_loss = loss_fct(shifted_prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) + + if not return_dict: + output = (prediction_scores,) + outputs[2:] + return ((lm_loss,) + output) if lm_loss is not None else output + + return CausalLMOutputWithCrossAttentions( + loss=lm_loss, + logits=prediction_scores, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + cross_attentions=outputs.cross_attentions, + ) + + def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs): + input_shape = input_ids.shape + # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly + if attention_mask is None: + attention_mask = input_ids.new_ones(input_shape) + + # cut decoder_input_ids if past is used + if past_key_values is not None: + input_ids = input_ids[:, -1:] + + return {"input_ids": input_ids, "attention_mask": attention_mask, "past_key_values": past_key_values} + + def _reorder_cache(self, past_key_values, beam_idx): + reordered_past = () + for layer_past in past_key_values: + reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),) + return reordered_past + + +@add_start_docstrings("""RoBERTa Model with a `language modeling` head on top.""", ROBERTA_START_DOCSTRING) +class RobertaForMaskedLM(RobertaPreTrainedModel): + _keys_to_ignore_on_save = [r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_missing = [r"position_ids", r"lm_head.decoder.weight", r"lm_head.decoder.bias"] + _keys_to_ignore_on_load_unexpected = [r"pooler"] + + def __init__(self, config): + super().__init__(config) + + if config.is_decoder: + logger.warning( + "If you want to use `RobertaForMaskedLM` make sure `config.is_decoder=False` for " + "bi-directional self-attention." + ) + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.lm_head = RobertaLMHead(config) + + # The LM head weights require special treatment only when they are tied with the word embeddings + self.update_keys_to_ignore(config, ["lm_head.decoder.weight"]) + + # Initialize weights and apply final processing + self.post_init() + + def get_output_embeddings(self): + return self.lm_head.decoder + + def set_output_embeddings(self, new_embeddings): + self.lm_head.decoder = new_embeddings + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=MaskedLMOutput, + config_class=_CONFIG_FOR_DOC, + mask="", + expected_output="' Paris'", + expected_loss=0.1, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.FloatTensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], MaskedLMOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ..., + config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the + loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]` + kwargs (`Dict[str, any]`, optional, defaults to *{}*): + Used to hide legacy arguments that have been deprecated. + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + sequence_output = outputs[0] + prediction_scores = self.lm_head(sequence_output) + + masked_lm_loss = None + if labels is not None: + loss_fct = CrossEntropyLoss() + masked_lm_loss = loss_fct(prediction_scores.view(-1, self.config.vocab_size), labels.view(-1)) + + if not return_dict: + output = (prediction_scores,) + outputs[2:] + return ((masked_lm_loss,) + output) if masked_lm_loss is not None else output + + return MaskedLMOutput( + loss=masked_lm_loss, + logits=prediction_scores, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class RobertaLMHead(nn.Module): + """Roberta Head for masked language modeling.""" + + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + self.layer_norm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) + + self.decoder = nn.Linear(config.hidden_size, config.vocab_size) + self.bias = nn.Parameter(torch.zeros(config.vocab_size)) + self.decoder.bias = self.bias + + def forward(self, features, **kwargs): + x = self.dense(features) + x = gelu(x) + x = self.layer_norm(x) + + # project back to size of vocabulary with bias + x = self.decoder(x) + + return x + + def _tie_weights(self): + # To tie those two weights if they get disconnected (on TPU or when the bias is resized) + # For accelerate compatibility and to not break backward compatibility + if self.decoder.bias.device.type == "meta": + self.decoder.bias = self.bias + else: + self.bias = self.decoder.bias + + +@add_start_docstrings( + """ + RoBERTa Model transformer with a sequence classification/regression head on top (a linear layer on top of the + pooled output) e.g. for GLUE tasks. + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForSequenceClassification(RobertaPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + self.config = config + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.classifier = RobertaClassificationHead(config) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint="cardiffnlp/twitter-roberta-base-emotion", + output_type=SequenceClassifierOutput, + config_class=_CONFIG_FOR_DOC, + expected_output="'optimism'", + expected_loss=0.08, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the sequence classification/regression loss. Indices should be in `[0, ..., + config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If + `config.num_labels > 1` a classification loss is computed (Cross-Entropy). + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + sequence_output = outputs[0] + logits = self.classifier(sequence_output) + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.num_labels == 1: + self.config.problem_type = "regression" + elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.num_labels == 1: + loss = loss_fct(logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(logits, labels) + + if not return_dict: + output = (logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +@add_start_docstrings( + """ + Roberta Model with a multiple choice classification head on top (a linear layer on top of the pooled output and a + softmax) e.g. for RocStories/SWAG tasks. + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForMultipleChoice(RobertaPreTrainedModel): + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + + self.roberta = RobertaModel(config) + self.dropout = nn.Dropout(config.hidden_dropout_prob) + self.classifier = nn.Linear(config.hidden_size, 1) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")) + @add_code_sample_docstrings( + checkpoint=_CHECKPOINT_FOR_DOC, + output_type=MultipleChoiceModelOutput, + config_class=_CONFIG_FOR_DOC, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], MultipleChoiceModelOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for computing the multiple choice classification loss. Indices should be in `[0, ..., + num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See + `input_ids` above) + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1] + + flat_input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None + flat_position_ids = position_ids.view(-1, position_ids.size(-1)) if position_ids is not None else None + flat_token_type_ids = token_type_ids.view(-1, token_type_ids.size(-1)) if token_type_ids is not None else None + flat_attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None + flat_inputs_embeds = ( + inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1)) + if inputs_embeds is not None + else None + ) + + outputs = self.roberta( + flat_input_ids, + position_ids=flat_position_ids, + token_type_ids=flat_token_type_ids, + attention_mask=flat_attention_mask, + head_mask=head_mask, + inputs_embeds=flat_inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + pooled_output = outputs[1] + + pooled_output = self.dropout(pooled_output) + logits = self.classifier(pooled_output) + reshaped_logits = logits.view(-1, num_choices) + + loss = None + if labels is not None: + loss_fct = CrossEntropyLoss() + loss = loss_fct(reshaped_logits, labels) + + if not return_dict: + output = (reshaped_logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return MultipleChoiceModelOutput( + loss=loss, + logits=reshaped_logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +@add_start_docstrings( + """ + Roberta Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for + Named-Entity-Recognition (NER) tasks. + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForTokenClassification(RobertaPreTrainedModel): + _keys_to_ignore_on_load_unexpected = [r"pooler"] + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + + self.roberta = RobertaModel(config, add_pooling_layer=False) + classifier_dropout = ( + config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob + ) + self.dropout = nn.Dropout(classifier_dropout) + self.classifier = nn.Linear(config.hidden_size, config.num_labels) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint="Jean-Baptiste/roberta-large-ner-english", + output_type=TokenClassifierOutput, + config_class=_CONFIG_FOR_DOC, + expected_output="['O', 'ORG', 'ORG', 'O', 'O', 'O', 'O', 'O', 'LOC', 'O', 'LOC', 'LOC']", + expected_loss=0.01, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + labels: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], TokenClassifierOutput]: + r""" + labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): + Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`. + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + sequence_output = outputs[0] + + sequence_output = self.dropout(sequence_output) + logits = self.classifier(sequence_output) + + loss = None + if labels is not None: + loss_fct = CrossEntropyLoss() + loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return TokenClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class RobertaClassificationHead(nn.Module): + """Head for sentence-level classification tasks.""" + + def __init__(self, config): + super().__init__() + self.dense = nn.Linear(config.hidden_size, config.hidden_size) + classifier_dropout = ( + config.classifier_dropout if config.classifier_dropout is not None else config.hidden_dropout_prob + ) + self.dropout = nn.Dropout(classifier_dropout) + self.out_proj = nn.Linear(config.hidden_size, config.num_labels) + + def forward(self, features, **kwargs): + x = features[:, 0, :] # take token (equiv. to [CLS]) + x = self.dropout(x) + x = self.dense(x) + x = torch.tanh(x) + x = self.dropout(x) + x = self.out_proj(x) + return x + + +@add_start_docstrings( + """ + Roberta Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear + layers on top of the hidden-states output to compute `span start logits` and `span end logits`). + """, + ROBERTA_START_DOCSTRING, +) +class RobertaForQuestionAnswering(RobertaPreTrainedModel): + _keys_to_ignore_on_load_unexpected = [r"pooler"] + _keys_to_ignore_on_load_missing = [r"position_ids"] + + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + + self.roberta = RobertaModel(config, add_pooling_layer=False) + self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels) + + # Initialize weights and apply final processing + self.post_init() + + @add_start_docstrings_to_model_forward(ROBERTA_INPUTS_DOCSTRING.format("batch_size, sequence_length")) + @add_code_sample_docstrings( + checkpoint="deepset/roberta-base-squad2", + output_type=QuestionAnsweringModelOutput, + config_class=_CONFIG_FOR_DOC, + expected_output="' puppet'", + expected_loss=0.86, + ) + def forward( + self, + input_ids: Optional[torch.LongTensor] = None, + attention_mask: Optional[torch.FloatTensor] = None, + token_type_ids: Optional[torch.LongTensor] = None, + position_ids: Optional[torch.LongTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + start_positions: Optional[torch.LongTensor] = None, + end_positions: Optional[torch.LongTensor] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]: + r""" + start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the start of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*): + Labels for position (index) of the end of the labelled span for computing the token classification loss. + Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence + are not taken into account for computing the loss. + """ + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + outputs = self.roberta( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids, + position_ids=position_ids, + head_mask=head_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + ) + + sequence_output = outputs[0] + + logits = self.qa_outputs(sequence_output) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +def create_position_ids_from_input_ids(input_ids, padding_idx, past_key_values_length=0): + """ + Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols + are ignored. This is modified from fairseq's `utils.make_positions`. + + Args: + x: torch.Tensor x: + + Returns: torch.Tensor + """ + # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA. + mask = input_ids.ne(padding_idx).int() + incremental_indices = (torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length) * mask + return incremental_indices.long() + padding_idx diff --git a/baselines/mezo/medium_models/src/models.py b/baselines/mezo/medium_models/src/models.py new file mode 100644 index 0000000..af9a3c6 --- /dev/null +++ b/baselines/mezo/medium_models/src/models.py @@ -0,0 +1,482 @@ +"""Custom models for few-shot learning specific operations.""" + +from socket import ntohl +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers.models.bert.modeling_bert import BertPreTrainedModel, BertModel, BertOnlyMLMHead +# from transformers.models.roberta.modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead +from .modeling_roberta import RobertaPreTrainedModel, RobertaModel, RobertaLMHead +# from transformers.models.opt.modeling_opt import OPTPreTrainedModel, OPTModel, OPTDecoder +from .modeling_opt import OPTPreTrainedModel, OPTModel, OPTDecoder, OPTForCausalLM +from transformers.models.gpt2.modeling_gpt2 import GPT2PreTrainedModel, GPT2Model, GPT2LMHeadModel +from transformers.modeling_outputs import BaseModelOutputWithPast +from typing import Callable, Dict, Optional, Union, List, Tuple +import random + + +import logging +logger = logging.getLogger(__name__) + + +def resize_token_type_embeddings(model, new_num_types: int, random_segment: bool): + """ + Resize the segment (token type) embeddings for BERT + """ + if hasattr(model, 'bert'): + old_token_type_embeddings = model.bert.embeddings.token_type_embeddings + else: + raise NotImplementedError + new_token_type_embeddings = nn.Embedding(new_num_types, old_token_type_embeddings.weight.size(1)) + if not random_segment: + new_token_type_embeddings.weight.data[:old_token_type_embeddings.weight.size(0)] = old_token_type_embeddings.weight.data + + model.config.type_vocab_size = new_num_types + if hasattr(model, 'bert'): + model.bert.embeddings.token_type_embeddings = new_token_type_embeddings + else: + raise NotImplementedError + +def model_for_prompting_forward( + model, + input_ids=None, + attention_mask=None, + token_type_ids=None, + mask_pos=None, + labels=None, + sfc_input_ids=None, + sfc_attention_mask=None, + sfc_mask_pos=None +): + if sfc_input_ids is not None: + with torch.no_grad(): + logits = model_for_prompting_forward(model, input_ids=sfc_input_ids, attention_mask=sfc_attention_mask, mask_pos=sfc_mask_pos)[0] + icl_sfc_bias = F.log_softmax(logits.detach().squeeze(0)) + + if mask_pos is not None: + mask_pos = mask_pos.squeeze() + + model_fn = model.get_model_fn() + # Encode everything + if token_type_ids is not None: + outputs = model_fn( + input_ids, + attention_mask=attention_mask, + token_type_ids=token_type_ids + ) + else: + outputs = model_fn( + input_ids, + attention_mask=attention_mask, + ) + + + # Get token representation + sequence_output = outputs[0] + if mask_pos is not None: + sequence_mask_output = sequence_output[torch.arange(sequence_output.size(0)), mask_pos] + else: + sequence_mask_output = sequence_output[:,0] # representation + # sequence_mask_output = sequence_output.mean(dim=1) # average representation + + if model.label_word_list is not None: + # Logits over vocabulary tokens + head_fn = model.get_lm_head_fn() + prediction_mask_scores = head_fn(sequence_mask_output) + + # Exit early and only return mask logits. + if model.return_full_softmax: + if labels is not None: + return torch.zeros(1, out=prediction_mask_scores.new()), prediction_mask_scores + return prediction_mask_scores + + # Return logits for each label + logits = [] + # use MLM logit + if model.model_args.use_task_word: + vocab_logits = model.lm_head(sequence_mask_output) + for _id in model.label_word_list: + logits.append(vocab_logits[:, _id].unsqueeze(-1)) + # use learned linear head logit on top of task word representation (standard LM-BFF) + else: + for label_id in range(len(model.label_word_list)): + logits.append(prediction_mask_scores[:, model.label_word_list[label_id]].unsqueeze(-1)) + logits = torch.cat(logits, -1) + + # Regression task + if model.config.num_labels == 1: + logsoftmax = nn.LogSoftmax(-1) + logits = logsoftmax(logits) # Log prob of right polarity + else: + logits = model.classifier(sequence_mask_output) + + + loss = None + if labels is not None: + if model.config.num_labels == 1: + # Regression task + if model.label_word_list is not None: + labels = torch.stack([1 - (labels.view(-1) - model.lb) / (model.ub - model.lb), (labels.view(-1) - model.lb) / (model.ub - model.lb)], -1) + loss = nn.KLDivLoss(log_target=True)(logits.view(-1, 2), labels) + else: + labels = (labels.float().view(-1) - model.lb) / (model.ub - model.lb) + loss = nn.MSELoss()(logits.view(-1), labels) + else: + if model.model_args.l2_loss: + coords = torch.nn.functional.one_hot(labels.squeeze(), model.config.num_labels).float() + loss = nn.MSELoss()(logits.view(-1, logits.size(-1)), coords) + else: + loss = nn.CrossEntropyLoss()(logits.view(-1, logits.size(-1)), labels.view(-1)) + + + if hasattr(model, "lr_weight"): + # Linear head + logits = torch.matmul(F.softmax(logits, -1), model.lr_weight) + if hasattr(model, "lr_bias"): + logits += model.lr_bias.unsqueeze(0) + + if model.model_args.sfc and hasattr(model, "sfc_bias"): + logits = F.log_softmax(logits, -1) - model.sfc_bias + if sfc_input_ids is not None: + logits = F.log_softmax(logits, -1) - icl_sfc_bias + + output = (logits,) + + + if model.model_args.use_task_word and model.num_labels == 1: + # Regression output + output = (torch.exp(logits[..., 1].unsqueeze(-1)) * (model.ub - model.lb) + model.lb,) + return ((loss,) + output) if loss is not None else output + +def convert_opt_model(model: OPTModel, config, num_exclude_layers): + model.model.decoder = EfficientOPTDecoder(config, num_exclude_layers) + return model + +class BertModelForPromptFinetuning(BertPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + self.bert = BertModel(config) + self.cls = BertOnlyMLMHead(config) + self.classifier = nn.Linear(config.hidden_size, self.num_labels) + + self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def get_model_fn(self): + return self.bert + + def get_lm_head_fn(self): + return self.cls + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels) + +class RobertaModelForPromptFinetuning(RobertaPreTrainedModel): + def __init__(self, config): + super().__init__(config) + logger.warn("By default for RoBERTa models the input embeddings and the output embeddings are NOT tied!!!!") + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + self.roberta = RobertaModel(config) + self.lm_head = RobertaLMHead(config) + self.classifier = nn.Linear(config.hidden_size, self.num_labels) + + self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def tie_emb(self): + output_embeddings = self.lm_head.decoder + self._tie_or_clone_weights(output_embeddings, self.roberta.get_input_embeddings()) + + def get_model_fn(self): + return self.roberta + + def get_lm_head_fn(self): + return self.lm_head + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels) + +class OPTModelForPromptFinetuning(OPTForCausalLM): + def __init__(self, config): + super().__init__(config) + logger.warn("By default for OPT models the input embeddings and the output embeddings are tied!!!!") + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + # self.model = OPTModel(config) + # self.lm_head = nn.Linear(config.word_embed_proj_dim, config.vocab_size, bias=False) + # self.classifier = nn.Linear(config.hidden_size, self.num_labels) + # self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def get_model_fn(self): + return self.model + + def get_lm_head_fn(self): + return self.lm_head + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None, sfc_input_ids=None, sfc_attention_mask=None, sfc_mask_pos=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels, sfc_input_ids=sfc_input_ids, sfc_attention_mask=sfc_attention_mask, sfc_mask_pos=sfc_mask_pos) + +class GPT2ModelForPromptFinetuning(GPT2LMHeadModel): + + def __init__(self, config): + super().__init__(config) + raise NotImplementedError("Need to check if the lm head is properly loaded and whether it is tied.") + self.num_labels = config.num_labels + print(config) + self.model_type = config.model_type + # self.transformer = GPT2Model(config) + # self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False) + self.classifier = nn.Linear(config.hidden_size, self.num_labels) + + self.init_weights() + + # These attributes should be assigned once the model is initialized + self.model_args, self.data_args, self.label_word_list = None, None, None + + # For regression + self.lb, self.ub = 0.0, 1.0 + + # For auto label search. + self.return_full_softmax = None + + def get_model_fn(self): + return self.transformer + + def get_lm_head_fn(self): + return self.lm_head + + def forward(self, input_ids=None, attention_mask=None, token_type_ids=None, mask_pos=None, labels=None): + return model_for_prompting_forward(self, input_ids, attention_mask, token_type_ids, mask_pos, labels) + +class EfficientOPTDecoder(OPTDecoder): + def __init__(self, config, num_exclude): + super().__init__(config) + self.num_exclude = num_exclude # number of initial layers to operate with torch.no_grad + + def forward( + self, + input_ids: torch.LongTensor = None, + attention_mask: Optional[torch.Tensor] = None, + head_mask: Optional[torch.Tensor] = None, + past_key_values: Optional[List[torch.FloatTensor]] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = None, + output_attentions: Optional[bool] = None, + output_hidden_states: Optional[bool] = None, + return_dict: Optional[bool] = None, + ) -> Union[Tuple, BaseModelOutputWithPast]: + output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions + output_hidden_states = ( + output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states + ) + use_cache = use_cache if use_cache is not None else self.config.use_cache + + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + # retrieve input_ids and inputs_embeds + if input_ids is not None and inputs_embeds is not None: + raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time") + elif input_ids is not None: + input_shape = input_ids.size() + input_ids = input_ids.view(-1, input_shape[-1]) + elif inputs_embeds is not None: + input_shape = inputs_embeds.size()[:-1] + else: + raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds") + + past_key_values_length = past_key_values[0][0].shape[2] if past_key_values is not None else 0 + + if inputs_embeds is None: + inputs_embeds = self.embed_tokens(input_ids) + + # embed positions + if attention_mask is None: + attention_mask = torch.ones(inputs_embeds.shape[:2], dtype=torch.bool, device=inputs_embeds.device) + pos_embeds = self.embed_positions(attention_mask, past_key_values_length) + + attention_mask = self._prepare_decoder_attention_mask( + attention_mask, input_shape, inputs_embeds, past_key_values_length + ) + + if self.project_in is not None: + inputs_embeds = self.project_in(inputs_embeds) + + hidden_states = inputs_embeds + pos_embeds + + # decoder layers + all_hidden_states = () if output_hidden_states else None + all_self_attns = () if output_attentions else None + next_decoder_cache = () if use_cache else None + + # check if head_mask has a correct number of layers specified if desired + for attn_mask, mask_name in zip([head_mask], ["head_mask"]): + if attn_mask is not None: + if attn_mask.size()[0] != (len(self.layers)): + raise ValueError( + f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for" + f" {head_mask.size()[0]}." + ) + + #### run first few layers without grad + with torch.no_grad(): + for idx, decoder_layer in enumerate(self.layers[:self.num_exclude]): + + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + #### rest of the layers with grad + for idx, decoder_layer in enumerate(self.layers[self.num_exclude:]): + # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description) + if output_hidden_states: + all_hidden_states += (hidden_states,) + + dropout_probability = random.uniform(0, 1) + if self.training and (dropout_probability < self.layerdrop): + continue + + past_key_value = past_key_values[idx] if past_key_values is not None else None + + if self.gradient_checkpointing and self.training: + if use_cache: + logger.warning( + "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..." + ) + use_cache = False + + def create_custom_forward(module): + def custom_forward(*inputs): + # None for past_key_value + return module(*inputs, output_attentions, None) + + return custom_forward + + layer_outputs = torch.utils.checkpoint.checkpoint( + create_custom_forward(decoder_layer), + hidden_states, + attention_mask, + head_mask[idx] if head_mask is not None else None, + None, + ) + else: + layer_outputs = decoder_layer( + hidden_states, + attention_mask=attention_mask, + layer_head_mask=(head_mask[idx] if head_mask is not None else None), + past_key_value=past_key_value, + output_attentions=output_attentions, + use_cache=use_cache, + ) + + hidden_states = layer_outputs[0] + + if use_cache: + next_decoder_cache += (layer_outputs[2 if output_attentions else 1],) + + if output_attentions: + all_self_attns += (layer_outputs[1],) + + if self.final_layer_norm is not None: + hidden_states = self.final_layer_norm(hidden_states) + + if self.project_out is not None: + hidden_states = self.project_out(hidden_states) + + # add hidden states from the last decoder layer + if output_hidden_states: + all_hidden_states += (hidden_states,) + + next_cache = next_decoder_cache if use_cache else None + if not return_dict: + return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None) + + return BaseModelOutputWithPast( + last_hidden_state=hidden_states, + past_key_values=next_cache, + hidden_states=all_hidden_states, + attentions=all_self_attns, + ) + + +MODEL_TYPES = { + "bert": BertModelForPromptFinetuning, + "roberta": RobertaModelForPromptFinetuning, + "opt": OPTModelForPromptFinetuning, + "gpt2": GPT2ModelForPromptFinetuning, +} diff --git a/baselines/mezo/medium_models/src/prefix.py b/baselines/mezo/medium_models/src/prefix.py new file mode 100644 index 0000000..91d06a2 --- /dev/null +++ b/baselines/mezo/medium_models/src/prefix.py @@ -0,0 +1,162 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import torch +from torch import nn + +def find_module(root_module: nn.Module, key: str): + """From OpenDelta""" + sub_keys = key.split(".") + parent_module = root_module + for sub_key in sub_keys[:-1]: + parent_module = getattr(parent_module, sub_key) + module = getattr(parent_module, sub_keys[-1]) + return parent_module, sub_keys[-1], module + + +def attn_forward_hook(self, *args, **kwargs): + + def _expand_bsz(x, bsz): + x = x.reshape(x.size(0), self.num_heads, -1).transpose(0,1) # (num_prefix, hidden) -> (num_head, num_prefix, hidden/num_head) + x = x.unsqueeze(0).expand(bsz, *x.shape) # -> (bsz, num_head, num_prefix, hidden/num_head) + return x + + if "hidden_states" in kwargs: + hidden_states = kwargs["hidden_states"] + else: + hidden_states = args[0] + bsz = hidden_states.size(0) + if 'past_key_value' not in kwargs or kwargs['past_key_value'] is None: + if self.reparam: + prefix_keys = self.prefix_mlp_keys(self.prefix_input_embeds) + prefix_values = self.prefix_mlp_values(self.prefix_input_embeds) + else: + prefix_keys, prefix_values = self.prefix_keys, self.prefix_values + kwargs['past_key_value'] = (_expand_bsz(prefix_keys, bsz), _expand_bsz(prefix_values, bsz)) + + if 'attention_mask' in kwargs and kwargs['attention_mask'] is not None: + am = kwargs['attention_mask'] + kwargs['attention_mask'] = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1) + elif len(args) > 1: # attention mask is passed via positional argument + am = args[1] + am = torch.cat([-torch.zeros((*am.shape[:-1], self.num_prefix), dtype=am.dtype, device=am.device), am], dim=-1) + args = (args[0], am) + args[2:] + + return self.original_forward(*args, **kwargs) + + +class PrefixTuning: + + def __init__(self, model, num_prefix, reparam=True, embed_dim=512, mid_dim=512, float16=False, init_by_real_act=False): + + self.model = model + self.num_prefix = num_prefix + self.hidden_dim = model.config.hidden_size + self.float16 = float16 + + # Reparameterization + self.reparam = reparam + self.embed_dim = embed_dim + self.mid_dim = mid_dim + + input_embeds = None # For reparameterization + if model.config.model_type == "opt": + attention_name = "attn" + first_layer_name = "layers.0" + layer_name = "layers." + elif model.config.model_type == "roberta": + attention_name = "attention" + first_layer_name = "layer.0" + layer_name = "layer." + else: + raise NotImplementedError + + if init_by_real_act: + # Initialize prefix with real words' activations + assert not reparam + + # Move the model to GPU first? + model = model.cuda() + input_tokens = torch.randint(low=0, high=model.config.vocab_size, size=(1, num_prefix), dtype=torch.long).cuda() + if model.config.model_type == "roberta": + with torch.no_grad(): + # real_key_values = model(input_ids=input_tokens, use_cache=True).past_key_values + real_key_values = model.roberta(input_ids=input_tokens, use_cache=True).past_key_values + elif model.config.model_type == "opt": + with torch.no_grad(): + real_key_values = model.model(input_ids=input_tokens, use_cache=True).past_key_values + else: + raise NotImplementedError + + for key, _ in model.named_modules(): + if key[-len(attention_name):] == attention_name: + layer_id = int(key.split(layer_name)[1].split(".")[0]) + logger.info(f"Inject prefix to: {key}") + _, _, attn = find_module(model, key) + attn.original_forward = attn.forward + attn.forward = attn_forward_hook.__get__(attn, type(attn)) + if not hasattr(attn, "num_heads"): + attn.num_heads = model.config.num_attention_heads + first = first_layer_name in key + self.add_prefix(attn, first=first, input_embeds=input_embeds) + if first and self.reparam: + input_embeds = attn.prefix_input_embeds + if init_by_real_act: + logger.info(f"Reinitialize with actual activation: {key} (layer {layer_id})") + keys = real_key_values[layer_id][0].squeeze(0).transpose(0, 1).reshape(num_prefix, -1) + values = real_key_values[layer_id][1].squeeze(0).transpose(0, 1).reshape(num_prefix, -1) + attn.prefix_keys.data = keys + attn.prefix_values.data = values + + for n, p in model.named_parameters(): + if "prefix" not in n: + # logger.info(f"Freeze {n}") + p.requires_grad = False + + def add_prefix(self, module, first, input_embeds=None): + module.num_prefix = self.num_prefix + module.reparam = self.reparam + if self.reparam: + if first: + logger.info("For prefix+reparameterization, inject the embeddings in the first layer.") + module.prefix_input_embeds = nn.Parameter(torch.randn(self.num_prefix, self.embed_dim, device=self.model.device, dtype=self.model.dtype), requires_grad=True) + else: + assert input_embeds is not None + module.prefix_input_embeds = input_embeds + module.prefix_mlp_keys = nn.Sequential( + nn.Linear(self.embed_dim, self.mid_dim), + nn.Tanh(), + nn.Linear(self.mid_dim, self.hidden_dim) + ).to(self.model.device) + module.prefix_mlp_values = nn.Sequential( + nn.Linear(self.embed_dim, self.mid_dim), + nn.Tanh(), + nn.Linear(self.mid_dim, self.hidden_dim) + ).to(self.model.device) + if self.float16: + module.prefix_mlp_keys = module.prefix_mlp_keys.half() + module.prefix_mlp_values = module.prefix_mlp_values.half() + else: + module.prefix_keys = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=self.model.device, dtype=self.model.dtype), requires_grad=True) + module.prefix_values = nn.Parameter(torch.randn(self.num_prefix, self.hidden_dim, device=self.model.device, dtype=self.model.dtype), requires_grad=True) + + +def test(): + from transformers import AutoTokenizer + from modeling_roberta import RobertaModel + model = RobertaModel.from_pretrained("roberta-base") + tokenizer = AutoTokenizer.from_pretrained("roberta-base") + model.cuda() + + PrefixTuning(model, num_prefix=5, reparam=False, init_by_real_act=True) + + inputs = tokenizer("Hello, my dog is", return_tensors="pt").to(model.device) + o = model(**inputs) + # print(o) + + +if __name__ == "__main__": + test() \ No newline at end of file diff --git a/baselines/mezo/medium_models/src/processors.py b/baselines/mezo/medium_models/src/processors.py new file mode 100644 index 0000000..41ffa8b --- /dev/null +++ b/baselines/mezo/medium_models/src/processors.py @@ -0,0 +1,611 @@ +"""Dataset utils for different data settings for GLUE.""" + +import os +import logging +from transformers import DataProcessor, InputExample +from transformers.data.processors.glue import * +from transformers.data.metrics import glue_compute_metrics +import pandas as pd +import logging + +logger = logging.getLogger(__name__) + +class MrpcProcessor(DataProcessor): + """Processor for the MRPC data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence1"].numpy().decode("utf-8"), + tensor_dict["sentence2"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + logger.info("LOOKING AT {}".format(os.path.join(data_dir, "train.tsv"))) + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["0", "1"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, i) + text_a = line[3] + text_b = line[4] + label = line[0] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class MnliProcessor(DataProcessor): + """Processor for the MultiNLI data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["premise"].numpy().decode("utf-8"), + tensor_dict["hypothesis"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev_matched.tsv")), "dev_matched") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test_matched.tsv")), "test_matched") + + def get_labels(self): + """See base class.""" + return ["contradiction", "entailment", "neutral"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[8] + text_b = line[9] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class MnliMismatchedProcessor(MnliProcessor): + """Processor for the MultiNLI Mismatched data set (GLUE version).""" + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev_mismatched.tsv")), "dev_mismatched") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test_mismatched.tsv")), "test_mismatched") + + +class SnliProcessor(DataProcessor): + """Processor for the MultiNLI data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["premise"].numpy().decode("utf-8"), + tensor_dict["hypothesis"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["contradiction", "entailment", "neutral"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[7] + text_b = line[8] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class ColaProcessor(DataProcessor): + """Processor for the CoLA data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence"].numpy().decode("utf-8"), + None, + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["0", "1"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + test_mode = set_type == "test" + text_index = 3 + examples = [] + for (i, line) in enumerate(lines): + guid = "%s-%s" % (set_type, i) + text_a = line[text_index] + label = line[1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label)) + return examples + + +class Sst2Processor(DataProcessor): + """Processor for the SST-2 data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence"].numpy().decode("utf-8"), + None, + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["0", "1"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + text_index = 0 + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, i) + text_a = line[text_index] + label = line[1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=None, label=label)) + return examples + + +class StsbProcessor(DataProcessor): + """Processor for the STS-B data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence1"].numpy().decode("utf-8"), + tensor_dict["sentence2"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return [None] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[7] + text_b = line[8] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class QqpProcessor(DataProcessor): + """Processor for the QQP data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["question1"].numpy().decode("utf-8"), + tensor_dict["question2"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["0", "1"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + test_mode = set_type == "test" + q1_index = 3 + q2_index = 4 + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + try: + text_a = line[q1_index] + text_b = line[q2_index] + label = line[5] + except IndexError: + continue + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class QnliProcessor(DataProcessor): + """Processor for the QNLI data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["question"].numpy().decode("utf-8"), + tensor_dict["sentence"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["entailment", "not_entailment"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[1] + text_b = line[2] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class RteProcessor(DataProcessor): + """Processor for the RTE data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence1"].numpy().decode("utf-8"), + tensor_dict["sentence2"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["entailment", "not_entailment"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[1] + text_b = line[2] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + + +class WnliProcessor(DataProcessor): + """Processor for the WNLI data set (GLUE version).""" + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence1"].numpy().decode("utf-8"), + tensor_dict["sentence2"].numpy().decode("utf-8"), + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "train.tsv")), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "dev.tsv")), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(self._read_tsv(os.path.join(data_dir, "test.tsv")), "test") + + def get_labels(self): + """See base class.""" + return ["0", "1"] + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + if i == 0: + continue + guid = "%s-%s" % (set_type, line[0]) + text_a = line[1] + text_b = line[2] + label = line[-1] + examples.append(InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label)) + return examples + +class TextClassificationProcessor(DataProcessor): + """ + Data processor for text classification datasets (mr, sst-5, subj, trec, cr, mpqa). + """ + + def __init__(self, task_name): + self.task_name = task_name + + def get_example_from_tensor_dict(self, tensor_dict): + """See base class.""" + return InputExample( + tensor_dict["idx"].numpy(), + tensor_dict["sentence"].numpy().decode("utf-8"), + None, + str(tensor_dict["label"].numpy()), + ) + + def get_train_examples(self, data_dir): + """See base class.""" + return self._create_examples(pd.read_csv(os.path.join(data_dir, "train.csv"), header=None).values.tolist(), "train") + + def get_dev_examples(self, data_dir): + """See base class.""" + return self._create_examples(pd.read_csv(os.path.join(data_dir, "dev.csv"), header=None).values.tolist(), "dev") + + def get_test_examples(self, data_dir): + """See base class.""" + return self._create_examples(pd.read_csv(os.path.join(data_dir, "test.csv"), header=None).values.tolist(), "test") + + def get_labels(self): + """See base class.""" + if self.task_name == "mr": + return list(range(2)) + elif self.task_name == "sst-5": + return list(range(5)) + elif self.task_name == "subj": + return list(range(2)) + elif self.task_name == "trec": + return list(range(6)) + elif self.task_name == "cr": + return list(range(2)) + elif self.task_name == "mpqa": + return list(range(2)) + else: + raise Exception("task_name not supported.") + + def _create_examples(self, lines, set_type): + """Creates examples for the training, dev and test sets.""" + examples = [] + for (i, line) in enumerate(lines): + guid = "%s-%s" % (set_type, i) + if self.task_name == "ag_news": + examples.append(InputExample(guid=guid, text_a=line[1] + '. ' + line[2], short_text=line[1] + ".", label=line[0])) + elif self.task_name == "yelp_review_full": + examples.append(InputExample(guid=guid, text_a=line[1], short_text=line[1], label=line[0])) + elif self.task_name == "yahoo_answers": + text = line[1] + if not pd.isna(line[2]): + text += ' ' + line[2] + if not pd.isna(line[3]): + text += ' ' + line[3] + examples.append(InputExample(guid=guid, text_a=text, short_text=line[1], label=line[0])) + elif self.task_name in ['mr', 'sst-5', 'subj', 'trec', 'cr', 'mpqa']: + examples.append(InputExample(guid=guid, text_a=line[1], label=line[0])) + else: + raise Exception("Task_name not supported.") + + return examples + +def text_classification_metrics(task_name, preds, labels): + return {"acc": (preds == labels).mean()} + +# Add your task to the following mappings + +processors_mapping = { + "cola": ColaProcessor(), + "mnli": MnliProcessor(), + "mnli-mm": MnliMismatchedProcessor(), + "mrpc": MrpcProcessor(), + "sst-2": Sst2Processor(), + "sts-b": StsbProcessor(), + "qqp": QqpProcessor(), + "qnli": QnliProcessor(), + "rte": RteProcessor(), + "wnli": WnliProcessor(), + "snli": SnliProcessor(), + "mr": TextClassificationProcessor("mr"), + "sst-5": TextClassificationProcessor("sst-5"), + "subj": TextClassificationProcessor("subj"), + "trec": TextClassificationProcessor("trec"), + "cr": TextClassificationProcessor("cr"), + "mpqa": TextClassificationProcessor("mpqa") +} + +num_labels_mapping = { + "cola": 2, + "mnli": 3, + "mrpc": 2, + "sst-2": 2, + "sts-b": 1, + "qqp": 2, + "qnli": 2, + "rte": 2, + "wnli": 2, + "snli": 3, + "mr": 2, + "sst-5": 5, + "subj": 2, + "trec": 6, + "cr": 2, + "mpqa": 2 +} + +output_modes_mapping = { + "cola": "classification", + "mnli": "classification", + "mnli-mm": "classification", + "mrpc": "classification", + "sst-2": "classification", + "sts-b": "regression", + "qqp": "classification", + "qnli": "classification", + "rte": "classification", + "wnli": "classification", + "snli": "classification", + "mr": "classification", + "sst-5": "classification", + "subj": "classification", + "trec": "classification", + "cr": "classification", + "mpqa": "classification" +} + +# Return a function that takes (task_name, preds, labels) as inputs +compute_metrics_mapping = { + "cola": glue_compute_metrics, + "mnli": glue_compute_metrics, + "mnli-mm": glue_compute_metrics, + "mrpc": glue_compute_metrics, + "sst-2": glue_compute_metrics, + "sts-b": glue_compute_metrics, + "qqp": glue_compute_metrics, + "qnli": glue_compute_metrics, + "rte": glue_compute_metrics, + "wnli": glue_compute_metrics, + "snli": text_classification_metrics, + "mr": text_classification_metrics, + "sst-5": text_classification_metrics, + "subj": text_classification_metrics, + "trec": text_classification_metrics, + "cr": text_classification_metrics, + "mpqa": text_classification_metrics, +} + +# For regression task only: median +median_mapping = { + "sts-b": 2.5 +} + +bound_mapping = { + "sts-b": (0, 5) +} diff --git a/baselines/mezo/medium_models/src/trainer.py b/baselines/mezo/medium_models/src/trainer.py new file mode 100644 index 0000000..f54016f --- /dev/null +++ b/baselines/mezo/medium_models/src/trainer.py @@ -0,0 +1,867 @@ +########## The following part is copied from Transformers' trainer (3.4.0) and later ported to be compatible with v4.4.2 and to support initialization from linear head probing. ########## + +# coding=utf-8 +# Copyright 2020-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +The Trainer class, to easily train a 🤗 Transformers from scratch or finetune it on a new task. +""" + +import collections +import inspect +import math +import os +import re +import shutil +import warnings +from pathlib import Path +from typing import Any, Callable, Dict, List, Optional, Tuple, Union + +import numpy as np +import torch +from packaging import version +from torch import nn +from torch.utils.data.dataloader import DataLoader +from torch.utils.data.dataset import Dataset +from torch.utils.data.distributed import DistributedSampler +from torch.utils.data.sampler import RandomSampler, SequentialSampler +from torch.optim.lr_scheduler import LambdaLR +import math +import time + +import transformers +from transformers.file_utils import is_datasets_available, is_in_notebook, is_torch_tpu_available +from transformers.integrations import ( + is_comet_available, + is_optuna_available, + is_ray_available, + is_tensorboard_available, + is_wandb_available, +) +from transformers.optimization import AdamW, get_linear_schedule_with_warmup, get_scheduler + +from transformers.trainer_callback import ( + DefaultFlowCallback, + ProgressCallback, +) +from transformers.trainer_utils import ( + default_compute_objective, +) +from transformers.training_args import TrainingArguments +from transformers.utils import logging +from transformers.trainer_utils import TrainOutput + +from tqdm import tqdm, trange +from torch.optim import SGD +import torch.nn.functional as F + +from src.linearhead_trainer import LinearHeadTrainer +from transformers.trainer_callback import TrainerState + +import copy + +_use_native_amp = False +_use_apex = False + +DEFAULT_CALLBACKS = [DefaultFlowCallback] +DEFAULT_PROGRESS_CALLBACK = ProgressCallback + +if is_in_notebook(): + from transformers.utils.notebook import NotebookProgressCallback + + DEFAULT_PROGRESS_CALLBACK = NotebookProgressCallback + +# Check if Pytorch version >= 1.6 to switch between Native AMP and Apex +if version.parse(torch.__version__) < version.parse("1.6"): + from transformers.file_utils import is_apex_available + + if is_apex_available(): + from apex import amp + _use_apex = True +else: + _use_native_amp = True + from torch.cuda.amp import autocast + +if version.parse(torch.__version__) < version.parse("1.2"): + _use_ddp_no_sync = False +else: + _use_ddp_no_sync = True + +if is_datasets_available(): + import datasets + +if is_torch_tpu_available(): + import torch_xla.core.xla_model as xm + import torch_xla.debug.metrics as met + import torch_xla.distributed.parallel_loader as pl + +if is_tensorboard_available(): + from transformers.integrations import TensorBoardCallback + + DEFAULT_CALLBACKS.append(TensorBoardCallback) + + +if is_wandb_available(): + from transformers.integrations import WandbCallback + + DEFAULT_CALLBACKS.append(WandbCallback) + +if is_comet_available(): + from transformers.integrations import CometCallback + + DEFAULT_CALLBACKS.append(CometCallback) + +if is_optuna_available(): + import optuna + +if is_ray_available(): + from ray import tune + +logger = logging.get_logger(__name__) +logger.setLevel(logging.INFO) + +########## The above part is copied from Transformers' trainer (3.4.0) ########## + +def default_dev_objective(metrics): + """ + Objective used for picking the best model on development sets + """ + if "eval_mnli/acc" in metrics: + return metrics["eval_mnli/acc"] + elif "eval_mnli-mm/acc" in metrics: + return metrics["eval_mnli-mm/acc"] + elif "eval_f1" in metrics: + return metrics["eval_f1"] + elif "eval_mcc" in metrics: + return metrics["eval_mcc"] + elif "eval_pearson" in metrics: + return metrics["eval_pearson"] + elif "eval_acc" in metrics: + return metrics["eval_acc"] + + raise Exception("No metric founded for {}".format(metrics)) + +class Trainer(LinearHeadTrainer): + """ + Adding some functions based on Transformers' Trainer class. + """ + + def create_optimizer_and_scheduler(self, num_training_steps: int): + """ + Based on Transformers' default one, we add fixing layer option where the bottom n layers' parameters + are fixed and only the top layers are further fine-tuned. + """ + if self.args.hf_inference_model: + return + + if self.optimizer is None: + params = {} + for n, p in self.model.named_parameters(): + if self.args.fix_layers > 0: + if 'encoder.layer' in n: + try: + layer_num = int(n[n.find('encoder.layer') + 14:].split('.')[0]) + except: + print(n) + raise Exception("") + if layer_num >= self.args.fix_layers: + print('yes', n) + params[n] = p + else: + print('no ', n) + elif 'embeddings' in n: + print('no ', n) + else: + print('yes', n) + params[n] = p + else: + params[n] = p + no_decay = ["bias", "LayerNorm.weight"] + optimizer_grouped_parameters = [ + { + "params": [p for n, p in params.items() if not any(nd in n for nd in no_decay)], + "weight_decay": self.args.weight_decay, + }, + { + "params": [p for n, p in params.items() if any(nd in n for nd in no_decay)], + "weight_decay": 0.0, + }, + ] + if self.args.optimizer == 'adam': + self.optimizer = AdamW( + optimizer_grouped_parameters, + lr=self.args.learning_rate, + betas=(self.args.adam_beta1, self.args.adam_beta2), + eps=self.args.adam_epsilon, + ) + elif self.args.optimizer == 'sgd': + self.optimizer = SGD( + optimizer_grouped_parameters, + lr=self.args.learning_rate + ) + else: + raise NotImplementedError + if self.lr_scheduler is None: + self.lr_scheduler = get_scheduler( + self.args.lr_scheduler_type, + optimizer=self.optimizer, + num_warmup_steps=self.args.get_warmup_steps(num_training_steps), + num_training_steps=num_training_steps, + ) + + def should_optim(self, name, param): + return (not self.args.layer_wise_optim or f".{self.state.global_step % self.model.config.num_hidden_layers}." in name) and param.requires_grad + + def zo_forward(self, model: nn.Module, inputs: Dict[str, Union[torch.Tensor, Any]]) -> torch.Tensor: + model.eval() + inputs = self._prepare_inputs(inputs) + if self.args.optimize_acc: + loss, logits = model(**inputs) + preds = F.softmax(logits, dim=-1) + acc = torch.sum(torch.argmax(preds, 1) == inputs['labels']) / len(preds) + loss = -acc + else: + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + self.state.zo_forward_step += 1 + return loss.detach() + + def efficient_perturb_parameters(self, model: nn.Module, random_seed: int, scaling_factor=1): + torch.manual_seed(random_seed) + for name, param in self.named_parameters_to_optim: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + param.data = param.data + scaling_factor * z * self.args.zero_order_eps + return model + + def norm_perturb_parameters(self, model: nn.Module, random_vector=None, scaling_factor=1): + if random_vector is None: + random_vector = {} + + for name, param in self.named_parameters_to_optim: + if name in random_vector: + z = random_vector[name] + else: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + random_vector[name] = z + + cname = self.retrieve_c(name) + if cname in self.cs: + z = z / self.cs[cname] + + param.data = param.data + scaling_factor * z * self.args.zero_order_eps + + return model, random_vector + + def perturb_parameters(self, model: nn.Module, random_vector=None, scaling_factor=1): + if random_vector is None: + random_vector = {} + + for name, param in self.named_parameters_to_optim: + if name in random_vector: + z = random_vector[name] + else: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + random_vector[name] = z + param.data = param.data + scaling_factor * z * self.args.zero_order_eps + + return model, random_vector + + def perturb_single_layer(self, model, layer_name, random_vector=None, scaling_factor=1): + if random_vector is None: + random_vector = {} + + for name, param in self.named_parameters_to_optim: + cname = self.retrieve_c(name) + if cname == layer_name: + if name in random_vector: + z = random_vector[name] + else: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + random_vector[name] = z + param.data = param.data + scaling_factor * z * self.args.zero_order_eps + + return model, random_vector + + def initialize_c(self, model, inputs): + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if self.should_optim(name, param): + self.named_parameters_to_optim.append((name, param)) + + self.cs = {'embed': 0.0, 'lm_head': 0.0} + # OPT: embed_tokens; embed_positions + # RoBERTa: embeddings + self.num_params = copy.deepcopy(self.cs) + self.num_model_layers = model.config.num_hidden_layers + layer_name = "layers" if model.config.model_type == "opt" else "layer" + for i in range(self.num_model_layers): + self.cs[f'{layer_name}.{i}.'] = 0.0 + self.num_params[f'{layer_name}.{i}.'] = 0 + + # ZO estimation of c's + if self.args.zo_variant != 'param_norm' and self.args.use_zo_grad_est: + for layer in self.cs.keys(): + with torch.no_grad(): + model, z = self.perturb_single_layer(model, layer_name=layer) + loss1 = self.zo_forward(model, inputs) + model, z = self.perturb_single_layer(model, layer_name=layer, random_vector=z, scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + + projected_grad = (loss1 - loss2) / (2 * self.args.zero_order_eps) + self.cs[layer] = torch.abs(projected_grad) + + model, z = self.perturb_single_layer(model, layer_name=layer, random_vector=z) + + # no need to run backprop if we are using parameter norm variant, can just measure them + elif self.args.zo_variant == 'param_norm': + for name, param in self.named_parameters_to_optim: + print(name) + ckey = self.retrieve_c(name) + if ckey in self.cs: + self.cs[ckey] += torch.sum(param.data ** 2) + self.num_params[ckey] += param.data.numel() + + # take sqrt to get norm + for ckey in self.cs: + self.cs[ckey] = torch.sqrt(self.cs[ckey]) + if self.args.scale_norm_by_num_params: + self.cs[ckey] /= torch.sqrt(self.cs[ckey]) + + for ckey in self.cs: + if self.cs[ckey] != 0: + self.cs[ckey] = self.cs[ckey].detach().item() + + # backpropagation estimation fo ZO c's + # this is mostly for debugging purposes to disentangle the variance from using ZO to estimate c + # from the effectiveness of the preconditioners + else: + model.eval() + inputs = self._prepare_inputs(inputs) + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + loss = loss.mean() # mean() to average on multi-gpu parallel training + loss.backward() + for name, param in self.named_parameters_to_optim: + if param.grad is None: + print(name) + else: + ckey = self.retrieve_c(name) + if ckey in self.cs: + self.cs[ckey] += torch.sum(param.grad ** 2) + self.num_params[ckey] += param.grad.numel() + + # take sqrt to get norm + for ckey in self.cs: + self.cs[ckey] = torch.sqrt(self.cs[ckey]) + if self.args.scale_norm_by_num_params: + self.cs[ckey] /= torch.sqrt(self.num_params[ckey]) + + for ckey in self.cs: + if self.cs[ckey] != 0: + self.cs[ckey] = self.cs[ckey].detach().item() + + self.layer_names = list(self.cs.keys()) + model.zero_grad() + + def retrieve_c(self, param_name): + for c_name in self.cs.keys(): + if c_name in param_name: + return c_name + + return '' # these parameters are likely not being used in the forward pass + + def get_num_samples(self): + if self.args.zero_order_sample_scheduler is None: + noise_sample_time = 1 + elif self.args.zero_order_sample_scheduler == "linear": + noise_sample_time = max(1, int(self.state.global_step / self.args.max_steps * self.args.zero_order_sample)) + elif self.args.zero_order_sample_scheduler == "constant": + noise_sample_time = int(self.args.zero_order_sample) + else: + raise NotImplementedError + # print("Sample %d zs" % (noise_sample_time)) + + return noise_sample_time + + def train(self, model_path=None, dev_objective=None): + """ + Main training entry point. + + The training logic is directly borrowed from transformers.Trainer (version 3.0.2). + Add early stopping. + """ + if self.args.from_linearhead and model_path is None: + super().train(model_path, dev_objective) # Train output layer using LinearHeadTrainer + + self.best_dir = None + self.objective = -float("inf") + self.dev_objective = dev_objective if dev_objective is not None else default_dev_objective + + # Data loading. + train_dataloader = self.get_train_dataloader() + num_update_steps_per_epoch = len(train_dataloader) // self.args.gradient_accumulation_steps + if num_update_steps_per_epoch == 0: + num_update_steps_per_epoch = 1 + if self.args.max_steps > 0: + t_total = self.args.max_steps + num_train_epochs = self.args.max_steps // num_update_steps_per_epoch + int( + self.args.max_steps % num_update_steps_per_epoch > 0 + ) + else: + t_total = int(len(train_dataloader) // self.args.gradient_accumulation_steps * self.args.num_train_epochs) + num_train_epochs = self.args.num_train_epochs + + self.create_optimizer_and_scheduler(num_training_steps=t_total) + optimizer = self.optimizer + scheduler = self.lr_scheduler + + # Check if saved optimizer or scheduler states exist + if ( + model_path is not None + and os.path.isfile(os.path.join(model_path, "optimizer.pt")) + and os.path.isfile(os.path.join(model_path, "scheduler.pt")) + ): + # Load in optimizer and scheduler states + optimizer.load_state_dict( + torch.load(os.path.join(model_path, "optimizer.pt"), map_location=self.args.device) + ) + scheduler.load_state_dict(torch.load(os.path.join(model_path, "scheduler.pt"))) + + model = self.model + + if self.args.fp16 and _use_apex: + if not transformers.is_apex_available(): + raise ImportError("Please install apex from https://www.github.com/nvidia/apex to use fp16 training.") + model, optimizer = amp.initialize(model, optimizer, opt_level=self.args.fp16_opt_level) + + # Multi-gpu training (should be after apex fp16 initialization) + if self.args.n_gpu > 1: + model = torch.nn.DataParallel(model) + + # Distributed training (should be after apex fp16 initialization) + if self.args.local_rank != -1: + model = torch.nn.parallel.DistributedDataParallel( + model, + device_ids=[self.args.local_rank], + output_device=self.args.local_rank, + find_unused_parameters=True, + ) + + # Train + if transformers.is_torch_tpu_available(): + total_train_batch_size = self.args.train_batch_size * xm.xrt_world_size() + else: + total_train_batch_size = ( + self.args.train_batch_size + * self.args.gradient_accumulation_steps + * (torch.distributed.get_world_size() if self.args.local_rank != -1 else 1) + ) + logger.info("***** Running training *****") + logger.info(" Num examples = %d", self.num_examples(train_dataloader)) + logger.info(" Num Epochs = %d", num_train_epochs) + logger.info(" Instantaneous batch size per device = %d", self.args.per_device_train_batch_size) + logger.info(" Total train batch size (w. parallel, distributed & accumulation) = %d", total_train_batch_size) + logger.info(" Gradient Accumulation steps = %d", self.args.gradient_accumulation_steps) + logger.info(" Total optimization steps = %d", t_total) + + self.state = TrainerState() + self.state.global_step = 0 + start_time = time.time() + self.state.zo_forward_step = 0 + self.epoch = 0 + epochs_trained = 0 + steps_trained_in_current_epoch = 0 + + if self.args.gradient_checkpointing: + model.gradient_checkpointing_enable() + + # Check if continuing training from a checkpoint + if model_path is not None: + # set global_step to global_step of last saved checkpoint from model path + try: + self.state.global_step = int(model_path.split("-")[-1].split("/")[0]) + epochs_trained = self.state.global_step // (len(train_dataloader) // self.args.gradient_accumulation_steps) + steps_trained_in_current_epoch = self.state.global_step % ( + len(train_dataloader) // self.args.gradient_accumulation_steps + ) + + logger.info(" Continuing training from checkpoint, will skip to saved global_step") + logger.info(" Continuing training from epoch %d", epochs_trained) + logger.info(" Continuing training from global step %d", self.state.global_step) + logger.info(" Will skip the first %d steps in the first epoch", steps_trained_in_current_epoch) + except ValueError: + self.state.global_step = 0 + logger.info(" Starting fine-tuning.") + + tr_loss = torch.tensor(0.0).to(self.args.device) + logging_loss_scalar = 0.0 + model.zero_grad() + metrics = None + for epoch in range(epochs_trained, int(num_train_epochs)): + if isinstance(train_dataloader, DataLoader) and isinstance(train_dataloader.sampler, DistributedSampler): + train_dataloader.sampler.set_epoch(epoch) + + if transformers.is_torch_tpu_available(): + parallel_loader = pl.ParallelLoader(train_dataloader, [self.args.device]).per_device_loader( + self.args.device + ) + epoch_iterator = tqdm(parallel_loader, desc="Iteration", disable=not self.is_local_process_zero()) + else: + epoch_iterator = tqdm(train_dataloader, desc="Iteration", disable=True) + + # Reset the past mems state at the beginning of each epoch if necessary. + if self.args.past_index >= 0: + self._past = None + + for step, inputs in enumerate(epoch_iterator): + if self.args.sync_embedding_layers: + assert model.module.model_type == 'opt', 'did not implement embedding layer synchronization for non-OPT models' + model.module.model.decoder.embed_tokens.weight = model.module.lm_head.weight + + # estimate c's (param or grad norm) on epoch 0 + if epoch == 0 and step == 0 and self.args.zo_variant is not None: + self.initialize_c(model, inputs) + elif step == 0 and self.args.zo_variant is not None and self.args.recompute_norms: + self.initialize_c(model, inputs) + + # Skip past any already trained steps if resuming training + if steps_trained_in_current_epoch > 0: + steps_trained_in_current_epoch -= 1 + continue + + if self.args.zero_order_optim: + # Get parameters that should be optimized (for layer-wise optimization and prefix-tuning) + self.named_parameters_to_optim = [] + for name, param in model.named_parameters(): + if self.should_optim(name, param): + self.named_parameters_to_optim.append((name, param)) + + if self.args.zo_by_layer: + assert not self.args.efficient_zero_order, 'did not implement preconditioned ZO for efficient ZO yet' + assert self.args.zero_order_use_trainer_optim, 'preconditioned ZO requires using the trainer optimizer' + num_zs = self.get_num_samples() + layers = [np.random.choice(self.layer_names)] if self.args.pc_rnd_layer else self.layer_names + + # for each layer: perturb only that layer and store the gradient estimates in the grad buffer + for layer in self.layer_names: + for _ in range(num_zs): + c_i = self.cs[layer] + with torch.no_grad(): + c_i = 1.0 if c_i == 0 else c_i # if the scaling is 0, just reset it to 1 so that there can eventually be some gradient to those layers + model, random_vector = self.perturb_single_layer(model, layer, scaling_factor=1.0/c_i) + loss1 = self.zo_forward(model, inputs) + model, random_vector = self.perturb_single_layer(model, layer, random_vector=random_vector, scaling_factor=-2.0/c_i) + loss2 = self.zo_forward(model, inputs) + model, random_vector = self.perturb_single_layer(model, layer, random_vector=random_vector, scaling_factor=1.0/c_i) + + projected_grad = (loss1 - loss2) / (2 * self.args.zero_order_eps) + # scale grad according to number of zs sampled + if not self.args.scale_lr_with_samples: + projected_grad = projected_grad / float(num_zs) + + for name, param in self.named_parameters_to_optim: + if self.retrieve_c(name) == layer: + z_tilde = random_vector[name] * c_i + + if param.grad is None: + param.grad = projected_grad * z_tilde + else: + param.grad += projected_grad * z_tilde + + # note that | E_z [ ] | is equal to norm of grad for that layer for gaussian z + # leverages this fact to update the grad norms + if self.args.zo_variant == 'grad_norm' and self.args.norm_running_update: + self.cs[layer] = torch.abs(projected_grad) + else: + # get number of zs to sample + num_zs = self.get_num_samples() + if num_zs > 1: + assert self.args.zero_order_use_trainer_optim, 'cannot sample multiple zs without storing intermediate gradient. use trainer.' + + for _ in range(num_zs): + # prepare for sampling new zs + random_vector = None + if self.args.efficient_zero_order: + random_seed = np.random.randint(1000000000) + + with torch.no_grad(): + # first function evaluation + if self.args.efficient_zero_order: + model = self.efficient_perturb_parameters(model, random_seed) + elif self.args.zo_variant is not None: + model, random_vector = self.norm_perturb_parameters(model) + else: + model, random_vector = self.perturb_parameters(model) + loss1 = self.zo_forward(model, inputs) + + # second function evaluation + if self.args.efficient_zero_order: + model = self.efficient_perturb_parameters(model, random_seed, scaling_factor=-2) + elif self.args.zo_variant is not None: + model, random_vector = self.norm_perturb_parameters(model, random_vector, scaling_factor=-2) + else: + model, random_vector = self.perturb_parameters(model, random_vector, scaling_factor=-2) + loss2 = self.zo_forward(model, inputs) + + projected_grad = (loss1 - loss2) / (2 * self.args.zero_order_eps) + + # scale grad according to accumulation + if self.args.gradient_accumulation_steps > 1: + assert self.args.zero_order_use_trainer_optim, 'grad accumulation not implemented for non-trainer ZO yet' + projected_grad = projected_grad / self.args.gradient_accumulation_steps + + # scale grad according to number of zs sampled + if not self.args.scale_lr_with_samples: + projected_grad = projected_grad / float(num_zs) + + # store gradient in parameter buffer if using trainer + # o/w, the loop will exit after one round and the update will be applied directly (see below) + if self.args.zero_order_use_trainer_optim: + if self.args.efficient_zero_order: + # print(random_seed) + torch.manual_seed(random_seed) + + for name, param in self.named_parameters_to_optim: + # recover noise used in perturbations + if self.args.efficient_zero_order: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + else: + z = random_vector[name] + + if self.args.zo_variant is not None and not self.args.change_grad_estimate: + cname = self.retrieve_c(name) + if cname in self.cs: + z = z * self.cs[cname] + + if param.grad is None: + param.grad = projected_grad * z + else: + param.grad += projected_grad * z + + # reset model back to its parameters at start of step + if self.args.efficient_zero_order: + model = self.efficient_perturb_parameters(model, random_seed) + elif self.args.zo_variant is not None: + model, random_vector = self.norm_perturb_parameters(model, random_vector) + else: + model, random_vector = self.perturb_parameters(model, random_vector) + + # apply gradient updates + # if using trainer, follow trainer logic to clip grad and check if parameters should be updated + if self.args.zero_order_use_trainer_optim: + if (step + 1) % self.args.gradient_accumulation_steps == 0 or ( + # last step in epoch but step is always smaller than gradient_accumulation_steps + len(epoch_iterator) <= self.args.gradient_accumulation_steps + and (step + 1) == len(epoch_iterator) + ): + # Gradient norm clipping + if self.args.zero_order_clip_grad: + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm) + + # Update the parameters and step scheduler + optimizer.step() + scheduler.step() + + # logging + if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or ( + self.state.global_step == 1 and self.args.logging_first_step + ): + logs = {} + logs["loss"] = loss1.item() + if not self.args.zero_order_clip_grad: + norm = 0.0 + for _, p in model.named_parameters(): + if p.grad is not None: + norm += torch.sum(p.grad ** 2) + norm = torch.sqrt(norm) + logs["grad_norm"] = norm.item() + logs["learning_rate"] = ( + scheduler.get_last_lr()[0] + if version.parse(torch.__version__) >= version.parse("1.4") + else scheduler.get_lr()[0] + ) + logs["num_zs"] = num_zs + logs["global_step"] = self.state.global_step + logs["zo_forward_step"] = self.state.zo_forward_step + logs["max_steps"] = self.args.max_steps + logs["max_zo_forward_steps"] = self.args.max_zo_forward_steps + logs["time"] = int(time.time() - start_time) + self.log(logs) + logger.info(str(logs)) + + model.zero_grad() + self.state.global_step += 1 + self.epoch = epoch + (step + 1) / len(epoch_iterator) + # if not using the trainer, the updates are resampled and directly applied to the parameters + else: + # Efficient mode + # WARNING: no gradient accumulation when not storing the grad + assert self.args.gradient_accumulation_steps == 1, 'gradient accumulation is not supported for zero-order optimization' + assert self.args.zero_order_sample_scheduler is None + assert not self.args.zero_order_clip_grad, 'gradient clipping not implemented yet for non-trainer ZO' + + if self.args.efficient_zero_order: + torch.manual_seed(random_seed) + for name, param in self.named_parameters_to_optim: + if self.args.efficient_zero_order: + z = torch.normal(mean=0, std=1, size=param.data.size(), device=param.data.device, dtype=param.data.dtype) + else: + z = random_vector[name] + param.data = param.data - self.args.learning_rate * (projected_grad * z + self.args.weight_decay * param.data) + + if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or ( + self.state.global_step == 1 and self.args.logging_first_step + ): + logs = {} + logs["loss"] = loss1.item() + logs["learning_rate"] = self.args.learning_rate + logs["global_step"] = self.state.global_step + logs["zo_forward_step"] = self.state.zo_forward_step + logs["max_steps"] = self.args.max_steps + logs["max_zo_forward_steps"] = self.args.max_zo_forward_steps + logs["time"] = int(time.time() - start_time) + self.log(logs) + logger.info(str(logs)) + + + self.state.global_step += 1 + self.epoch = epoch + (step + 1) / len(epoch_iterator) + + # Debug information + # print("%.5f, %.5f" % (loss1.item(), loss2.item())) + # print("Loss: %.10f, projected_grad: %.5f" % (loss1, projected_grad)) + + # standard, non-ZO optimization + else: + tr_loss += self.training_step(model, inputs) + + if (step + 1) % self.args.gradient_accumulation_steps == 0 or ( + # last step in epoch but step is always smaller than gradient_accumulation_steps + len(epoch_iterator) <= self.args.gradient_accumulation_steps + and (step + 1) == len(epoch_iterator) + ): + if self.args.fp16 and _use_native_amp: + self.scaler.unscale_(optimizer) + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm) + elif self.args.fp16: + norm = torch.nn.utils.clip_grad_norm_(amp.master_params(optimizer), self.args.max_grad_norm) + else: + norm = torch.nn.utils.clip_grad_norm_(model.parameters(), self.args.max_grad_norm) + + if self.args.optimizer_variant == 'signgd': + for n,p in model.named_parameters(): + if p.grad is not None: + p.grad = torch.sign(p.grad) + + if transformers.is_torch_tpu_available(): + xm.optimizer_step(optimizer) + elif self.args.fp16 and _use_native_amp: + self.scaler.step(optimizer) + self.scaler.update() + else: + optimizer.step() + + scheduler.step() + model.zero_grad() + self.state.global_step += 1 + self.epoch = epoch + (step + 1) / len(epoch_iterator) + + if (self.args.logging_steps > 0 and self.state.global_step % self.args.logging_steps == 0) or ( + self.state.global_step == 1 and self.args.logging_first_step + ): + logs = {} + tr_loss_scalar = tr_loss.item() + logs["loss"] = (tr_loss_scalar - logging_loss_scalar) / self.args.logging_steps + logs["norm"] = norm.item() + # backward compatibility for pytorch schedulers + logs["learning_rate"] = ( + scheduler.get_last_lr()[0] + if version.parse(torch.__version__) >= version.parse("1.4") + else scheduler.get_lr()[0] + ) + logging_loss_scalar = tr_loss_scalar + + self.log(logs) + logger.info(str(logs)) + + if self.args.max_steps > 0 and self.state.global_step > self.args.max_steps or (self.args.max_zo_forward_steps > 0 and self.state.zo_forward_step > self.args.max_zo_forward_steps): + epoch_iterator.close() + break + + if self.args.evaluate_during_training and self.state.global_step % self.args.eval_steps == 0: + output = self.evaluate() + metrics = output.metrics + objective = self.dev_objective(metrics) + if objective > self.objective: + logger.info("Best dev result: {}".format(objective)) + self.objective = objective + # self.save_model(self.args.output_dir) + + # Now we save this to (CPU) memory instead of disk <-- much faster + self.best_model_ckpt = {k: v.detach().cpu() for k, v in model.state_dict().items()} + + if self.args.max_steps > 0 and self.state.global_step > self.args.max_steps or (self.args.max_zo_forward_steps > 0 and self.state.zo_forward_step > self.args.max_zo_forward_steps): + # train_iterator.close() + break + if self.args.tpu_metrics_debug or self.args.debug: + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + + if self.args.past_index and hasattr(self, "_past"): + # Clean the state at the end of training + delattr(self, "_past") + + logger.info("\n\nTraining completed. Do not forget to share your model on huggingface.co/models =)\n\n") + return TrainOutput(self.state.global_step, tr_loss / self.state.global_step, metrics), self.objective + + + """ + Difference compared to original implementation: return output instead of output.metrics (so there is also the logits) + """ + def evaluate(self, eval_dataset: Optional[Dataset] = None) -> Dict[str, float]: + """ + Run evaluation and returns metrics. + + The calling script will be responsible for providing a method to compute metrics, as they are + task-dependent (pass it to the init :obj:`compute_metrics` argument). + + You can also subclass and override this method to inject custom behavior. + + Args: + eval_dataset (:obj:`Dataset`, `optional`): + Pass a dataset if you wish to override :obj:`self.eval_dataset`. If it is an :obj:`datasets.Dataset`, + columns not accepted by the ``model.forward()`` method are automatically removed. It must implement + the :obj:`__len__` method. + + Returns: + A dictionary containing the evaluation loss and the potential metrics computed from the predictions. + """ + if eval_dataset is not None and not isinstance(eval_dataset, collections.abc.Sized): + raise ValueError("eval_dataset must implement __len__") + + eval_dataloader = self.get_eval_dataloader(eval_dataset) + + output = self.prediction_loop(eval_dataloader, description="Evaluation") + + self.log(output.metrics) + logger.info(output.metrics) + + if self.args.tpu_metrics_debug or self.args.debug: + # tpu-comment: Logging debug metrics for PyTorch/XLA (compile, execute times, ops, etc.) + xm.master_print(met.metrics_report()) + + return output diff --git a/baselines/mezo/medium_models/tools/gather_result.py b/baselines/mezo/medium_models/tools/gather_result.py new file mode 100644 index 0000000..708bcc9 --- /dev/null +++ b/baselines/mezo/medium_models/tools/gather_result.py @@ -0,0 +1,259 @@ +import argparse +import json +import numpy as np +import torch +from torch import device +import itertools + +from transformers.optimization import get_scheduler + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--condition", type=str, help="A dictionary contains conditions that the experiment results need to fulfill (e.g., tag, task_name, few_shot_type)") + parser.add_argument("--args_to_care", default=None, type=str, help="A list of args to care about. If provided, outputs which configs were not tested in your grid search") + + # These options should be kept as their default values + parser.add_argument("--log", type=str, default="log", help="Log path.") + parser.add_argument("--key", type=str, default='', help="Validation metric name") + parser.add_argument("--test_key", type=str, default="", help="Test metric name") + parser.add_argument("--test_key2", type=str, default="", help="Second test metric name") + + args = parser.parse_args() + + condition = eval(args.condition) + if args.args_to_care is not None: + args_to_care = eval(args.args_to_care) + + if len(args.key) == 0: + if condition['task_name'] == 'cola': + args.key = 'cola_dev_eval_mcc' + args.test_key = 'cola_test_eval_mcc' + elif condition['task_name'] == 'mrpc/acc': + args.key = 'mrpc_dev_eval_acc' + args.test_key = 'mrpc_test_eval_acc' + args.test_key2 = 'mrpc_test_eval_f1' + condition['task_name'] = 'mrpc' + elif condition['task_name'] == 'mrpc/f1': + args.key = 'mrpc_dev_eval_f1' + args.test_key2 = 'mrpc_test_eval_acc' + args.test_key = 'mrpc_test_eval_f1' + condition['task_name'] = 'mrpc' + elif condition['task_name'] == 'qqp/acc': + args.key = 'qqp_dev_eval_acc' + args.test_key = 'qqp_test_eval_acc' + args.test_key2 = 'qqp_test_eval_f1' + condition['task_name'] = 'qqp' + elif condition['task_name'] == 'qqp/f1': + args.key = 'qqp_dev_eval_f1' + args.test_key2 = 'qqp_test_eval_acc' + args.test_key = 'qqp_test_eval_f1' + condition['task_name'] = 'qqp' + elif condition['task_name'] == 'sts-b/pearson': + args.key = 'sts-b_dev_eval_pearson' + args.test_key = 'sts-b_test_eval_pearson' + args.test_key2 = 'sts-b_test_eval_spearmanr' + condition['task_name'] = 'sts-b' + elif condition['task_name'] == 'sts-b/spearmanr': + args.key = 'sts-b_dev_eval_spearmanr' + args.test_key2 = 'sts-b_test_eval_pearson' + args.test_key = 'sts-b_test_eval_spearmanr' + condition['task_name'] = 'sts-b' + elif condition['task_name'] == 'qnli': + args.key = 'qnli_dev_eval_acc' + args.test_key = 'qnli_test_eval_acc' + elif condition['task_name'] == 'sst-2': + args.key = 'sst-2_dev_eval_acc' + args.test_key = 'sst-2_test_eval_acc' + elif condition['task_name'] == 'snli': + args.key = 'snli_dev_eval_acc' + args.test_key = 'snli_test_eval_acc' + elif condition['task_name'] == 'mnli': + args.key = 'mnli_dev_eval_mnli/acc' + args.test_key = 'mnli_test_eval_mnli/acc' + elif condition['task_name'] == 'mnli-mm': + condition['task_name'] = 'mnli' + args.key = 'mnli_dev_eval_mnli/acc' + args.test_key = 'mnli-mm_test_eval_mnli-mm/acc' + elif condition['task_name'] == 'rte': + args.key = 'rte_dev_eval_acc' + args.test_key = 'rte_test_eval_acc' + elif condition['task_name'] == 'ag_news': + args.key = 'ag_news_dev_eval_acc' + args.test_key = 'ag_news_test_eval_acc' + elif condition['task_name'] == 'yahoo_answers': + args.key = 'yahoo_answers_dev_eval_acc' + args.test_key = 'yahoo_answers_test_eval_acc' + elif condition['task_name'] == 'yelp_review_full': + args.key = 'yelp_review_full_dev_eval_acc' + args.test_key = 'yelp_review_full_test_eval_acc' + elif condition['task_name'] == 'mr': + args.key = 'mr_dev_eval_acc' + args.test_key = 'mr_test_eval_acc' + elif condition['task_name'] == 'sst-5': + args.key = 'sst-5_dev_eval_acc' + args.test_key = 'sst-5_test_eval_acc' + elif condition['task_name'] == 'subj': + args.key = 'subj_dev_eval_acc' + args.test_key = 'subj_test_eval_acc' + elif condition['task_name'] == 'trec': + args.key = 'trec_dev_eval_acc' + args.test_key = 'trec_test_eval_acc' + elif condition['task_name'] == 'cr': + args.key = 'cr_dev_eval_acc' + args.test_key = 'cr_test_eval_acc' + elif condition['task_name'] == 'mpqa': + args.key = 'mpqa_dev_eval_acc' + args.test_key = 'mpqa_test_eval_acc' + else: + raise NotImplementedError + + with open(args.log) as f: + result_list = [] + for line in f: + line = line.replace("<", "\"") + line = line.replace(">", "\"") + line = line.replace(" inf,", "float('inf'),") + line = line.replace(" nan,", "float('nan'),") + result_list.append(eval(line)) + + seed_result = {} + + for item in result_list: + ok = True + for cond in condition: + if isinstance(condition[cond], list): + if cond not in item or (item[cond] not in condition[cond]): + ok = False + break + else: + if cond not in item or (item[cond] != condition[cond]): + ok = False + break + if ok and args.test_key in item and args.key in item: + seed = item['data_dir'].split('-')[-1] + '-' + str(item['seed']) + if seed not in seed_result: + seed_result[seed] = [item] + else: + seed_result[seed].append(item) + + all_seed_result = seed_result + all_tags = sorted(set(x['tag'] for x in sum(all_seed_result.values(), []))) + all_k = sorted(set(x['num_k'] for x in sum(all_seed_result.values(), []))) + + for tag in all_tags: + for k in all_k: + print("Tag: {}, K: {}".format(tag, k)) + seed_result_with_duplicates = { + s: list(x for x in v if x['tag'] == tag and x['num_k'] == k) + for s, v in all_seed_result.items() + } + seed_result = { + s: list({x['output_dir']: x for x in v}.values()) + for s, v in seed_result_with_duplicates.items() + } + seed_best = { + k: max(sorted(v, key=lambda x: x['output_dir']), key=lambda x: x[args.key]) + for k, v in seed_result.items() if v + } + + ### check if all possible configs were run or not + if args.args_to_care is not None: + unique_arg_values = {} + for _arg in args_to_care: + unique_arg_values[_arg] = [] + + # collect all desired configs and all that were run + arg_configs = {} # all configs that were run + for seed in seed_result.keys(): + seed_configs = [] + for config in seed_result[seed]: + if config['tag'] == tag and config['num_k'] == k: + _config = [] + for _arg in args_to_care: + _value = config[_arg] + if _value not in unique_arg_values[_arg]: + unique_arg_values[_arg].append(_value) + _config.append(_value) + seed_configs.append(tuple(_config)) + arg_configs[seed] = seed_configs + + # compare to all possible configs + missing_configs = {'seeds': []} + for arg in args_to_care: + missing_configs[f'{arg}s'] = [] + + num_missing = 0 + for seed in seed_result.keys(): + all_possible_configs = itertools.product(*list(unique_arg_values.values())) + print(f'Missing configs for seed {seed}') + for config in all_possible_configs: + if config not in arg_configs[seed]: + missing_configs['seeds'].append(seed.split('-')[-1]) + print(f'\t', end='') + for _arg, _val in zip(args_to_care, config): + print(f'{_arg}: {_val}', end=' ') + missing_configs[f'{_arg}s'].append(str(_val)) + print() + num_missing += 1 + + print(f'Rerun {num_missing} configs') + for key, missed in missing_configs.items(): + missed_str = ' '.join(missed) + print(f'{key}=({missed_str})') + + final_result_dev = np.zeros((len(seed_best))) + final_result_test = np.zeros((len(seed_best))) + final_result_test2 = np.zeros((len(seed_best))) + final_result_loss = np.zeros((len(seed_best))) + num_results = np.zeros((len(seed_best))) + for i, seed in enumerate(seed_best): + # for res in seed_result[seed]: + # print(res) + + final_result_dev[i] = seed_best[seed][args.key] + final_result_test[i] = seed_best[seed][args.test_key] + test_loss_key = args.test_key.split("_eval")[0] + "_eval_loss" + dev_loss_key = test_loss_key.replace("test", "dev") + final_result_loss[i] = seed_best[seed][test_loss_key] + num_results[i] = len(seed_result[seed]) + if len(args.test_key2) > 0: + final_result_test2[i] = seed_best[seed][args.test_key2] + print("%s: best dev (%.5f, loss=%.4f) test (%.5f, loss=%.4f) %s | total trials: %d (ignored %d)" % ( + seed, + seed_best[seed][args.key], + seed_best[seed][dev_loss_key], + seed_best[seed][args.test_key], + seed_best[seed][test_loss_key], + "test2 (%.5f)" % (seed_best[seed][args.test_key2]) if len(args.test_key2) > 0 else "", + len(seed_result[seed]), + len(seed_result_with_duplicates[seed]) - len(seed_result[seed]) + )) + s = '' + if args.args_to_care is None: + hp_to_care_about = [ + 'per_device_train_batch_size', + 'gradient_accumulation_steps', + 'learning_rate', + 'zero_order_eps', + 'zero_order_sample', + 'zero_order_sample_scheduler', + 'scale_lr_with_samples', + 'lr_scheduler_type', + 'weight_decay', + ] + else: + hp_to_care_about = args_to_care + for k in hp_to_care_about: + s += '| {}: {} '.format(k, seed_best[seed].get(k, "")) + print(' ' + s) + s = "mean +- std: " + if len(final_result_test) > 0: + s += "%.1f (%.1f) (#seeds %s) (#runs %s) (median %.1f)" % (final_result_test.mean() * 100, final_result_test.std() * 100, len(final_result_test), num_results.sum(), np.median(final_result_test) * 100,) + if len(args.test_key2) > 0: + s += " | second metric: %.1f (%.1f) (median %.1f)" % (final_result_test2.mean() * 100, final_result_test2.std() * 100, np.median(final_result_test2) * 100) + s += " | loss: %.4f (%.4f)" % (final_result_loss.mean(), final_result_loss.std()) + print(s) + print("") + +if __name__ == '__main__': + main() diff --git a/baselines/mezo/medium_models/tools/generate_k_shot_data.py b/baselines/mezo/medium_models/tools/generate_k_shot_data.py new file mode 100644 index 0000000..8196809 --- /dev/null +++ b/baselines/mezo/medium_models/tools/generate_k_shot_data.py @@ -0,0 +1,192 @@ +"""This script samples K examples randomly without replacement from the original data.""" + +import argparse +import os +import numpy as np +import pandas as pd +from pandas import DataFrame + +def get_label(task, line): + if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]: + # GLUE style + line = line.strip().split('\t') + if task == 'CoLA': + return line[1] + elif task == 'MNLI': + return line[-1] + elif task == 'MRPC': + return line[0] + elif task == 'QNLI': + return line[-1] + elif task == 'QQP': + return line[-1] + elif task == 'RTE': + return line[-1] + elif task == 'SNLI': + return line[-1] + elif task == 'SST-2': + return line[-1] + elif task == 'STS-B': + return 0 if float(line[-1]) < 2.5 else 1 + elif task == 'WNLI': + return line[-1] + else: + raise NotImplementedError + else: + return line[0] + +def load_datasets(data_dir, tasks): + datasets = {} + for task in tasks: + if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]: + # GLUE style (tsv) + dataset = {} + dirname = os.path.join(data_dir, task) + if task == "MNLI": + splits = ["train", "dev_matched", "dev_mismatched"] + else: + splits = ["train", "dev"] + for split in splits: + filename = os.path.join(dirname, f"{split}.tsv") + with open(filename, "r") as f: + lines = f.readlines() + dataset[split] = lines + datasets[task] = dataset + else: + # Other datasets (csv) + dataset = {} + dirname = os.path.join(data_dir, task) + splits = ["train", "test"] + for split in splits: + filename = os.path.join(dirname, f"{split}.csv") + dataset[split] = pd.read_csv(filename, header=None) + datasets[task] = dataset + return datasets + +def split_header(task, lines): + """ + Returns if the task file has a header or not. Only for GLUE tasks. + """ + if task in ["CoLA"]: + return [], lines + elif task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI"]: + return lines[0:1], lines[1:] + else: + raise ValueError("Unknown GLUE task.") + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("--k", type=int, default=16, + help="Training examples for each class.") + parser.add_argument("--task", type=str, nargs="+", + default=['SST-2', 'sst-5', 'mr', 'cr', 'mpqa', 'subj', 'trec', 'CoLA', 'MRPC', 'QQP', 'STS-B', 'MNLI', 'SNLI', 'QNLI', 'RTE'], + help="Task names") + parser.add_argument("--seed", type=int, nargs="+", + default=[100, 13, 21, 42, 87], + help="Random seeds") + + parser.add_argument("--data_dir", type=str, default="data/original", help="Path to original data") + parser.add_argument("--output_dir", type=str, default="data", help="Output path") + parser.add_argument("--mode", type=str, default='k-shot', choices=['k-shot', 'k-shot-10x', 'k-shot-1k-test'], help="k-shot or k-shot-10x (10x dev set)") + + args = parser.parse_args() + args.output_dir = os.path.join(args.output_dir, args.mode) + + k = args.k + print("K =", k) + datasets = load_datasets(args.data_dir, args.task) + + for seed in args.seed: + print("Seed = %d" % (seed)) + for task, dataset in datasets.items(): + # Set random seed + np.random.seed(seed) + + # Shuffle the training set + print("| Task = %s" % (task)) + if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]: + # GLUE style + train_header, train_lines = split_header(task, dataset["train"]) + np.random.shuffle(train_lines) + else: + # Other datasets + train_lines = dataset['train'].values.tolist() + np.random.shuffle(train_lines) + + # Set up dir + task_dir = os.path.join(args.output_dir, task) + setting_dir = os.path.join(task_dir, f"{k}-{seed}") + os.makedirs(setting_dir, exist_ok=True) + + # Write test splits + if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]: + # GLUE style + # Use the original development set as the test set (the original test sets are not publicly available) + for split, lines in dataset.items(): + if split.startswith("train"): + continue + split = split.replace('dev', 'test') + + test_header, test_lines = split_header(task, lines) + if '1k-test' in args.mode and len(test_lines) > 1000: + np.random.seed(42) + np.random.shuffle(test_lines) + test_lines = test_lines[:1000] + with open(os.path.join(setting_dir, f"{split}.tsv"), "w") as f: + for line in test_header: + f.write(line) + for line in test_lines: + f.write(line) + else: + # Other datasets + # Use the original test sets + test_dataset = dataset['test'] + if '1k-test' in args.mode and len(test_dataset.index) > 1000: + test_dataset = test_dataset.sample(n=1000, random_state=42) + test_dataset.to_csv(os.path.join(setting_dir, 'test.csv'), header=False, index=False) + + # Get label list for balanced sampling + label_list = {} + for line in train_lines: + label = get_label(task, line) + if label not in label_list: + label_list[label] = [line] + else: + label_list[label].append(line) + + if task in ["MNLI", "MRPC", "QNLI", "QQP", "RTE", "SNLI", "SST-2", "STS-B", "WNLI", "CoLA"]: + with open(os.path.join(setting_dir, "train.tsv"), "w") as f: + for line in train_header: + f.write(line) + for label in label_list: + for line in label_list[label][:k]: + f.write(line) + name = "dev.tsv" + if task == 'MNLI': + name = "dev_matched.tsv" + with open(os.path.join(setting_dir, name), "w") as f: + for line in train_header: + f.write(line) + for label in label_list: + dev_rate = 11 if '10x' in args.mode else 2 + for line in label_list[label][k:k*dev_rate]: + f.write(line) + else: + new_train = [] + for label in label_list: + for line in label_list[label][:k]: + new_train.append(line) + new_train = DataFrame(new_train) + new_train.to_csv(os.path.join(setting_dir, 'train.csv'), header=False, index=False) + + new_dev = [] + for label in label_list: + dev_rate = 11 if '10x' in args.mode else 2 + for line in label_list[label][k:k*dev_rate]: + new_dev.append(line) + new_dev = DataFrame(new_dev) + new_dev.to_csv(os.path.join(setting_dir, 'dev.csv'), header=False, index=False) + + +if __name__ == "__main__": + main() diff --git a/baselines/mezo/native.py b/baselines/mezo/native.py new file mode 100644 index 0000000..89c3939 --- /dev/null +++ b/baselines/mezo/native.py @@ -0,0 +1,71 @@ +"""Run the original entry point with shared local assets. No optimizer rewrite.""" +import argparse +from datetime import datetime,timezone +import json +import os +from pathlib import Path +import runpy +import sys + +HERE=Path(__file__).resolve().parent +ROOT=HERE.parents[1] +sys.path.insert(0,str(ROOT/'src')) +from experiments_codebase.paths import paths,model_path,save + +def main(): + p=argparse.ArgumentParser(description=__doc__,add_help=False) + p.add_argument('--asset-model',default='facebook/opt-1.3b') + p.add_argument('--asset-task',choices=['sst2','drop'],default='sst2') + p.add_argument('--asset-out',type=Path) + args,rest=p.parse_known_args();method=HERE.name + roots=paths();os.environ.setdefault('WANDB_MODE','disabled');os.environ['WANDB_DIR']=str(roots['results']/'wandb') + out=(args.asset_out or roots['results']/f'native_{method}_{datetime.now(timezone.utc):%Y%m%dT%H%M%S%fZ}').resolve() + if not out.is_relative_to(roots['results'].resolve()):raise ValueError('Output must be under shared results') + # Both local datasets are supplied through the HF Dataset API expected by authors. + import datasets + original=datasets.load_dataset + def local_dataset(name,*pos,**kw): + config=pos[0] if pos else kw.get('name') + alias='sst2' if (name in ('glue','nyu-mll/glue') and config=='sst2') or name=='sst2' else ('drop' if name in ('drop','ucinlp/drop') else None) + if alias: + ds=datasets.load_from_disk(str(roots['data']/alias)) + split=kw.get('split');return ds[split] if split else ds + return original(name,*pos,**kw) + datasets.load_dataset=local_dataset + model=str(model_path(args.asset_model)) + if method=='loren': + if args.asset_task=='drop':raise ValueError('Official LOREN has no DROP task; use run_compatible.py with the modern group for a labeled task extension') + if 'Qwen' in args.asset_model:raise ValueError('Official LOREN has no Qwen model branch; use the modern compatibility entry') + entry=HERE/'main.py' + defaults=['--model_name',model,'--task',args.asset_task,'--algorithm','LOREN','--results',str(out),'--full_parameter'] + else: + work=HERE/('zo-bench' if method=='agzo' else 'large_models') + entry=work/('run_lozo.py' if method=='lozo' else 'run.py') + task='SST2' if args.asset_task=='sst2' else 'DROP' + defaults=['--model_name',model,'--task_name',task,'--output_dir',str(out),'--trainer',{'mezo':'zo','lozo':'LOZO','agzo':'agzo'}[method], + '--report_to','none','--train_set_seed','42','--train_as_classification',str(task=='SST2'),'--lr_scheduler_type','constant'] + defaults+=['--result_file',str(out/'result.json')] + # User's original HF/author flags appear last and override wrapper defaults. + if '--help' not in rest: + out.mkdir(parents=True,exist_ok=False) + save(out/'launch.json',dict(method=method,entry=str(entry),argv=defaults+rest,executable=sys.executable,adapter='Local assets and paths only; original Trainer/optimizer',pid=os.getpid())) + sys.path.insert(0,str(entry.parent));os.chdir(out if out.exists() else HERE) + sys.argv=[str(entry),*defaults,*rest] + if method=='agzo': + import torch + if torch.cuda.is_available() and not hasattr(torch,'npu'): + # The author's NPU helper has incomplete CUDA branches. Only device + # plumbing is adapted; trainer.py and AGZO numerical methods are intact. + import npu_compat as devices + devices.device_count=torch.cuda.device_count + devices.mem_get_info=torch.cuda.mem_get_info + devices.get_active_device_info=lambda:('cuda',torch.cuda.current_device(),torch.cuda.get_device_properties(0).total_memory/2**30,torch.cuda.get_device_name()) + devices.safe_set_device=lambda index:(torch.cuda.set_device(int(index or 0)) or int(index or 0),torch.cuda.device_count()) + devices.to_device=lambda tensor:tensor.cuda() + source=entry.read_text().replace('torch.npu.manual_seed_all(seed)','torch.cuda.manual_seed_all(seed)').replace('torch.npu.device_count()','torch.cuda.device_count()') + if out.exists():save(out/'compatibility_changes.json',{'scope':'CUDA device plumbing only','source_modified_on_disk':False,'numerical_optimizer_modified':False,'changes':['NPU seed -> CUDA seed','NPU device count -> CUDA count','device helper memory/info/count/set/to_device CUDA callbacks']}) + exec(compile(source,str(entry),'exec'),dict(__name__='__main__',__file__=str(entry))) + return + runpy.run_path(str(entry),run_name='__main__') + +if __name__=='__main__':main() diff --git a/baselines/mezo/pyproject.toml b/baselines/mezo/pyproject.toml new file mode 100644 index 0000000..9bd2562 --- /dev/null +++ b/baselines/mezo/pyproject.toml @@ -0,0 +1,14 @@ +[project] +name = "official-mezo-experiment" +version = "0.1.0" +requires-python = ">=3.11,<3.12" +dependencies = ["torch==2.13.0", "setuptools==80.9.0", "numpy==1.26.4", "matplotlib==3.10.7", "psutil==7.1.3", "scikit-learn==1.7.2", "sentencepiece==0.2.1", "wandb==0.23.1", "rouge==1.0.1", "nltk==3.9.2", "einops==0.8.1"] + +[dependency-groups] +native = ["transformers==4.28.1", "datasets==2.14.7", "pyarrow==17.0.0", "accelerate==0.20.3", "huggingface-hub==0.36.0"] +modern = ["transformers==4.57.1", "datasets==3.6.0", "pyarrow==20.0.0", "accelerate==1.12.0", "huggingface-hub==0.36.0"] + +[tool.uv] +package = false +default-groups = ["native"] +conflicts = [[{group="native"}, {group="modern"}]] diff --git a/baselines/mezo/run_compatible.py b/baselines/mezo/run_compatible.py new file mode 100644 index 0000000..8d8c48b --- /dev/null +++ b/baselines/mezo/run_compatible.py @@ -0,0 +1,7 @@ +"""Modern task adapter calling pinned official numerical methods; not the original Trainer.""" +import sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / 'src')) +from experiments_codebase.runner import main +if __name__ == '__main__': + main(forced_method='mezo') diff --git a/baselines/mezo/uv.lock b/baselines/mezo/uv.lock new file mode 100644 index 0000000..34a5df1 --- /dev/null +++ b/baselines/mezo/uv.lock @@ -0,0 +1,1711 @@ +version = 1 +revision = 3 +requires-python = "==3.11.*" +resolution-markers = [ + "sys_platform == 'linux' and extra != 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native'", + "sys_platform == 'win32' and extra != 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native'", + "sys_platform == 'emscripten' and extra != 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32' and extra != 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native'", + "sys_platform == 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra != 'group-24-official-mezo-experiment-native'", + "sys_platform == 'win32' and extra == 'group-24-official-mezo-experiment-modern' and extra != 'group-24-official-mezo-experiment-native'", + "sys_platform == 'emscripten' and extra == 'group-24-official-mezo-experiment-modern' and extra != 'group-24-official-mezo-experiment-native'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32' and extra == 'group-24-official-mezo-experiment-modern' and extra != 'group-24-official-mezo-experiment-native'", + "sys_platform == 'linux' and extra != 'group-24-official-mezo-experiment-modern' and extra != 'group-24-official-mezo-experiment-native'", + "sys_platform != 'linux' and extra != 'group-24-official-mezo-experiment-modern' and extra != 'group-24-official-mezo-experiment-native'", +] +conflicts = [[ + { package = "official-mezo-experiment", group = "modern" }, + { package = "official-mezo-experiment", group = "native" }, +]] + +[[package]] +name = "accelerate" +version = "0.20.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyyaml" }, + { name = "torch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1a/fe/5a4a583065c410f5a3dcb9b4f202e6b9191d3e965f007c63c85ea135cd46/accelerate-0.20.3.tar.gz", hash = "sha256:79a896978c20dac270083d42bf033f4c9a80dcdd6b946f1ca92d8d6d0f0f5ba9", size = 213044, upload-time = "2023-06-08T16:16:36.887Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/10/d3/5382aa337d3e67214003a17b06bfc07cf0334356b4e8aaf3b12b0d38c83f/accelerate-0.20.3-py3-none-any.whl", hash = "sha256:147183e7a2215f7bd45a7af3b986a963daa8a61fa58b0912b9473049e011ad15", size = 227580, upload-time = "2023-06-08T16:16:34.728Z" }, +] + +[[package]] +name = "accelerate" +version = "1.12.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyyaml" }, + { name = "safetensors" }, + { name = "torch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4a/8e/ac2a9566747a93f8be36ee08532eb0160558b07630a081a6056a9f89bf1d/accelerate-1.12.0.tar.gz", hash = "sha256:70988c352feb481887077d2ab845125024b2a137a5090d6d7a32b57d03a45df6", size = 398399, upload-time = "2025-11-21T11:27:46.973Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/d2/c581486aa6c4fbd7394c23c47b83fa1a919d34194e16944241daf9e762dd/accelerate-1.12.0-py3-none-any.whl", hash = "sha256:3e2091cd341423207e2f084a6654b1efcd250dc326f2a37d6dde446e07cabb11", size = 380935, upload-time = "2025-11-21T11:27:44.522Z" }, +] + +[[package]] +name = "aiohappyeyeballs" +version = "2.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/f4/eec0465c2f67b2664688d0240b3212d5196fd89e741df67ddb81f8d35658/aiohappyeyeballs-2.7.1.tar.gz", hash = "sha256:065665c041c42a5938ed220bdcd7230f22527fbec085e1853d2402c8a3615d9d", size = 24757, upload-time = "2026-07-01T17:11:55.501Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/43/1947f06babed6b3f1d7f38b0c767f52df66bfb2bc10b468c4a7de9eceff2/aiohappyeyeballs-2.7.1-py3-none-any.whl", hash = "sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472", size = 15038, upload-time = "2026-07-01T17:11:54.055Z" }, +] + +[[package]] +name = "aiohttp" +version = "3.14.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohappyeyeballs" }, + { name = "aiosignal" }, + { name = "attrs" }, + { name = "frozenlist" }, + { name = "multidict" }, + { name = "propcache" }, + { name = "typing-extensions" }, + { name = "yarl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6c/4c/bdccd81e9ee225b69c60e7766c9a5b05364f118f4d383713b89a682d772d/aiohttp-3.14.5.tar.gz", hash = "sha256:5558a7f5a05af9ecf744af91e5baefc436f93c9333e656c27ec253f9a6bbe178", size = 8078052, upload-time = "2026-10-11T01:05:12.408Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d8/f3/8997f18890a92c79f77fcfbb4f78ca17c2d4ab109e9eb6d31b4e9de194a0/aiohttp-3.14.5-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:d51db97c96384fbfcaf8f4c65922183a68b94f891c3c10c862ef5f6df2adbb1f", size = 832358, upload-time = "2026-10-11T00:59:42.195Z" }, + { url = "https://files.pythonhosted.org/packages/8e/42/084651e9efb5cadb99265f786df60f2a7b353cead7bfd2c87003cb4867ad/aiohttp-3.14.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ae53924aa853a7a2ca20ed4142c7c6b56338e4d4cd999e2980075b9efc2e257a", size = 559636, upload-time = "2026-10-11T00:59:43.677Z" }, + { url = "https://files.pythonhosted.org/packages/3d/fe/92838944e601f0fe195fd3f3ada37e29fbee3d19bfd323fe15937ec79d36/aiohttp-3.14.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:a2c473a355f9239efcb72c92d5abfd8fcdb0cc78c8e9af607e72ca12dbb36593", size = 552588, upload-time = "2026-10-11T00:59:45.592Z" }, + { url = "https://files.pythonhosted.org/packages/8f/b8/dd9b95c5c20ceae1b47738e656bd79e9883e3117a9cc8b143901eb604e9a/aiohttp-3.14.5-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:32e8fa6644e541fcd7e02430588c7fc93b602c1778ea0bc345505db76b61cfb4", size = 1928224, upload-time = "2026-10-11T00:59:47.294Z" }, + { url = "https://files.pythonhosted.org/packages/c6/47/70010cd2ba8746968d53d433ff328c33f06a66c99da5f3de759c64a6b2eb/aiohttp-3.14.5-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:579f97d5120f2971876d2ddca2968135f6944d00c44c3a6590ad7d86ca9b403f", size = 1877674, upload-time = "2026-10-11T00:59:49.472Z" }, + { url = "https://files.pythonhosted.org/packages/c5/a1/b026f071dbd87f0bdba86b92d47e46f3899e3ad7143b6e0fe7e7887090b4/aiohttp-3.14.5-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:24409db442e2fb6e766bc7f3943851a8381dec3098140e43bb2e843b79e31b12", size = 1985850, upload-time = "2026-10-11T00:59:51.296Z" }, + { url = "https://files.pythonhosted.org/packages/36/d1/f7b6f6f8c3cb5a71b53baeddc2e70c224c28b12a23a55c42994c504019b7/aiohttp-3.14.5-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5e8f97c0488ffda3082766ac0f2c8150a9a58c4d05788330e479cfd449b37939", size = 2105471, upload-time = "2026-10-11T00:59:53.191Z" }, + { url = "https://files.pythonhosted.org/packages/42/74/2a2b22953de15c6c8a80debf26db3047e4e8a5a5db6dd7c2c6c01eec0605/aiohttp-3.14.5-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:50a195903119008fe9cc68710535eb37f556ffffd6a7759afe70a2c145587045", size = 1929915, upload-time = "2026-10-11T00:59:55.609Z" }, + { url = "https://files.pythonhosted.org/packages/33/ad/f80e8d33933d0eacd0217efa3b7fb32c9f48ed480ed0db53cf9948bf474f/aiohttp-3.14.5-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0133c3c3b54a0bf1e71fa5c1ad95c93f07fd54e24ef1fe182f5122e1573d2bf1", size = 1773832, upload-time = "2026-10-11T00:59:57.611Z" }, + { url = "https://files.pythonhosted.org/packages/04/a4/0273d239f3e3bb69438f209c64c82e1f98dc60d5db264795e41f7dd05dcb/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:c172db893e516e1358e65a95ee20b7ce7173963eefe318b6ab2a2220688b999e", size = 1901001, upload-time = "2026-10-11T01:00:00.605Z" }, + { url = "https://files.pythonhosted.org/packages/16/ed/7dd439d26c654645bc34ca3c9a822fc11c1c51801fed1cefdfe1cc41c1f6/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:f2a7966bda23dd85051f1661ce0ace38d6890e05ec6c357ecae9d2479cba377e", size = 1907218, upload-time = "2026-10-11T01:00:02.699Z" }, + { url = "https://files.pythonhosted.org/packages/32/dd/86249c3b8248562a17fd3e22ee0c164378d65766f01aceef62cf52783710/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:4887d130a7bbfed3a85493bb5a25e5b5b558d40c1d986dd16970d2bb26d63793", size = 1958650, upload-time = "2026-10-11T01:00:04.851Z" }, + { url = "https://files.pythonhosted.org/packages/bc/0b/ca4d53d68f683ce195807fd0aeb063bf6d1c6b39343fff234c9524e8d5a9/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:225c579c23b68b343cccea27a7e06e3bd8ec23a09c30b427eb3f1e4ca6239b20", size = 1760057, upload-time = "2026-10-11T01:00:06.978Z" }, + { url = "https://files.pythonhosted.org/packages/6b/42/005437ffd7fa56c2ce3347add40404b654a32754ce91f2e2a14b9e5ab2bc/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:ab52d8f1fc1b64821c1fbad64a647ed6203627004059a6d1ed4f0858a1499703", size = 1978081, upload-time = "2026-10-11T01:00:08.868Z" }, + { url = "https://files.pythonhosted.org/packages/03/71/3a5b66fe1b7b23d3c6524350817ed55de5feb7fbb4cccba7cbe044d118dd/aiohttp-3.14.5-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:cb131d775a1573c1aee66656bd78b023577bbdb6cb8349a07773bd4f73e68a6e", size = 1922954, upload-time = "2026-10-11T01:00:11.035Z" }, + { url = "https://files.pythonhosted.org/packages/69/84/d08a554f281d42fd7c6b2b6dd7738f3e3a7a9f657ddd87e11ca2091cdfe3/aiohttp-3.14.5-cp311-cp311-win32.whl", hash = "sha256:e87046c8ff77a8decdb6a41d8ab25824b47531b2da933aeab0c1e21c7acff329", size = 488101, upload-time = "2026-10-11T01:00:12.933Z" }, + { url = "https://files.pythonhosted.org/packages/0f/15/52b5e65f02b33686ae49f1518548ae4f5a7adaf31d9d3c54fa12a143137b/aiohttp-3.14.5-cp311-cp311-win_amd64.whl", hash = "sha256:6f275c11d1aa6d4c458e05a68be084efe3c55a113d99e3f46a318098e52948fc", size = 512575, upload-time = "2026-10-11T01:00:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/b0/b9/bb75012635f3defb0f7cbb7c4ae391e36bb9cb3fbdca3b9944e2ebebf743/aiohttp-3.14.5-cp311-cp311-win_arm64.whl", hash = "sha256:b032a0023eb41d768ce77d83210ab2a3c389bc0b09313273c7e1eca48c10a755", size = 493179, upload-time = "2026-10-11T01:00:16.961Z" }, + { url = "https://files.pythonhosted.org/packages/68/30/173960c42b05a6c59f7558e4b12a4b0d9ba376cf6aa9bde7f9e08a30ca8d/aiohttp-3.14.5-py3-none-any.whl", hash = "sha256:efc21a454892828368b11c2c780de0ff8bc991f73f6b99c6b66e56205470929b", size = 279517, upload-time = "2026-10-11T01:05:08.523Z" }, +] + +[[package]] +name = "aiosignal" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "frozenlist" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, +] + +[[package]] +name = "annotated-types" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/5f/56/a8120250d128bed162cd73c76d45f6ef9991f3e068f62a8ee060afa3104a/annotated_types-0.8.0.tar.gz", hash = "sha256:13b2beaad985e05e2d6407ee4c4f35590b11f8d693a258a561055cac8f64cab7", size = 15893, upload-time = "2026-07-23T20:16:13.995Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/99/91/8acff4f5e50511b911bbccb72b8628a49c68ce14148cd9f6431094859a90/annotated_types-0.8.0-py3-none-any.whl", hash = "sha256:f072f4d804ea359e4eaf198b1af7a8b0943881a87f31bb764f8bf219bb9419e0", size = 13427, upload-time = "2026-07-23T20:16:12.938Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "certifi" +version = "2026.10.23" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/22/67/6a0b94a7960d5e1b5eacd2fb529f3fccc47db4644f7f0a7cfdcfc3be578a/charset_normalizer-3.5.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:3d21b8b13c7592db2ac5e544a6d83187b995257472b0c9e8351b6d507ae37ed6", size = 370642, upload-time = "2026-09-30T04:35:06.91Z" }, + { url = "https://files.pythonhosted.org/packages/fb/94/01009e13b94041599004edf32e56e382c24e570f60f79bab8efe45cfe1eb/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d760fe2a4d7c3b226cb9026d6a842868d52a7901bd98420e1baf14e80da85cf5", size = 259280, upload-time = "2026-09-30T04:35:08.448Z" }, + { url = "https://files.pythonhosted.org/packages/66/85/3b5358f60a13210f0b67d3755c168ef758701b021e655d88d4da28554467/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c9790464842f85f437dbbb54417eda1e0e6bfc52dd8d22d6fd1c994b73b2dc74", size = 245335, upload-time = "2026-09-30T04:35:10.104Z" }, + { url = "https://files.pythonhosted.org/packages/74/75/77c1c479b09ecd751d1e767b251ea5c14d4d50ff757bf404afab2692f600/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:4685902cf26edf013ed7a3da0f426ebba7a00ebb9541386d835afbf002c11cab", size = 291707, upload-time = "2026-09-30T04:35:11.575Z" }, + { url = "https://files.pythonhosted.org/packages/0b/0d/363f78cacb70f58f15f4b083961bbd9d292f335d3f5c66fc4f1cfe69cb90/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4495c5002a7b28557e7e222e77e0b661183e432b7d6d2e788101e3f240e05b8c", size = 286747, upload-time = "2026-09-30T04:35:13.022Z" }, + { url = "https://files.pythonhosted.org/packages/e4/ed/cf505d3011ffceb12c2067a7a5d3cfe92b875d4d44bb0ff0d69375e2c184/charset_normalizer-3.5.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:211d5a3eb6af8f513b8d4ca19a8c1b7accab1b5f0d3175f9826b03c1a920dc1f", size = 269972, upload-time = "2026-09-30T04:35:14.606Z" }, + { url = "https://files.pythonhosted.org/packages/15/d8/f0a93a431d170e7ca681d4f6650fee3de934d18560e474e7267eb4b0f987/charset_normalizer-3.5.2-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:ef4fcbf3327382cd4c9f540babd61248208af7b93eec4de397b4d5f58a09e288", size = 269339, upload-time = "2026-09-30T04:35:16.087Z" }, + { url = "https://files.pythonhosted.org/packages/86/bd/9b2bd1c5b7af02462c9752d33994834ff972a96b4c483eefde9e594488e2/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:bd16aabe4a02a297c23417aa17ac6299dbd8c49f673bcd645b4929b11f5a4400", size = 261683, upload-time = "2026-09-30T04:35:17.488Z" }, + { url = "https://files.pythonhosted.org/packages/76/a5/cac540ab0fd61f3fec88ad3dbb64509e71424593d73cfdfff5ab3e4db279/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:fb9e68df06293761f9fe66ade60a9bc6d0f5e42b8acf2939a9158af86ab0e5bd", size = 248143, upload-time = "2026-09-30T04:35:18.849Z" }, + { url = "https://files.pythonhosted.org/packages/71/7a/ff467301deef2089fad87f72df9e000a26a78fec7acbb18e1999371b8369/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:59f63901b0031c3136cf64704dcb21de0bbae62ce2c9529bc39d27665463de37", size = 292358, upload-time = "2026-09-30T04:35:20.326Z" }, + { url = "https://files.pythonhosted.org/packages/ad/77/22d7e785d1e210afc2e2f58600dd1799d17a35665faf84383f002826c5f8/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:304d5463e65a35d7bb0850550e0780395395f6fcf452f04db7d5ca7cecc425ac", size = 268766, upload-time = "2026-09-30T04:35:21.72Z" }, + { url = "https://files.pythonhosted.org/packages/ae/91/e8e946267f1c2d9e2bd651726e2fbd2addf02c4d36cea5069e32ca9d7bb5/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9cf9b1a857e25c4baceeb3624e92a56df3668f398c4acba74e174d81fb4d1d3a", size = 287432, upload-time = "2026-09-30T04:35:23.273Z" }, + { url = "https://files.pythonhosted.org/packages/4e/88/7561d8a88d555e7df6623abe7c0070b4baf47549b9408783a2ae0a1a6cf7/charset_normalizer-3.5.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:114e4d0c92d618409ed82a99e22b5c5e768fe995f2973f78265f4524f49d4640", size = 272470, upload-time = "2026-09-30T04:35:24.655Z" }, + { url = "https://files.pythonhosted.org/packages/35/7e/578c702301ec036f01455f30744a08d2b42f6ab35b9b2d4bf8cae0ef2a80/charset_normalizer-3.5.2-cp311-cp311-win32.whl", hash = "sha256:2625388c6c754520c37abaf3b41eb34d1cc4a373f457898f08606c8e362b891d", size = 186688, upload-time = "2026-09-30T04:35:26.225Z" }, + { url = "https://files.pythonhosted.org/packages/e8/fc/fdf8cf52ff21cd5bf158f20978991cf985325842f74283eb6df26c8a39d8/charset_normalizer-3.5.2-cp311-cp311-win_amd64.whl", hash = "sha256:87e50a3e7cb90af586b6c5faf23e302a970415ac73bd7bd90a515a04b427ef96", size = 214932, upload-time = "2026-09-30T04:35:27.796Z" }, + { url = "https://files.pythonhosted.org/packages/97/66/3e45a506d8110b632541faf9a9470185aa9878f1ed44020f31346c1c5e5b/charset_normalizer-3.5.2-cp311-cp311-win_arm64.whl", hash = "sha256:254eb48b9fa5ee9898a3c445825a1f340fe53712a098904b39b0bddba8ea3cb1", size = 202828, upload-time = "2026-09-30T04:35:29.259Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" }, + { url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" }, + { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" }, + { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" }, + { url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" }, +] + +[[package]] +name = "click" +version = "8.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/37/edbf1b0707709013c0cf2e8317e03d97ed29bf4cac709fe328904ae92a38/click-8.5.1.tar.gz", hash = "sha256:9bbfada76703fd1d784b83eea012e3e8c6a001a876543ef104fa56aaaeb072b4", size = 399151, upload-time = "2026-11-06T17:37:01.021Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/31/7d/164b7ffc8624fe9efb4221bf9af485d5c1e41b9ae118045d2b6dc5457d8b/click-8.5.1-py3-none-any.whl", hash = "sha256:8bb5376d2006950386f8c6427613334a2acadc5f559cb80e638d00b4df957e37", size = 126163, upload-time = "2026-11-06T17:36:59.287Z" }, +] + +[[package]] +name = "cloudpickle" +version = "3.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/27/fb/576f067976d320f5f0114a8d9fa1215425441bb35627b1993e5afd8111e5/cloudpickle-3.1.2.tar.gz", hash = "sha256:7fda9eb655c9c230dab534f1983763de5835249750e85fbcef43aaa30a9a2414", size = 22330, upload-time = "2025-11-03T09:25:26.604Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/39/799be3f2f0f38cc727ee3b4f1445fe6d5e4133064ec2e4115069418a5bb6/cloudpickle-3.1.2-py3-none-any.whl", hash = "sha256:9acb47f6afd73f60dc1df93bb801b472f05ff42fa6c84167d25cb206be1fbf4a", size = 22228, upload-time = "2025-11-03T09:25:25.534Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "contourpy" +version = "1.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/58/01/1253e6698a07380cd31a736d248a3f2a50a7c88779a1813da27503cadc2a/contourpy-1.3.3.tar.gz", hash = "sha256:083e12155b210502d0bca491432bb04d56dc3432f95a979b429f2848c3dbe880", size = 13466174, upload-time = "2025-07-26T12:03:12.549Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/91/2e/c4390a31919d8a78b90e8ecf87cd4b4c4f05a5b48d05ec17db8e5404c6f4/contourpy-1.3.3-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:709a48ef9a690e1343202916450bc48b9e51c049b089c7f79a267b46cffcdaa1", size = 288773, upload-time = "2025-07-26T12:01:02.277Z" }, + { url = "https://files.pythonhosted.org/packages/0d/44/c4b0b6095fef4dc9c420e041799591e3b63e9619e3044f7f4f6c21c0ab24/contourpy-1.3.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:23416f38bfd74d5d28ab8429cc4d63fa67d5068bd711a85edb1c3fb0c3e2f381", size = 270149, upload-time = "2025-07-26T12:01:04.072Z" }, + { url = "https://files.pythonhosted.org/packages/30/2e/dd4ced42fefac8470661d7cb7e264808425e6c5d56d175291e93890cce09/contourpy-1.3.3-cp311-cp311-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:929ddf8c4c7f348e4c0a5a3a714b5c8542ffaa8c22954862a46ca1813b667ee7", size = 329222, upload-time = "2025-07-26T12:01:05.688Z" }, + { url = "https://files.pythonhosted.org/packages/f2/74/cc6ec2548e3d276c71389ea4802a774b7aa3558223b7bade3f25787fafc2/contourpy-1.3.3-cp311-cp311-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9e999574eddae35f1312c2b4b717b7885d4edd6cb46700e04f7f02db454e67c1", size = 377234, upload-time = "2025-07-26T12:01:07.054Z" }, + { url = "https://files.pythonhosted.org/packages/03/b3/64ef723029f917410f75c09da54254c5f9ea90ef89b143ccadb09df14c15/contourpy-1.3.3-cp311-cp311-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0bf67e0e3f482cb69779dd3061b534eb35ac9b17f163d851e2a547d56dba0a3a", size = 380555, upload-time = "2025-07-26T12:01:08.801Z" }, + { url = "https://files.pythonhosted.org/packages/5f/4b/6157f24ca425b89fe2eb7e7be642375711ab671135be21e6faa100f7448c/contourpy-1.3.3-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:51e79c1f7470158e838808d4a996fa9bac72c498e93d8ebe5119bc1e6becb0db", size = 355238, upload-time = "2025-07-26T12:01:10.319Z" }, + { url = "https://files.pythonhosted.org/packages/98/56/f914f0dd678480708a04cfd2206e7c382533249bc5001eb9f58aa693e200/contourpy-1.3.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:598c3aaece21c503615fd59c92a3598b428b2f01bfb4b8ca9c4edeecc2438620", size = 1326218, upload-time = "2025-07-26T12:01:12.659Z" }, + { url = "https://files.pythonhosted.org/packages/fb/d7/4a972334a0c971acd5172389671113ae82aa7527073980c38d5868ff1161/contourpy-1.3.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:322ab1c99b008dad206d406bb61d014cf0174df491ae9d9d0fac6a6fda4f977f", size = 1392867, upload-time = "2025-07-26T12:01:15.533Z" }, + { url = "https://files.pythonhosted.org/packages/75/3e/f2cc6cd56dc8cff46b1a56232eabc6feea52720083ea71ab15523daab796/contourpy-1.3.3-cp311-cp311-win32.whl", hash = "sha256:fd907ae12cd483cd83e414b12941c632a969171bf90fc937d0c9f268a31cafff", size = 183677, upload-time = "2025-07-26T12:01:17.088Z" }, + { url = "https://files.pythonhosted.org/packages/98/4b/9bd370b004b5c9d8045c6c33cf65bae018b27aca550a3f657cdc99acdbd8/contourpy-1.3.3-cp311-cp311-win_amd64.whl", hash = "sha256:3519428f6be58431c56581f1694ba8e50626f2dd550af225f82fb5f5814d2a42", size = 225234, upload-time = "2025-07-26T12:01:18.256Z" }, + { url = "https://files.pythonhosted.org/packages/d9/b6/71771e02c2e004450c12b1120a5f488cad2e4d5b590b1af8bad060360fe4/contourpy-1.3.3-cp311-cp311-win_arm64.whl", hash = "sha256:15ff10bfada4bf92ec8b31c62bf7c1834c244019b4a33095a68000d7075df470", size = 193123, upload-time = "2025-07-26T12:01:19.848Z" }, + { url = "https://files.pythonhosted.org/packages/a5/29/8dcfe16f0107943fa92388c23f6e05cff0ba58058c4c95b00280d4c75a14/contourpy-1.3.3-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:cd5dfcaeb10f7b7f9dc8941717c6c2ade08f587be2226222c12b25f0483ed497", size = 278809, upload-time = "2025-07-26T12:02:52.74Z" }, + { url = "https://files.pythonhosted.org/packages/85/a9/8b37ef4f7dafeb335daee3c8254645ef5725be4d9c6aa70b50ec46ef2f7e/contourpy-1.3.3-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:0c1fc238306b35f246d61a1d416a627348b5cf0648648a031e14bb8705fcdfe8", size = 261593, upload-time = "2025-07-26T12:02:54.037Z" }, + { url = "https://files.pythonhosted.org/packages/0a/59/ebfb8c677c75605cc27f7122c90313fd2f375ff3c8d19a1694bda74aaa63/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:70f9aad7de812d6541d29d2bbf8feb22ff7e1c299523db288004e3157ff4674e", size = 302202, upload-time = "2025-07-26T12:02:55.947Z" }, + { url = "https://files.pythonhosted.org/packages/3c/37/21972a15834d90bfbfb009b9d004779bd5a07a0ec0234e5ba8f64d5736f4/contourpy-1.3.3-pp311-pypy311_pp73-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5ed3657edf08512fc3fe81b510e35c2012fbd3081d2e26160f27ca28affec989", size = 329207, upload-time = "2025-07-26T12:02:57.468Z" }, + { url = "https://files.pythonhosted.org/packages/0c/58/bd257695f39d05594ca4ad60df5bcb7e32247f9951fd09a9b8edb82d1daa/contourpy-1.3.3-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:3d1a3799d62d45c18bafd41c5fa05120b96a28079f2393af559b843d1a966a77", size = 225315, upload-time = "2025-07-26T12:02:58.801Z" }, +] + +[[package]] +name = "cuda-bindings" +version = "13.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-pathfinder", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/09/74e159fbe67b081cca842871addce6d2b493f9bb48ce85124f023eb5f1c9/cuda_bindings-13.5.0-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:71c15ed97099a8ef416515d80ddd10770e0f6339234e16855a526d2896516631", size = 7434875, upload-time = "2026-11-05T12:05:50.666Z" }, + { url = "https://files.pythonhosted.org/packages/f6/0d/ca24317a31118b90fd60126aec5c0a92a191a7fdd39524032d43328b49b5/cuda_bindings-13.5.0-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:08b7e8d674c3266facb00453a7e34ea7d3ea965c2f594bb728f269f45f39fbe2", size = 8390178, upload-time = "2026-11-05T12:05:52.653Z" }, + { url = "https://files.pythonhosted.org/packages/a6/7b/455b204f07dcbac810bc48b558d3febff8adb81b6036efac315bd5a4aa33/cuda_bindings-13.5.0-cp311-cp311-win_amd64.whl", hash = "sha256:0d7a5d92be00b2a618fd7c62482f6c69584fd5ac498193b236600810d7ebaf74", size = 8097474, upload-time = "2026-11-05T12:05:59.207Z" }, + { url = "https://files.pythonhosted.org/packages/a0/70/9ab184a434f47dacedd47a49901c0be1a81080e8b57d1d3f0e5445bb1277/cuda_bindings-13.5.0-cp311-cp311-win_arm64.whl", hash = "sha256:4d850299e6ba1ca9caec78b3d87b6b7590ed1d6c9a404272798f40b1e19e3f24", size = 7010633, upload-time = "2026-11-05T12:06:00.913Z" }, +] + +[[package]] +name = "cuda-pathfinder" +version = "1.8.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/9e/08555797c979322def080814686417ea93f66d38f5c48ebab6867a85a21e/cuda_pathfinder-1.8.6-py3-none-any.whl", hash = "sha256:bf6b3b06323cf95a11d671818392da5da23ddbbb4dfc4b77ca10622783c25980", size = 62603, upload-time = "2026-11-05T21:22:51.229Z" }, +] + +[[package]] +name = "cuda-toolkit" +version = "13.0.3.0" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/c7/a79086a62c98befcdb8349656c6f114e2db3b8b2422f6e25c97a7f2a9a3c/cuda_toolkit-13.0.3.0-py2.py3-none-any.whl", hash = "sha256:d693caaa261214ddd7dbb60d68e71cbed884e68c2be7509778f3051da0b91c3f", size = 2512, upload-time = "2026-04-14T00:50:08.173Z" }, +] + +[package.optional-dependencies] +cublas = [ + { name = "nvidia-cublas", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +cudart = [ + { name = "nvidia-cuda-runtime", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +cufft = [ + { name = "nvidia-cufft", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +cufile = [ + { name = "nvidia-cufile", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +cupti = [ + { name = "nvidia-cuda-cupti", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +curand = [ + { name = "nvidia-curand", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +cusolver = [ + { name = "nvidia-cublas", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-cusolver", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-cusparse", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +cusparse = [ + { name = "nvidia-cusparse", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +nvjitlink = [ + { name = "nvidia-nvjitlink", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +nvrtc = [ + { name = "nvidia-cuda-nvrtc", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +nvtx = [ + { name = "nvidia-nvtx", marker = "(platform_machine != 'aarch64' and platform_machine != 'x86_64' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native') or (platform_machine == 'aarch64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (sys_platform != 'linux' and extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] + +[[package]] +name = "cycler" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, +] + +[[package]] +name = "datasets" +version = "2.14.7" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "aiohttp" }, + { name = "dill" }, + { name = "fsspec", extra = ["http"], marker = "extra == 'group-24-official-mezo-experiment-native'" }, + { name = "huggingface-hub" }, + { name = "multiprocess" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pyarrow", version = "17.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyarrow-hotfix" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "xxhash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/95/59/69ac07a49eeb587641f8a24eab5b5e406e308ed276e2a6de39d07a7cb6c3/datasets-2.14.7.tar.gz", hash = "sha256:394cf9b4ec0694b25945977b16ad5d18d5c15fb0e94141713eb8ead7452caf9e", size = 2181591, upload-time = "2023-11-15T08:12:38.218Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/00/23/80a2147a547cb2fd59eb92a13787c849b3efaefcea02a5c963dfc93f7c56/datasets-2.14.7-py3-none-any.whl", hash = "sha256:1a64041a7da4f4130f736fc371c1f528b8ddd208cebe156400f65719bdbba79d", size = 520442, upload-time = "2023-11-15T08:12:33.787Z" }, +] + +[[package]] +name = "datasets" +version = "3.6.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "dill" }, + { name = "filelock" }, + { name = "fsspec", extra = ["http"], marker = "extra == 'group-24-official-mezo-experiment-modern'" }, + { name = "huggingface-hub" }, + { name = "multiprocess" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pyarrow", version = "20.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "xxhash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1a/89/d3d6fef58a488f8569c82fd293ab7cbd4250244d67f425dcae64c63800ea/datasets-3.6.0.tar.gz", hash = "sha256:1b2bf43b19776e2787e181cfd329cb0ca1a358ea014780c3581e0f276375e041", size = 569336, upload-time = "2025-05-07T15:15:02.659Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/34/a08b0ee99715eaba118cbe19a71f7b5e2425c2718ef96007c325944a1152/datasets-3.6.0-py3-none-any.whl", hash = "sha256:25000c4a2c0873a710df127d08a202a06eab7bf42441a6bc278b499c2f72cd1b", size = 491546, upload-time = "2025-05-07T15:14:59.742Z" }, +] + +[[package]] +name = "dill" +version = "0.3.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c4/31/54dd222e02311c2dbc9e680d37cbd50f4494ce1ee9b04c69980e4ec26f38/dill-0.3.7.tar.gz", hash = "sha256:cc1c8b182eb3013e24bd475ff2e9295af86c1a38eb1aff128dac8962a9ce3c03", size = 183355, upload-time = "2023-07-22T22:18:46.449Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f5/3a/74a29b11cf2cdfcd6ba89c0cecd70b37cd1ba7b77978ce611eb7a146a832/dill-0.3.7-py3-none-any.whl", hash = "sha256:76b122c08ef4ce2eedcd4d1abd8e641114bfc6c2867f49f3c41facf65bf19f5e", size = 115254, upload-time = "2023-07-22T22:18:44.511Z" }, +] + +[[package]] +name = "einops" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e5/81/df4fbe24dff8ba3934af99044188e20a98ed441ad17a274539b74e82e126/einops-0.8.1.tar.gz", hash = "sha256:de5d960a7a761225532e0f1959e5315ebeafc0cd43394732f103ca44b9837e84", size = 54805, upload-time = "2025-02-09T03:17:00.434Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/62/9773de14fe6c45c23649e98b83231fffd7b9892b6cf863251dc2afa73643/einops-0.8.1-py3-none-any.whl", hash = "sha256:919387eb55330f5757c6bea9165c5ff5cfe63a642682ea788a6d472576d81737", size = 64359, upload-time = "2025-02-09T03:17:01.998Z" }, +] + +[[package]] +name = "filelock" +version = "4.2.10" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/cf/05bcdacabdc0aec7dc8e19d76281bd82325df62dae3b6430e9ba57397689/filelock-4.2.10.tar.gz", hash = "sha256:fcc3c0cb8bfe7f4b3bb0e231c04b15dbad068cb3c2515f343d8fde4dce93bd5d", size = 670595, upload-time = "2026-11-09T18:58:00.54Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/90/5d0096a325aa0f83ba7a3968bfb485b67e32c947bdf9cd0fcb4b485be718/filelock-4.2.10-py3-none-any.whl", hash = "sha256:9479aaeb4db20b5a53e3da28493edd24720b66b8a0b84030aa56ccdf243d6857", size = 218040, upload-time = "2026-11-09T18:57:59.088Z" }, +] + +[[package]] +name = "fonttools" +version = "4.68.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0c/b5/672312ae80ce8b8eb9779c56052a24c8f36652aa7293a1a420553bcf03e5/fonttools-4.68.0.tar.gz", hash = "sha256:73294e233070f71e2b3653b6bd8564af676d57f26d075761fb06d1ab2e4a7a5d", size = 3848583, upload-time = "2026-10-27T16:30:26.451Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/21/51/7c725115425be01aa0fac87eb38f8e8c8c04de80d49a99b08a74898b25ee/fonttools-4.68.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:362443ab355701d6fd26b10d022cd6c8456e1e248f80103c44cbe5ef0228f87f", size = 3135538, upload-time = "2026-10-27T16:28:02.169Z" }, + { url = "https://files.pythonhosted.org/packages/2e/d5/0a04cbde3e3e997d7bda216f77566bea2eb79018e4ca2adb13ce3c9a7206/fonttools-4.68.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:664dfa7a4869b3c827dfc2c38dbbb7a58d53e97933d1bd51ee6729792ee73d50", size = 2632853, upload-time = "2026-10-27T16:28:04.962Z" }, + { url = "https://files.pythonhosted.org/packages/d8/8c/aa4c7b38f4814d6bcb3378276bff802c9610a1227f1d24965a9f23f0a48c/fonttools-4.68.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:53f2387d7e3816763f30e08d14263be18e28ead53d4dc20a82f9280d0c99d88a", size = 5530571, upload-time = "2026-10-27T16:28:06.952Z" }, + { url = "https://files.pythonhosted.org/packages/00/01/e0f5b3d648ddd2eae35c4bcddcc2cffc059279e9d2cdb325bed10458f606/fonttools-4.68.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:4b9c89b5876f1a74b1341632dfaf4c4c2be565d76c060445df401ebe7a4ceefa", size = 5493829, upload-time = "2026-10-27T16:28:09.127Z" }, + { url = "https://files.pythonhosted.org/packages/ea/bb/9c5568659275c86e6eebb060d98e8ea77c56fb78ee77ea5654a057f72bde/fonttools-4.68.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:054a4d5de7e1f973ab9789e9ae3f20238774783ca9bf7ee0359aebae4de9400c", size = 5496373, upload-time = "2026-10-27T16:28:11.378Z" }, + { url = "https://files.pythonhosted.org/packages/b0/32/0a35ffd35bfc1b0a754563a45500e87d651e0f336cf006a25e0bc460ba2f/fonttools-4.68.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:b5a015b322275d3d745b06d5e69cf74ef4b1ce2dae02afbe4826cb186d8527a3", size = 5634196, upload-time = "2026-10-27T16:28:13.783Z" }, + { url = "https://files.pythonhosted.org/packages/93/76/3454e20f07dbe4b308b7bc99117292109bb7775a1b595ead768110144553/fonttools-4.68.0-cp311-cp311-win32.whl", hash = "sha256:bd5b047ed8f16b83d0344fef053668712ab9c88e2e46d8612ec41df83c5222e1", size = 1624232, upload-time = "2026-10-27T16:28:16.001Z" }, + { url = "https://files.pythonhosted.org/packages/46/87/4ba592099172764aa56e66919b0c3ddaf944c775433e806e36e165062095/fonttools-4.68.0-cp311-cp311-win_amd64.whl", hash = "sha256:35425bba603cf9d72c9f3c173ea6c98632164f3bdfb1ce1a3dcc928979c6ec6d", size = 1681821, upload-time = "2026-10-27T16:28:17.757Z" }, + { url = "https://files.pythonhosted.org/packages/e1/54/004f12709b21a56bb944fdca6d165b0d90cf9366143675dbc7bb46784ddd/fonttools-4.68.0-cp311-cp311-win_arm64.whl", hash = "sha256:04365b897c9ee29a048b6d4db74c75c38b70aa6d1074726fbdd7ea1a23aa8ed2", size = 1649151, upload-time = "2026-10-27T16:28:19.502Z" }, + { url = "https://files.pythonhosted.org/packages/35/74/4ea331ecc65ba05a58b1e4e8ccd604c8a15565f876dfbf93fc2a2ea2e22b/fonttools-4.68.0-py3-none-any.whl", hash = "sha256:d76f8fdcb6936f5e1045a0c9dd721a4bf11112e60d1e243bfa1d39f06a8b3104", size = 1248357, upload-time = "2026-10-27T16:30:24.389Z" }, +] + +[[package]] +name = "frozenlist" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/03/077f869d540370db12165c0aa51640a873fb661d8b315d1d4d67b284d7ac/frozenlist-1.8.0-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:09474e9831bc2b2199fad6da3c14c7b0fbdd377cce9d3d77131be28906cb7d84", size = 86912, upload-time = "2025-10-06T05:35:45.98Z" }, + { url = "https://files.pythonhosted.org/packages/df/b5/7610b6bd13e4ae77b96ba85abea1c8cb249683217ef09ac9e0ae93f25a91/frozenlist-1.8.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:17c883ab0ab67200b5f964d2b9ed6b00971917d5d8a92df149dc2c9779208ee9", size = 50046, upload-time = "2025-10-06T05:35:47.009Z" }, + { url = "https://files.pythonhosted.org/packages/6e/ef/0e8f1fe32f8a53dd26bdd1f9347efe0778b0fddf62789ea683f4cc7d787d/frozenlist-1.8.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:fa47e444b8ba08fffd1c18e8cdb9a75db1b6a27f17507522834ad13ed5922b93", size = 50119, upload-time = "2025-10-06T05:35:48.38Z" }, + { url = "https://files.pythonhosted.org/packages/11/b1/71a477adc7c36e5fb628245dfbdea2166feae310757dea848d02bd0689fd/frozenlist-1.8.0-cp311-cp311-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:2552f44204b744fba866e573be4c1f9048d6a324dfe14475103fd51613eb1d1f", size = 231067, upload-time = "2025-10-06T05:35:49.97Z" }, + { url = "https://files.pythonhosted.org/packages/45/7e/afe40eca3a2dc19b9904c0f5d7edfe82b5304cb831391edec0ac04af94c2/frozenlist-1.8.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:957e7c38f250991e48a9a73e6423db1bb9dd14e722a10f6b8bb8e16a0f55f695", size = 233160, upload-time = "2025-10-06T05:35:51.729Z" }, + { url = "https://files.pythonhosted.org/packages/a6/aa/7416eac95603ce428679d273255ffc7c998d4132cfae200103f164b108aa/frozenlist-1.8.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:8585e3bb2cdea02fc88ffa245069c36555557ad3609e83be0ec71f54fd4abb52", size = 228544, upload-time = "2025-10-06T05:35:53.246Z" }, + { url = "https://files.pythonhosted.org/packages/8b/3d/2a2d1f683d55ac7e3875e4263d28410063e738384d3adc294f5ff3d7105e/frozenlist-1.8.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:edee74874ce20a373d62dc28b0b18b93f645633c2943fd90ee9d898550770581", size = 243797, upload-time = "2025-10-06T05:35:54.497Z" }, + { url = "https://files.pythonhosted.org/packages/78/1e/2d5565b589e580c296d3bb54da08d206e797d941a83a6fdea42af23be79c/frozenlist-1.8.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:c9a63152fe95756b85f31186bddf42e4c02c6321207fd6601a1c89ebac4fe567", size = 247923, upload-time = "2025-10-06T05:35:55.861Z" }, + { url = "https://files.pythonhosted.org/packages/aa/c3/65872fcf1d326a7f101ad4d86285c403c87be7d832b7470b77f6d2ed5ddc/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b6db2185db9be0a04fecf2f241c70b63b1a242e2805be291855078f2b404dd6b", size = 230886, upload-time = "2025-10-06T05:35:57.399Z" }, + { url = "https://files.pythonhosted.org/packages/a0/76/ac9ced601d62f6956f03cc794f9e04c81719509f85255abf96e2510f4265/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:f4be2e3d8bc8aabd566f8d5b8ba7ecc09249d74ba3c9ed52e54dc23a293f0b92", size = 245731, upload-time = "2025-10-06T05:35:58.563Z" }, + { url = "https://files.pythonhosted.org/packages/b9/49/ecccb5f2598daf0b4a1415497eba4c33c1e8ce07495eb07d2860c731b8d5/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:c8d1634419f39ea6f5c427ea2f90ca85126b54b50837f31497f3bf38266e853d", size = 241544, upload-time = "2025-10-06T05:35:59.719Z" }, + { url = "https://files.pythonhosted.org/packages/53/4b/ddf24113323c0bbcc54cb38c8b8916f1da7165e07b8e24a717b4a12cbf10/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:1a7fa382a4a223773ed64242dbe1c9c326ec09457e6b8428efb4118c685c3dfd", size = 241806, upload-time = "2025-10-06T05:36:00.959Z" }, + { url = "https://files.pythonhosted.org/packages/a7/fb/9b9a084d73c67175484ba2789a59f8eebebd0827d186a8102005ce41e1ba/frozenlist-1.8.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:11847b53d722050808926e785df837353bd4d75f1d494377e59b23594d834967", size = 229382, upload-time = "2025-10-06T05:36:02.22Z" }, + { url = "https://files.pythonhosted.org/packages/95/a3/c8fb25aac55bf5e12dae5c5aa6a98f85d436c1dc658f21c3ac73f9fa95e5/frozenlist-1.8.0-cp311-cp311-win32.whl", hash = "sha256:27c6e8077956cf73eadd514be8fb04d77fc946a7fe9f7fe167648b0b9085cc25", size = 39647, upload-time = "2025-10-06T05:36:03.409Z" }, + { url = "https://files.pythonhosted.org/packages/0a/f5/603d0d6a02cfd4c8f2a095a54672b3cf967ad688a60fb9faf04fc4887f65/frozenlist-1.8.0-cp311-cp311-win_amd64.whl", hash = "sha256:ac913f8403b36a2c8610bbfd25b8013488533e71e62b4b4adce9c86c8cea905b", size = 44064, upload-time = "2025-10-06T05:36:04.368Z" }, + { url = "https://files.pythonhosted.org/packages/5d/16/c2c9ab44e181f043a86f9a8f84d5124b62dbcb3a02c0977ec72b9ac1d3e0/frozenlist-1.8.0-cp311-cp311-win_arm64.whl", hash = "sha256:d4d3214a0f8394edfa3e303136d0575eece0745ff2b47bd2cb2e66dd92d4351a", size = 39937, upload-time = "2025-10-06T05:36:05.669Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, +] + +[[package]] +name = "fsspec" +version = "2023.10.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a4/f7/16ec1f92523165d10301cfa8cb83df0356dbe615d4ca5ed611a16f53e09a/fsspec-2023.10.0.tar.gz", hash = "sha256:330c66757591df346ad3091a53bd907e15348c2ba17d63fd54f5c39c4457d2a5", size = 165452, upload-time = "2023-10-21T17:37:04.636Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e8/f6/3eccfb530aac90ad1301c582da228e4763f19e719ac8200752a4841b0b2d/fsspec-2023.10.0-py3-none-any.whl", hash = "sha256:346a8f024efeb749d2a5fca7ba8854474b1ff9af7c3faaf636a4548781136529", size = 166384, upload-time = "2023-10-21T17:37:02.632Z" }, +] + +[package.optional-dependencies] +http = [ + { name = "aiohttp" }, + { name = "requests" }, +] + +[[package]] +name = "gitdb" +version = "4.0.12" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "smmap" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/72/94/63b0fc47eb32792c7ba1fe1b694daec9a63620db1e313033d18140c2320a/gitdb-4.0.12.tar.gz", hash = "sha256:5ef71f855d191a3326fcfbc0d5da835f26b13fbcba60c32c21091c349ffdb571", size = 394684, upload-time = "2025-01-02T07:20:46.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/61/5c78b91c3143ed5c14207f463aecfc8f9dbb5092fb2869baf37c273b2705/gitdb-4.0.12-py3-none-any.whl", hash = "sha256:67073e15955400952c6565cc3e707c554a4eea2e428946f7a4c162fab9bd9bcf", size = 62794, upload-time = "2025-01-02T07:20:43.624Z" }, +] + +[[package]] +name = "gitpython" +version = "3.2.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "gitdb" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/c0/ff/fee293f1ec3e1b64db6eb270e00964f29c086d769201474cedb8d1608930/gitpython-3.2.1.tar.gz", hash = "sha256:0f1229ec5c057bdabdeeda8bda4f17bda679ab33dbccc00f24e6a480553c8613", size = 241688, upload-time = "2026-10-14T12:20:20.589Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6b/50/2a923c4dc02522ff9567f07c67ed1deca6d5fa9474f4708168b8088dfa37/gitpython-3.2.1-py3-none-any.whl", hash = "sha256:d66b0832aa8755c1a84892937282df0befb16c97e5a64aeebd68be9c5e323f53", size = 231548, upload-time = "2026-10-14T12:20:18.844Z" }, +] + +[[package]] +name = "hf-xet" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" }, + { url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" }, + { url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" }, + { url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" }, + { url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" }, +] + +[[package]] +name = "huggingface-hub" +version = "0.36.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "filelock" }, + { name = "fsspec" }, + { name = "hf-xet", marker = "platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/63/4910c5fa9128fdadf6a9c5ac138e8b1b6cee4ca44bf7915bbfbce4e355ee/huggingface_hub-0.36.0.tar.gz", hash = "sha256:47b3f0e2539c39bf5cde015d63b72ec49baff67b6931c3d97f3f84532e2b8d25", size = 463358, upload-time = "2025-10-23T12:12:01.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/bd/1a875e0d592d447cbc02805fd3fe0f497714d6a2583f59d14fa9ebad96eb/huggingface_hub-0.36.0-py3-none-any.whl", hash = "sha256:7bcc9ad17d5b3f07b57c78e79d527102d08313caa278a641993acddcb894548d", size = 566094, upload-time = "2025-10-23T12:11:59.557Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "joblib" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cloudpickle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d5/1d/537ab090f302b838943a1b56497dd53059b9a9b46a074936470173a2e207/joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03", size = 327903, upload-time = "2026-08-31T09:39:04.122Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115, upload-time = "2026-08-31T09:39:02.298Z" }, +] + +[[package]] +name = "kiwisolver" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea041ef5bba3ed21a003522fa088834b069b1909981f30/kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a", size = 104395, upload-time = "2026-08-28T10:28:27.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/94/7b/2de6908edc668427c149af5f93112e931f87e1fa4cab80bac32c5844dccc/kiwisolver-1.5.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:b3d78f7bb2b9d9a30345be1474b9aaa8685430b54afb51ba3639b5c6c11e9ed6", size = 123364, upload-time = "2026-08-28T10:25:04.359Z" }, + { url = "https://files.pythonhosted.org/packages/8a/24/e70914415c77c97be7e22c80a0740869cb7428768cc380fdcdf6703e7084/kiwisolver-1.5.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:5025e36fb4fb275cef0a4e30dbb11cb4ae61d1c83deb90189cb5d7e4cafd6b55", size = 66558, upload-time = "2026-08-28T10:25:05.506Z" }, + { url = "https://files.pythonhosted.org/packages/e8/2b/8b08b11833db4d475b8ef1f36174f8d8a7abd31bedd7e794be78e8814b48/kiwisolver-1.5.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:dc1a26b8e53395a01c2c611e58602fa47461f136fba7cd5542e6db6d64be1839", size = 64071, upload-time = "2026-08-28T10:25:06.7Z" }, + { url = "https://files.pythonhosted.org/packages/89/00/05c2d0369ac322d22d5c05f84b5c4a6856fa6207fbae42869108a28f0383/kiwisolver-1.5.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:95a02752aa032eef4aed01cda6d9b687c669bd0396bf4519eef8bba22a286720", size = 1438206, upload-time = "2026-08-28T10:25:08.254Z" }, + { url = "https://files.pythonhosted.org/packages/c0/05/c941a139f27438c1910d630fdc3ccfdab7c8407c72052299ead12ece086e/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:719a35fa1156db3640555f95ebb94f60a444e64d1c69626b0edef5df78eba225", size = 1248975, upload-time = "2026-08-28T10:25:10.053Z" }, + { url = "https://files.pythonhosted.org/packages/58/a1/2669ee5512e39b9d4de25faacaedf788c957f93730c5f7c63993ec4f5933/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:febcce10f2bcdbb80b4ea919238a6a4ac13dbc4c7cadbe8d5d75c3682f8b5404", size = 1266301, upload-time = "2026-08-28T10:25:11.754Z" }, + { url = "https://files.pythonhosted.org/packages/28/b8/353f52f2c7f861a9e90cd2e8f90f85b3ad03060835f823e08298d094c463/kiwisolver-1.5.1-cp311-cp311-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:1d852545c4d0e35a72728d072cbaa59e2fa7dd84bdf01e068d670dd0ceb58eb6", size = 1319708, upload-time = "2026-08-28T10:25:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/21/0e/14b83200eadc2c1d63b76bac01c1813bf072aecf567429f303e00b70258e/kiwisolver-1.5.1-cp311-cp311-manylinux_2_39_riscv64.whl", hash = "sha256:2e10ae1bba1899188b33557c10d73affcc12033edd18adddb57d209039976a4c", size = 971720, upload-time = "2026-08-28T10:25:14.934Z" }, + { url = "https://files.pythonhosted.org/packages/86/91/9d43d84d23b1cbff72a142d387ead1ea03db0cba8ff86ed5335addad3cc9/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:b69602970994a2ed8bbfa78c2f0394a7435226c6040489702d9f0a0ad0c07052", size = 2200119, upload-time = "2026-08-28T10:25:16.636Z" }, + { url = "https://files.pythonhosted.org/packages/ff/7c/f2bd9616f27ffb5e17cecc0baa5d0bbcee7e55aeddc0ccc871d69e2fc3ee/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:d50de98e8d807dc31822fff96f50293163a62418eb65487a21b42713d72ed0b7", size = 2295005, upload-time = "2026-08-28T10:25:18.374Z" }, + { url = "https://files.pythonhosted.org/packages/ba/17/ee671b72bf8f46a08379d4392c65582541759a542428197562f2898294ad/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3221f78211074f561c44ca42eac0619828171bec15a2c4cf6f7747d07df76e8e", size = 1960982, upload-time = "2026-08-28T10:25:19.893Z" }, + { url = "https://files.pythonhosted.org/packages/2e/f7/0e26b4c05bee3bdb0f048dfa305e4fe701999ea17b51e9c616ef91035bbe/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:0ba9527afc80ae3d7814ed98b6572d02bf85eaf48065678342c5f0c6dab7a8c7", size = 2464918, upload-time = "2026-08-28T10:25:21.65Z" }, + { url = "https://files.pythonhosted.org/packages/ae/62/6eb431133d30ce656ac1e5ff72fac70dd34d54c3984f4011b9ac8bf77d54/kiwisolver-1.5.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e12dfea7f5fc2a34a9080efbf79c4c44eb380ec5b9c6fea09407e08f0d1e941d", size = 2270967, upload-time = "2026-08-28T10:25:23.643Z" }, + { url = "https://files.pythonhosted.org/packages/bf/9f/6f9e489c188200e6fb3193935501894811e8c97577c8ffe9033589bf3521/kiwisolver-1.5.1-cp311-cp311-win_amd64.whl", hash = "sha256:1a7587dc335f2c0f5bd577fd0540bd16c66006bdb60f759a1059f025e6c4f071", size = 70744, upload-time = "2026-08-28T10:25:25.061Z" }, + { url = "https://files.pythonhosted.org/packages/c6/6d/dfc430d1d43957061599adea3f08ea982bb6f4ab601a8c974bedcf2ba850/kiwisolver-1.5.1-cp311-cp311-win_arm64.whl", hash = "sha256:e4e4523d6f336708d732516e6cfca7796cf3d96c9474eb5aecf6165f2f1fefc3", size = 68404, upload-time = "2026-08-28T10:25:26.186Z" }, + { url = "https://files.pythonhosted.org/packages/b5/1d/59ba570b1774e95e97fde3a0981b2e22118a7a495f73bf74cedc538566a0/kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:416ba7ff9f233b7036689bb5a3783537e838ad483f63558d2a800f75afe738b1", size = 59450, upload-time = "2026-08-28T10:28:20.383Z" }, + { url = "https://files.pythonhosted.org/packages/22/98/a6849f04dc18b5400e8b98affa2cd8fd86ed583085f036e57b32e571f4fa/kiwisolver-1.5.1-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:8af9b142ad719ae3a911ebf616bc4b78b32bbab84d6a40d3ad2f129670509957", size = 57400, upload-time = "2026-08-28T10:28:21.632Z" }, + { url = "https://files.pythonhosted.org/packages/f4/ce/a7dc71353dd06a4cbe02222773f52d4a28c81e5a452a75797f8ed113dc99/kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:5daa1f19e097050b9c4d9a78fcc9263cb96c9dfae08037ddc1b7c4ad1889f2a2", size = 79891, upload-time = "2026-08-28T10:28:22.936Z" }, + { url = "https://files.pythonhosted.org/packages/10/b1/d61c61a84ff85d1a36a99df2c152b59ffedb1d356c598902aba44abcdb60/kiwisolver-1.5.1-pp311-pypy311_pp73-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cdaeeb6c350106df6bf9d873395973e5f066a9713200b72cd64f55d0a3eafab6", size = 77605, upload-time = "2026-08-28T10:28:24.322Z" }, + { url = "https://files.pythonhosted.org/packages/d3/52/5aef56f21a460a6e43ab3cdfc7697d59d7b87deb0ec97a0f7b91aa4a521b/kiwisolver-1.5.1-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:17851e5dad4484be0cbccbde3b15331deae036de9aebd45eed964487802b172f", size = 98465, upload-time = "2026-08-28T10:28:25.696Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/55/18dbb4778b30ada5ce071608503cc3edc9e14e13d868c17a6d178fc30f7a/markupsafe-3.0.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9e25feb9e330b63edb0278a0acdf85e50d0cb0fbf49c3084abbe4e24ae195346", size = 11520, upload-time = "2026-10-02T23:04:36.299Z" }, + { url = "https://files.pythonhosted.org/packages/6c/14/0b05f79b4733e264a18d08fe08fa1df7347630ff32a6cb82180d9dccec55/markupsafe-3.0.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7d3391b2188d18737cb2fa147028b1096236eaa7e156446c650a489fa2cadc91", size = 12063, upload-time = "2026-10-02T23:04:37.291Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3a/63ba10b6c1463216b3e4df669a9f0e5a3b0c3071557d2e8229e3968c79fb/markupsafe-3.0.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849dd2bb0e5e4ab2b71c7191726a4a8d5aa8a610daa584728cbee0b710ddc4ef", size = 24321, upload-time = "2026-10-02T23:04:38.262Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/5f015261b76ad633d187ef6f388b413aedd64a8773c4df59e530a0be5525/markupsafe-3.0.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:befb4158af32106b9a93db8d6d1d1cbbd418c0d5aca0cabb7b1780abf0c89169", size = 28845, upload-time = "2026-10-02T23:04:39.295Z" }, + { url = "https://files.pythonhosted.org/packages/33/cf/26e594b26be40c2f1fec63ccf8a8b99d0335a5b2cbe84835c7d82a994375/markupsafe-3.0.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:71f88e749ea29f67f21f3b36433c1dc54c7729ed2a6d9e2da2e0d9e0d7b224eb", size = 24701, upload-time = "2026-10-02T23:04:40.348Z" }, + { url = "https://files.pythonhosted.org/packages/81/a5/a513b76c139a3915b43404324e55c0b7979ae4f0d39eb6f075b0282e90a8/markupsafe-3.0.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6da83a088f8ef93b2d483a8232a4dbf4d69d3d8496b568a03c56becac43e1808", size = 22961, upload-time = "2026-10-02T23:04:41.372Z" }, + { url = "https://files.pythonhosted.org/packages/46/cf/4c66192c100b4542bcbe392ae06696b670f66927be3ac38a213234778ff9/markupsafe-3.0.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:8f0fac8b13d14bb06c68195f849371924ae53dd7b1c00fed24650f704383b692", size = 21920, upload-time = "2026-10-02T23:04:42.429Z" }, + { url = "https://files.pythonhosted.org/packages/cb/17/ac3662678bfbad649893117ada2ba44dc30bf56884e84f13154a792b10f1/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:4a7cdc2a420ca01058182da4253329764d4bfa055564d1eced90e6ba1e8b1d3d", size = 23726, upload-time = "2026-10-02T23:04:43.531Z" }, + { url = "https://files.pythonhosted.org/packages/f7/af/fe47cee339180a69ebca3c57fb3483d0f5cbd1e8337d1871fb1d9c1aebee/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:83b3944fea42a8400edf92fd1770fb8d0d4f7de651353bd2d8525a92dba69a21", size = 22539, upload-time = "2026-10-02T23:04:44.618Z" }, + { url = "https://files.pythonhosted.org/packages/12/32/d55440ba140442800e02d799c9cb5ab597bf6ebdb1177b5ea39a11f797bd/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:8138eb83940ec7299024d92d4dee45f601b9e6c5ffde9d25f4e35e326203c707", size = 23963, upload-time = "2026-10-02T23:04:45.656Z" }, + { url = "https://files.pythonhosted.org/packages/50/9d/9c86042cb364c2ad4c971e6d1247929effd25f714cd7ee11b05e6316445b/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:811d02d5122171c1941357efd8f9bf4ffe907b7f0a1a4e729a880e4be3f46e3e", size = 21506, upload-time = "2026-10-02T23:04:46.671Z" }, + { url = "https://files.pythonhosted.org/packages/75/ef/5b824f03ba40c3b3652b6272d083d2fc4fcdd440de519a3a39ba2c3e7262/markupsafe-3.0.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:50b5bedc9ed8a94fc8857a42ef4f84a81ea88f8d4f05dc8705fb23ee6d8dcca7", size = 22955, upload-time = "2026-10-02T23:04:47.698Z" }, + { url = "https://files.pythonhosted.org/packages/1e/e8/44cfcb5ea40e5e43cec7793ef90704ed0c475280839076c4345757eb8e59/markupsafe-3.0.4-cp311-cp311-win32.whl", hash = "sha256:2e5a7cd7fdd14fcb1ae5d7d8bf23d24fbd1daefd1fbca2580132e1ea75f098b5", size = 14094, upload-time = "2026-10-02T23:04:48.788Z" }, + { url = "https://files.pythonhosted.org/packages/91/89/f2b509f7bf79352e40117824c1070dbeafd4df67031d3fa98165a3134228/markupsafe-3.0.4-cp311-cp311-win_amd64.whl", hash = "sha256:fdb4ca07ab75ffadab4a8b135ad59cdbb3156b99310f3d565370da74a15d6bd3", size = 14328, upload-time = "2026-10-02T23:04:49.801Z" }, + { url = "https://files.pythonhosted.org/packages/2b/5a/ccf22672a0f64dc682306e288f0dabcb06c7a201f3bb6e6cbf86d9e8ad03/markupsafe-3.0.4-cp311-cp311-win_arm64.whl", hash = "sha256:569d65055d367e3dcdf30c3f41119467b73d9ee9faf332bdf40402644f5ac08e", size = 14188, upload-time = "2026-10-02T23:04:50.847Z" }, +] + +[[package]] +name = "matplotlib" +version = "3.10.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "contourpy" }, + { name = "cycler" }, + { name = "fonttools" }, + { name = "kiwisolver" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "pyparsing" }, + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ae/e2/d2d5295be2f44c678ebaf3544ba32d20c1f9ef08c49fe47f496180e1db15/matplotlib-3.10.7.tar.gz", hash = "sha256:a06ba7e2a2ef9131c79c49e63dad355d2d878413a0376c1727c8b9335ff731c7", size = 34804865, upload-time = "2025-10-09T00:28:00.669Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/bc/0fb489005669127ec13f51be0c6adc074d7cf191075dab1da9fe3b7a3cfc/matplotlib-3.10.7-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:53b492410a6cd66c7a471de6c924f6ede976e963c0f3097a3b7abfadddc67d0a", size = 8257507, upload-time = "2025-10-09T00:26:19.073Z" }, + { url = "https://files.pythonhosted.org/packages/e2/6a/d42588ad895279ff6708924645b5d2ed54a7fb2dc045c8a804e955aeace1/matplotlib-3.10.7-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d9749313deb729f08207718d29c86246beb2ea3fdba753595b55901dee5d2fd6", size = 8119565, upload-time = "2025-10-09T00:26:21.023Z" }, + { url = "https://files.pythonhosted.org/packages/10/b7/4aa196155b4d846bd749cf82aa5a4c300cf55a8b5e0dfa5b722a63c0f8a0/matplotlib-3.10.7-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2222c7ba2cbde7fe63032769f6eb7e83ab3227f47d997a8453377709b7fe3a5a", size = 8692668, upload-time = "2025-10-09T00:26:22.967Z" }, + { url = "https://files.pythonhosted.org/packages/e6/e7/664d2b97016f46683a02d854d730cfcf54ff92c1dafa424beebef50f831d/matplotlib-3.10.7-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e91f61a064c92c307c5a9dc8c05dc9f8a68f0a3be199d9a002a0622e13f874a1", size = 9521051, upload-time = "2025-10-09T00:26:25.041Z" }, + { url = "https://files.pythonhosted.org/packages/a8/a3/37aef1404efa615f49b5758a5e0261c16dd88f389bc1861e722620e4a754/matplotlib-3.10.7-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:6f1851eab59ca082c95df5a500106bad73672645625e04538b3ad0f69471ffcc", size = 9576878, upload-time = "2025-10-09T00:26:27.478Z" }, + { url = "https://files.pythonhosted.org/packages/33/cd/b145f9797126f3f809d177ca378de57c45413c5099c5990de2658760594a/matplotlib-3.10.7-cp311-cp311-win_amd64.whl", hash = "sha256:6516ce375109c60ceec579e699524e9d504cd7578506f01150f7a6bc174a775e", size = 8115142, upload-time = "2025-10-09T00:26:29.774Z" }, + { url = "https://files.pythonhosted.org/packages/2e/39/63bca9d2b78455ed497fcf51a9c71df200a11048f48249038f06447fa947/matplotlib-3.10.7-cp311-cp311-win_arm64.whl", hash = "sha256:b172db79759f5f9bc13ef1c3ef8b9ee7b37b0247f987fbbbdaa15e4f87fd46a9", size = 7992439, upload-time = "2025-10-09T00:26:40.32Z" }, + { url = "https://files.pythonhosted.org/packages/58/8f/76d5dc21ac64a49e5498d7f0472c0781dae442dd266a67458baec38288ec/matplotlib-3.10.7-pp311-pypy311_pp73-macosx_10_15_x86_64.whl", hash = "sha256:15112bcbaef211bd663fa935ec33313b948e214454d949b723998a43357b17b0", size = 8252283, upload-time = "2025-10-09T00:27:54.739Z" }, + { url = "https://files.pythonhosted.org/packages/27/0d/9c5d4c2317feb31d819e38c9f947c942f42ebd4eb935fc6fd3518a11eaa7/matplotlib-3.10.7-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:d2a959c640cdeecdd2ec3136e8ea0441da59bcaf58d67e9c590740addba2cb68", size = 8116733, upload-time = "2025-10-09T00:27:56.406Z" }, + { url = "https://files.pythonhosted.org/packages/9a/cc/3fe688ff1355010937713164caacf9ed443675ac48a997bab6ed23b3f7c0/matplotlib-3.10.7-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3886e47f64611046bc1db523a09dd0a0a6bed6081e6f90e13806dd1d1d1b5e91", size = 8693919, upload-time = "2025-10-09T00:27:58.41Z" }, +] + +[[package]] +name = "mpmath" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, +] + +[[package]] +name = "multidict" +version = "7.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/6b/29ef8e752f5854dcc267ded0652c475bec99b86f255957a0d4fcad657b18/multidict-7.2.1.tar.gz", hash = "sha256:e8af3e6f1bdbc31fd762b094133b478b89988eaebc63cbe82b1d9e3bbd15cede", size = 369994, upload-time = "2026-10-24T20:41:35.457Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/24/4347a7502ad47cb05a1b8d4e219514b4f0b1e38d4e4734c053c20328949f/multidict-7.2.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:fd24c4425fdb8e822601335602375c6d0cb020f7a368e1d5842eb7925a9c8748", size = 173141, upload-time = "2026-10-24T20:40:02.481Z" }, + { url = "https://files.pythonhosted.org/packages/8d/f2/2a8fcfe4c2c435101f9227b7f7ea81d786ffef993cadd2394e6926020ca9/multidict-7.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cecb2c778f00a65c6ca01410dd194d0e797a9eebb7c6dea0db87718719f293c7", size = 97197, upload-time = "2026-10-24T20:40:06.534Z" }, + { url = "https://files.pythonhosted.org/packages/7a/57/39be4ac4fa9c20e3af7dd7e89adf7dd404b4547fb4453c5c96082e197b9c/multidict-7.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:0d852d3d9638f852158d7de7200dd77f7ff8d77fc8f3d396032f3d847883f631", size = 104843, upload-time = "2026-10-24T20:40:05.829Z" }, + { url = "https://files.pythonhosted.org/packages/63/da/6a5c78daa34e458ced17573b7527395c4c39ebb253220274382d361a1493/multidict-7.2.1-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:76a4f5132b8dc29eb3c768ee9b47e132a1d24fbc2e9259854c01af9beaff1d49", size = 490713, upload-time = "2026-10-24T20:40:41.715Z" }, + { url = "https://files.pythonhosted.org/packages/8a/75/b8252bc6411f7f4b9649b83e143789b7bc1dda44f656b09ce74f894ca027/multidict-7.2.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:295a15ccb8cfde9351dd6062b80af4e839460636b3c46813b4aa443905ded86a", size = 504189, upload-time = "2026-10-24T20:40:04.042Z" }, + { url = "https://files.pythonhosted.org/packages/c0/45/38e8191d0a7c7b56015dfc4c2910b731aa719c5ad3f369b2357567f03434/multidict-7.2.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:987f65f6c9321402bc7012f6c6d09ba501b88ddb1640f5b0b4a19f2caafe24a5", size = 465834, upload-time = "2026-10-24T20:40:08.058Z" }, + { url = "https://files.pythonhosted.org/packages/9f/55/378869573886f7efcac24d2c698938dadf973e0da40b812c8b0df847fc46/multidict-7.2.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:36b868758fb11cfa748c788b793994e73660abec90f83c780a678539c2c468bf", size = 522423, upload-time = "2026-10-24T20:40:07.427Z" }, + { url = "https://files.pythonhosted.org/packages/af/c5/8936fe02c11196994ac05c4876ad62336a66ef353ea2d1a2ca3adce71678/multidict-7.2.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:5b944091cfa7da4f7a9bd2587569cd90c94b89ec4721f8e87fe62504f2432b67", size = 544512, upload-time = "2026-10-24T20:40:43.362Z" }, + { url = "https://files.pythonhosted.org/packages/d0/38/b8403d97ae5273002fa664c3c440c5cc186082fa0ba20fcc93885d13a686/multidict-7.2.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3b7542fad2706595c1b1853b46f2c3c4ae5cc5a6252b7225f294d607a29e1bdf", size = 510054, upload-time = "2026-10-24T20:40:05.525Z" }, + { url = "https://files.pythonhosted.org/packages/18/5d/473e1436ea8577cdfb42371c0507a244d51f8d8ef08bea0f9e6e63906478/multidict-7.2.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:363e5db93fc3f65f3218a79fe108d217b9d264181a4e993c77552bfe275d0393", size = 452816, upload-time = "2026-10-24T20:40:09.49Z" }, + { url = "https://files.pythonhosted.org/packages/1e/b7/67376e6821fb28c21de1fb37731efd2e3a6a523bdefc4af6997bd043da7a/multidict-7.2.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:5deadf03fb4a7842696d551f9f9a06dd4445bb43ca06b5f9736e4e1885561333", size = 490712, upload-time = "2026-10-24T20:40:09.097Z" }, + { url = "https://files.pythonhosted.org/packages/1a/89/5144d8b36f133109ff36408089a475b9a3a3c1840176a39a9a8fb67a0000/multidict-7.2.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:0ec95a02f9f08246cc7f1d85ac425e4d5c233fd3f098f5be1b2cca16aa690186", size = 462856, upload-time = "2026-10-24T20:40:44.771Z" }, + { url = "https://files.pythonhosted.org/packages/ff/7f/38310388c4c5e351dfc419a04e4c7a26cde14b0e1019bc72bbd1b0d95613/multidict-7.2.1-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:3d6fce7cc4ef63d9a7633cbae43e737798412805a4c3ba876cdf472dc6ff9c51", size = 490108, upload-time = "2026-10-24T20:40:06.965Z" }, + { url = "https://files.pythonhosted.org/packages/ce/0d/94162600e5bbf24bf33398f3b33ae2f78211375313dbdaaf1513b2554a66/multidict-7.2.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:37b161535e92776788957a165fcf38a80b33c1efde7b18cab287db4e4574df78", size = 508935, upload-time = "2026-10-24T20:40:10.882Z" }, + { url = "https://files.pythonhosted.org/packages/1d/40/a0cae932493346cb0d442ffa380e65491fdae8df338d8cdf2f39695c0947/multidict-7.2.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:e47d058c2db95010f5d2e1f6037acebdfb0e2fa4507650e1041437985c91db38", size = 447620, upload-time = "2026-10-24T20:40:10.548Z" }, + { url = "https://files.pythonhosted.org/packages/5e/a5/6ec5cd1c15574aca277ab08920f7e78a6a1e1c15912bfaf59b48683230f7/multidict-7.2.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:7238f7135481926d52a94c18a8cca633a9e72c1cbfccd5796548298a479b0656", size = 523896, upload-time = "2026-10-24T20:40:46.258Z" }, + { url = "https://files.pythonhosted.org/packages/ae/60/d164a2583548561f7e596f13bbd1c3492ea33a77d499d3ceaa2acf76d850/multidict-7.2.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:c10ac5e3e76837180656079008f71add8339b00c3c26314092bcd1e8e449049f", size = 502961, upload-time = "2026-10-24T20:40:08.732Z" }, + { url = "https://files.pythonhosted.org/packages/30/6b/474aee537e0c87210ce8f4fd21558b461e8a8e74c79440de036022a9eeda/multidict-7.2.1-cp311-cp311-win32.whl", hash = "sha256:2b4d0c4e13d329ffee73d46128e32dd3b4aeb2f9c6ac9c8a89eb28d3b82dcea8", size = 84159, upload-time = "2026-10-24T20:40:12.222Z" }, + { url = "https://files.pythonhosted.org/packages/1f/02/41d769148f32c9bd535fd0ddd946c4e42f38acaddf7899f3bf49d9e67703/multidict-7.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:a789e3d27fc5665cc0477f10a35a89383313e4c9cf8b5e6af7ea71f039cdcc0e", size = 94895, upload-time = "2026-10-24T20:40:12.036Z" }, + { url = "https://files.pythonhosted.org/packages/23/be/e04fcf29542d0db25cdec79acbe5662481c3ba6b760353c393f9c46156f2/multidict-7.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:2022bd3194968a027f64ed16f9779e62e71a823a9df3971a7328c1d45dfeb9ab", size = 92384, upload-time = "2026-10-24T20:40:47.827Z" }, + { url = "https://files.pythonhosted.org/packages/9d/96/1aaad0e5df33f1f5af21775c411349c0234a6edd581ea403bc81919a6eab/multidict-7.2.1-py3-none-any.whl", hash = "sha256:08ea94663d9e7c25d14d78222f7aee906c472d4837766bec62477c38f6e419dc", size = 28145, upload-time = "2026-10-24T20:40:59.159Z" }, +] + +[[package]] +name = "multiprocess" +version = "0.70.15" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dill" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/68/e0/a77ca96e772e13c828fa52f3ad370d413bef194aeaf78b7c6611870ad815/multiprocess-0.70.15.tar.gz", hash = "sha256:f20eed3036c0ef477b07a4177cf7c1ba520d9a2677870a4f47fe026f0cd6787e", size = 1894495, upload-time = "2023-07-23T05:03:29.314Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/35/a8/36d8d7b3e46b377800d8dec47891cdf05842d1a2366909ae4a0c89fbc5e6/multiprocess-0.70.15-py310-none-any.whl", hash = "sha256:7dd58e33235e83cf09d625e55cffd7b0f0eede7ee9223cdd666a87624f60c21a", size = 134824, upload-time = "2023-07-23T05:03:21.182Z" }, + { url = "https://files.pythonhosted.org/packages/e7/41/96ac938770ba6e7d5ae1d8c9cafebac54b413549042c6260f0d0a6ec6622/multiprocess-0.70.15-py311-none-any.whl", hash = "sha256:134f89053d82c9ed3b73edd3a2531eb791e602d4f4156fc92a79259590bd9670", size = 135392, upload-time = "2023-07-23T05:03:22.885Z" }, + { url = "https://files.pythonhosted.org/packages/ca/3f/8354ce12fd13bd5c5bb4722261a10ca1d6e2eb7c1c08fa3d8a4e9dc98f44/multiprocess-0.70.15-py37-none-any.whl", hash = "sha256:f7d4a1629bccb433114c3b4885f69eccc200994323c80f6feee73b0edc9199c5", size = 116276, upload-time = "2023-07-23T05:03:24.718Z" }, + { url = "https://files.pythonhosted.org/packages/c2/a6/c5cb599d917904878f220a4dbdfdcc4ef291dd3956c35b3b0dc6fc42fb6d/multiprocess-0.70.15-py38-none-any.whl", hash = "sha256:bee9afba476c91f9ebee7beeee0601face9eff67d822e893f9a893725fbd6316", size = 132626, upload-time = "2023-07-23T05:03:25.895Z" }, + { url = "https://files.pythonhosted.org/packages/c6/c9/820b5ab056f4ada76fbe05bd481a948f287957d6cbfd59e2dd2618b408c1/multiprocess-0.70.15-py39-none-any.whl", hash = "sha256:3e0953f5d52b4c76f1c973eaf8214554d146f2be5decb48e928e55c7a2d19338", size = 133349, upload-time = "2023-07-23T05:03:27.022Z" }, +] + +[[package]] +name = "networkx" +version = "3.6.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/6a/51/63fe664f3908c97be9d2e4f1158eb633317598cfa6e1fc14af5383f17512/networkx-3.6.1.tar.gz", hash = "sha256:26b7c357accc0c8cde558ad486283728b65b6a95d85ee1cd66bafab4c8168509", size = 2517025, upload-time = "2025-12-08T17:02:39.908Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9e/c9/b2622292ea83fbb4ec318f5b9ab867d0a28ab43c5717bb85b0a5f6b3b0a4/networkx-3.6.1-py3-none-any.whl", hash = "sha256:d47fbf302e7d9cbbb9e2555a0d267983d2aa476bac30e90dfbe5669bd57f3762", size = 2068504, upload-time = "2025-12-08T17:02:38.159Z" }, +] + +[[package]] +name = "nltk" +version = "3.9.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "joblib" }, + { name = "regex" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f9/76/3a5e4312c19a028770f86fd7c058cf9f4ec4321c6cf7526bab998a5b683c/nltk-3.9.2.tar.gz", hash = "sha256:0f409e9b069ca4177c1903c3e843eef90c7e92992fa4931ae607da6de49e1419", size = 2887629, upload-time = "2025-10-01T07:19:23.764Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/60/90/81ac364ef94209c100e12579629dc92bf7a709a84af32f8c551b02c07e94/nltk-3.9.2-py3-none-any.whl", hash = "sha256:1e209d2b3009110635ed9709a67a1a3e33a10f799490fa71cf4bec218c11c88a", size = 1513404, upload-time = "2025-10-01T07:19:21.648Z" }, +] + +[[package]] +name = "numpy" +version = "1.26.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/65/6e/09db70a523a96d25e115e71cc56a6f9031e7b8cd166c1ac8438307c14058/numpy-1.26.4.tar.gz", hash = "sha256:2a02aba9ed12e4ac4eb3ea9421c420301a0c6460d9830d74a9df87efa4912010", size = 15786129, upload-time = "2024-02-06T00:26:44.495Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/11/57/baae43d14fe163fa0e4c47f307b6b2511ab8d7d30177c491960504252053/numpy-1.26.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:4c66707fabe114439db9068ee468c26bbdf909cac0fb58686a42a24de1760c71", size = 20630554, upload-time = "2024-02-05T23:51:50.149Z" }, + { url = "https://files.pythonhosted.org/packages/1a/2e/151484f49fd03944c4a3ad9c418ed193cfd02724e138ac8a9505d056c582/numpy-1.26.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:edd8b5fe47dab091176d21bb6de568acdd906d1887a4584a15a9a96a1dca06ef", size = 13997127, upload-time = "2024-02-05T23:52:15.314Z" }, + { url = "https://files.pythonhosted.org/packages/79/ae/7e5b85136806f9dadf4878bf73cf223fe5c2636818ba3ab1c585d0403164/numpy-1.26.4-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7ab55401287bfec946ced39700c053796e7cc0e3acbef09993a9ad2adba6ca6e", size = 14222994, upload-time = "2024-02-05T23:52:47.569Z" }, + { url = "https://files.pythonhosted.org/packages/3a/d0/edc009c27b406c4f9cbc79274d6e46d634d139075492ad055e3d68445925/numpy-1.26.4-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:666dbfb6ec68962c033a450943ded891bed2d54e6755e35e5835d63f4f6931d5", size = 18252005, upload-time = "2024-02-05T23:53:15.637Z" }, + { url = "https://files.pythonhosted.org/packages/09/bf/2b1aaf8f525f2923ff6cfcf134ae5e750e279ac65ebf386c75a0cf6da06a/numpy-1.26.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:96ff0b2ad353d8f990b63294c8986f1ec3cb19d749234014f4e7eb0112ceba5a", size = 13885297, upload-time = "2024-02-05T23:53:42.16Z" }, + { url = "https://files.pythonhosted.org/packages/df/a0/4e0f14d847cfc2a633a1c8621d00724f3206cfeddeb66d35698c4e2cf3d2/numpy-1.26.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:60dedbb91afcbfdc9bc0b1f3f402804070deed7392c23eb7a7f07fa857868e8a", size = 18093567, upload-time = "2024-02-05T23:54:11.696Z" }, + { url = "https://files.pythonhosted.org/packages/d2/b7/a734c733286e10a7f1a8ad1ae8c90f2d33bf604a96548e0a4a3a6739b468/numpy-1.26.4-cp311-cp311-win32.whl", hash = "sha256:1af303d6b2210eb850fcf03064d364652b7120803a0b872f5211f5234b399f20", size = 5968812, upload-time = "2024-02-05T23:54:26.453Z" }, + { url = "https://files.pythonhosted.org/packages/3f/6b/5610004206cf7f8e7ad91c5a85a8c71b2f2f8051a0c0c4d5916b76d6cbb2/numpy-1.26.4-cp311-cp311-win_amd64.whl", hash = "sha256:cd25bcecc4974d09257ffcd1f098ee778f7834c3ad767fe5db785be9a4aa9cb2", size = 15811913, upload-time = "2024-02-05T23:54:53.933Z" }, +] + +[[package]] +name = "nvidia-cublas" +version = "13.1.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cuda-nvrtc", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" }, + { url = "https://files.pythonhosted.org/packages/3b/cd/154ca20c38269e05eff77c1464e6c1da89f50a6390b565e9d82e06bc11e1/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:37936a16db8fe4ac1f065c2139360608a543a09275cb1a1af612e08cfa065436", size = 423138758, upload-time = "2026-04-08T18:46:58.655Z" }, + { url = "https://files.pythonhosted.org/packages/45/9e/2f562daf80eb8f7a685fb7bea4fda71f6048e4f359d6fdd1b6e70206cb2f/nvidia_cublas-13.1.1.3-py3-none-win_amd64.whl", hash = "sha256:b6cdce694e47ff6aadf0a69df1cab6628d696f5ff56e8d16af50309d855fa20f", size = 404358158, upload-time = "2026-04-08T18:47:26.987Z" }, +] + +[[package]] +name = "nvidia-cuda-cupti" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/2a/80353b103fc20ce05ef51e928daed4b6015db4aaa9162ed0997090fe2250/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_aarch64.whl", hash = "sha256:796bd679890ee55fb14a94629b698b6db54bcfd833d391d5e94017dd9d7d3151", size = 10310827, upload-time = "2025-09-04T08:26:42.012Z" }, + { url = "https://files.pythonhosted.org/packages/33/6d/737d164b4837a9bbd202f5ae3078975f0525a55730fe871d8ed4e3b952b0/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_x86_64.whl", hash = "sha256:4eb01c08e859bf924d222250d2e8f8b8ff6d3db4721288cf35d14252a4d933c8", size = 10715597, upload-time = "2025-09-04T08:26:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/ad/df/b74b10025c1205695c5676373f2edd3e87a7202cc62ead0dfbc373b0f6ea/nvidia_cuda_cupti-13.0.85-py3-none-win_amd64.whl", hash = "sha256:683f58d301548deeefcb8f6fac1b8d907691b9d8b18eccab417f51e362102f00", size = 7736776, upload-time = "2025-09-04T08:38:08.38Z" }, +] + +[[package]] +name = "nvidia-cuda-nvrtc" +version = "13.0.88" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/68/483a78f5e8f31b08fb1bb671559968c0ca3a065ac7acabfc7cee55214fd6/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:ad9b6d2ead2435f11cbb6868809d2adeeee302e9bb94bcf0539c7a40d80e8575", size = 90215200, upload-time = "2025-09-04T08:28:44.204Z" }, + { url = "https://files.pythonhosted.org/packages/b7/dc/6bb80850e0b7edd6588d560758f17e0550893a1feaf436807d64d2da040f/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d27f20a0ca67a4bb34268a5e951033496c5b74870b868bacd046b1b8e0c3267b", size = 43015449, upload-time = "2025-09-04T08:28:20.239Z" }, + { url = "https://files.pythonhosted.org/packages/4a/af/345fedb9f4c76c84ab4fa445b36bd4048a4d9db60e6bc76b4f913ff4b852/nvidia_cuda_nvrtc-13.0.88-py3-none-win_amd64.whl", hash = "sha256:6bcd4e7f8e205cbe644f5a98f2f799bef9556fefc89dd786e79a16312ce49872", size = 76807835, upload-time = "2025-09-04T08:39:15.274Z" }, +] + +[[package]] +name = "nvidia-cuda-runtime" +version = "13.0.96" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/4f/17d7b9b8e285199c58ce28e31b5c5bbaa4d8271af06a89b6405258245de2/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ef9bcbe90493a2b9d810e43d249adb3d02e98dd30200d86607d8d02687c43f55", size = 2261060, upload-time = "2025-10-09T08:55:15.78Z" }, + { url = "https://files.pythonhosted.org/packages/2e/24/d1558f3b68b1d26e706813b1d10aa1d785e4698c425af8db8edc3dced472/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7f82250d7782aa23b6cfe765ecc7db554bd3c2870c43f3d1821f1d18aebf0548", size = 2243632, upload-time = "2025-10-09T08:55:36.117Z" }, + { url = "https://files.pythonhosted.org/packages/b7/94/6b867483bec07da24ffa32736c79fabb94ef3a7af4d787a9d4a974868576/nvidia_cuda_runtime-13.0.96-py3-none-win_amd64.whl", hash = "sha256:f79298c8a098cec150a597c8eba58ecdab96e3bdc4b9bc4f9983635031740492", size = 2927037, upload-time = "2025-10-09T09:04:23.782Z" }, +] + +[[package]] +name = "nvidia-cudnn-cu13" +version = "9.20.0.48" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cublas", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/c5/83384d846b2fd17c44bd499b36c75a45ed4f095fbbb2252294e89cea5c5c/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:e31454ae00094b0c55319d9d15b6fa2fc50a9e1c0f5c8c80fb75258234e731e1", size = 444574296, upload-time = "2026-03-09T19:28:27.751Z" }, + { url = "https://files.pythonhosted.org/packages/6e/5e/edb9c0ae051602c3ccaffe424256463636d639e27d7f302dde9975ef9e7a/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0c45dd8eeb50b603f07995b1b300c62ffe6a1980482b82b3bcf94a4ca9d49304", size = 366173588, upload-time = "2026-03-09T19:29:34.474Z" }, + { url = "https://files.pythonhosted.org/packages/78/39/21507455b1bca8b5702a9e9fc6ce73735f216f558dac2c9ede58e4d456b8/nvidia_cudnn_cu13-9.20.0.48-py3-none-win_amd64.whl", hash = "sha256:af8139732b99c0118be65ea5aac97f0d46018f8c552889e49d2fb0c6261a4a24", size = 350712614, upload-time = "2026-03-09T19:31:11.398Z" }, +] + +[[package]] +name = "nvidia-cufft" +version = "12.0.0.61" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, + { url = "https://files.pythonhosted.org/packages/a8/2f/7b57e29836ea8714f81e9898409196f47d772d5ddedddf1592eadb8ab743/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6c44f692dce8fd5ffd3e3df134b6cdb9c2f72d99cf40b62c32dde45eea9ddad3", size = 214085489, upload-time = "2025-09-04T08:31:56.044Z" }, + { url = "https://files.pythonhosted.org/packages/85/b2/f8af21a2ed1beed337a6a02c5a28aeb85441f4d578ec3d529543c775ea4b/nvidia_cufft-12.0.0.61-py3-none-win_amd64.whl", hash = "sha256:2abce5b39d2f5ae12730fb7e5db6696533e36c26e2d3e8fd1750bdd2853364eb", size = 213342123, upload-time = "2025-09-04T08:40:51.145Z" }, +] + +[[package]] +name = "nvidia-cufile" +version = "1.15.1.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/70/4f193de89a48b71714e74602ee14d04e4019ad36a5a9f20c425776e72cd6/nvidia_cufile-1.15.1.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:08a3ecefae5a01c7f5117351c64f17c7c62efa5fffdbe24fc7d298da19cd0b44", size = 1223672, upload-time = "2025-09-04T08:32:22.779Z" }, + { url = "https://files.pythonhosted.org/packages/ab/73/cc4a14c9813a8a0d509417cf5f4bdaba76e924d58beb9864f5a7baceefbf/nvidia_cufile-1.15.1.6-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:bdc0deedc61f548bddf7733bdc216456c2fdb101d020e1ab4b88d232d5e2f6d1", size = 1136992, upload-time = "2025-09-04T08:32:14.119Z" }, +] + +[[package]] +name = "nvidia-curand" +version = "10.4.0.35" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/72/7c2ae24fb6b63a32e6ae5d241cc65263ea18d08802aaae087d9f013335a2/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:133df5a7509c3e292aaa2b477afd0194f06ce4ea24d714d616ff36439cee349a", size = 61962106, upload-time = "2025-08-04T10:21:41.128Z" }, + { url = "https://files.pythonhosted.org/packages/a5/9f/be0a41ca4a4917abf5cb9ae0daff1a6060cc5de950aec0396de9f3b52bc5/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:1aee33a5da6e1db083fe2b90082def8915f30f3248d5896bcec36a579d941bfc", size = 59544258, upload-time = "2025-08-04T10:22:03.992Z" }, + { url = "https://files.pythonhosted.org/packages/99/27/72103153b1ffc00e09fdc40ac970235343dcd1ea8bd762e84d2d73219ffa/nvidia_curand-10.4.0.35-py3-none-win_amd64.whl", hash = "sha256:65b1710aa6961d326b411e314b374290904c5ddf41dc3f766ebc3f1d7d4ca69f", size = 55242481, upload-time = "2025-08-04T10:30:41.831Z" }, +] + +[[package]] +name = "nvidia-cusolver" +version = "12.0.4.66" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cublas", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-cusparse", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, + { url = "https://files.pythonhosted.org/packages/5f/67/cba3777620cdacb99102da4042883709c41c709f4b6323c10781a9c3aa34/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0a759da5dea5c0ea10fd307de75cdeb59e7ea4fcb8add0924859b944babf1112", size = 200941980, upload-time = "2025-09-04T08:33:22.767Z" }, + { url = "https://files.pythonhosted.org/packages/99/ef/332a0101260ca78a1daef046bf0b06199e8ed4dac1d2aa698289c358169c/nvidia_cusolver-12.0.4.66-py3-none-win_amd64.whl", hash = "sha256:16515bd33a8e76bb54d024cfa068fa68d30e80fc34b9e1090813ea9362e0cb65", size = 193551444, upload-time = "2025-09-04T08:41:46.813Z" }, +] + +[[package]] +name = "nvidia-cusparse" +version = "12.6.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-nvjitlink", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, + { url = "https://files.pythonhosted.org/packages/fa/18/623c77619c31d62efd55302939756966f3ecc8d724a14dab2b75f1508850/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2b3c89c88d01ee0e477cb7f82ef60a11a4bcd57b6b87c33f789350b59759360b", size = 145942937, upload-time = "2025-09-04T08:33:58.029Z" }, + { url = "https://files.pythonhosted.org/packages/02/b0/b043d6f3480f102f885cf87fc3ffd3edcb5e23b855025a50e2ef4d059185/nvidia_cusparse-12.6.3.3-py3-none-win_amd64.whl", hash = "sha256:cbcf42feb737bd7ec15b4c0a63e62351886bd3f975027b8815d7f720a2b5ea79", size = 143783033, upload-time = "2025-09-04T08:42:12.391Z" }, +] + +[[package]] +name = "nvidia-cusparselt-cu13" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/e1/cdc1797eadf82d3a9a575a19b33fdc871a97edbec42c00b5b5e914f4aff4/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:4dca476c50bf4780d46cd0bfbd82e2bc10a08e4fef7950917ce8d7578d22a23f", size = 221051344, upload-time = "2025-09-05T18:49:51.289Z" }, + { url = "https://files.pythonhosted.org/packages/34/7d/2661f2fb3ac4302f3a246f5fc030213ac60c1fe0bce84f9783dbd831dbb7/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:786ce87568c303fadb5afcc7102d454cd3040d75f6f8626f5db460d1871f4dd0", size = 170148586, upload-time = "2025-09-05T18:50:50.248Z" }, + { url = "https://files.pythonhosted.org/packages/31/83/f3647ce26916c94a6ca4ff1810623e2c405cff2dea6e78d29516b2514df9/nvidia_cusparselt_cu13-0.8.1-py3-none-win_amd64.whl", hash = "sha256:dccbd362f91a7b9024d1f55ee9f548ac065027ff15d8c8b0db889ab3a8f31215", size = 156885108, upload-time = "2025-09-05T18:51:35.958Z" }, +] + +[[package]] +name = "nvidia-nccl-cu13" +version = "2.29.7" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/0d/daf50d44177ee0cbc7ff0a0c91eb5ff676c82be42f9a970bc7597f440c3a/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_aarch64.whl", hash = "sha256:674a12383e3c38a1bcccae7d4f3633b37852230b6047883cb2f4c2d1b36d9bf5", size = 206014712, upload-time = "2026-03-03T05:34:20.843Z" }, + { url = "https://files.pythonhosted.org/packages/67/f4/58e4e91b6919367c7aafb8e36fce9aad1a3047e536bf7e2fd560927d3a4c/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:edd81538446786ec3b73972543e53bb43bcaf0bfc8ef76cb679fcc390ffe136d", size = 205976000, upload-time = "2026-03-03T05:36:24.472Z" }, +] + +[[package]] +name = "nvidia-nvjitlink" +version = "13.5.37" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cc/1f/2321702b8d60b4b4dd18b957f61612dbac9cb1c07e940cf6582106b7c8b8/nvidia_nvjitlink-13.5.37-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:280d7cb9649704145f074b8dbde500de04ce02d0872e066e20a83c17bcaa93eb", size = 46642491, upload-time = "2026-11-04T23:33:31.696Z" }, + { url = "https://files.pythonhosted.org/packages/24/15/dd228f798cd01d7aeaf19d872b2b20f9aeafc1a7d8b6bfaa878b30b8d6f7/nvidia_nvjitlink-13.5.37-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:893f6f9a55b2720ed94913b5ba3332e972da8c78dfa2863d0244403dbd528ffc", size = 45253761, upload-time = "2026-11-04T23:33:22.854Z" }, + { url = "https://files.pythonhosted.org/packages/a7/53/c43398492e8374880d5e01c23c4dac33ba0c3bd03515d6ecc574254c0967/nvidia_nvjitlink-13.5.37-py3-none-win_amd64.whl", hash = "sha256:4465d4e8f2212118220b580c82523c5654f93a62906bd51d29d79bdfc12376c1", size = 41467665, upload-time = "2026-11-04T23:38:44.689Z" }, + { url = "https://files.pythonhosted.org/packages/d7/4a/1ff9ab7d0c961a1b5539f8291c881bea82adbbf8ba40a9e81f9c9b3a8d5d/nvidia_nvjitlink-13.5.37-py3-none-win_arm64.whl", hash = "sha256:eb30348ae64c525180a280025dd12a089c3e2e1dc4e19cdd58f68c6edc622404", size = 38552904, upload-time = "2026-11-04T23:43:27.658Z" }, +] + +[[package]] +name = "nvidia-nvshmem-cu13" +version = "3.4.5" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/0f/05cc9c720236dcd2db9c1ab97fff629e96821be2e63103569da0c9b72f19/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dc2a197f38e5d0376ad52cd1a2a3617d3cdc150fd5966f4aee9bcebb1d68fe9", size = 60215947, upload-time = "2025-09-06T00:32:20.022Z" }, + { url = "https://files.pythonhosted.org/packages/3c/35/a9bf80a609e74e3b000fef598933235c908fcefcef9026042b8e6dfde2a9/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:290f0a2ee94c9f3687a02502f3b9299a9f9fe826e6d0287ee18482e78d495b80", size = 60412546, upload-time = "2025-09-06T00:32:41.564Z" }, +] + +[[package]] +name = "nvidia-nvtx" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c2/f3/d86c845465a2723ad7e1e5c36dcd75ddb82898b3f53be47ebd429fb2fa5d/nvidia_nvtx-13.0.85-py3-none-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4936d1d6780fbe68db454f5e72a42ff64d1fd6397df9f363ae786930fd5c1cd4", size = 148047, upload-time = "2025-09-04T08:29:01.761Z" }, + { url = "https://files.pythonhosted.org/packages/a8/64/3708a90d1ebe202ffdeb7185f878a3c84d15c2b2c31858da2ce0583e2def/nvidia_nvtx-13.0.85-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb7780edb6b14107373c835bf8b72e7a178bac7367e23da7acb108f973f157a6", size = 148878, upload-time = "2025-09-04T08:28:53.627Z" }, + { url = "https://files.pythonhosted.org/packages/d2/50/0e2220f8620a177de994211186ffc5bfa9f2ce1e1282797f8f90096f9f88/nvidia_nvtx-13.0.85-py3-none-win_amd64.whl", hash = "sha256:d66ea44254dd3c6eacc300047af6e1288d2269dd072b417e0adffbf479e18519", size = 137066, upload-time = "2025-09-04T08:39:25.649Z" }, +] + +[[package]] +name = "official-mezo-experiment" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "einops" }, + { name = "matplotlib" }, + { name = "nltk" }, + { name = "numpy" }, + { name = "psutil" }, + { name = "rouge" }, + { name = "scikit-learn" }, + { name = "sentencepiece" }, + { name = "setuptools" }, + { name = "torch" }, + { name = "wandb" }, +] + +[package.dev-dependencies] +modern = [ + { name = "accelerate", version = "1.12.0", source = { registry = "https://pypi.org/simple" } }, + { name = "datasets", version = "3.6.0", source = { registry = "https://pypi.org/simple" } }, + { name = "huggingface-hub" }, + { name = "pyarrow", version = "20.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "transformers", version = "4.57.1", source = { registry = "https://pypi.org/simple" } }, +] +native = [ + { name = "accelerate", version = "0.20.3", source = { registry = "https://pypi.org/simple" } }, + { name = "datasets", version = "2.14.7", source = { registry = "https://pypi.org/simple" } }, + { name = "huggingface-hub" }, + { name = "pyarrow", version = "17.0.0", source = { registry = "https://pypi.org/simple" } }, + { name = "transformers", version = "4.28.1", source = { registry = "https://pypi.org/simple" } }, +] + +[package.metadata] +requires-dist = [ + { name = "einops", specifier = "==0.8.1" }, + { name = "matplotlib", specifier = "==3.10.7" }, + { name = "nltk", specifier = "==3.9.2" }, + { name = "numpy", specifier = "==1.26.4" }, + { name = "psutil", specifier = "==7.1.3" }, + { name = "rouge", specifier = "==1.0.1" }, + { name = "scikit-learn", specifier = "==1.7.2" }, + { name = "sentencepiece", specifier = "==0.2.1" }, + { name = "setuptools", specifier = "==80.9.0" }, + { name = "torch", specifier = "==2.13.0" }, + { name = "wandb", specifier = "==0.23.1" }, +] + +[package.metadata.requires-dev] +modern = [ + { name = "accelerate", specifier = "==1.12.0" }, + { name = "datasets", specifier = "==3.6.0" }, + { name = "huggingface-hub", specifier = "==0.36.0" }, + { name = "pyarrow", specifier = "==20.0.0" }, + { name = "transformers", specifier = "==4.57.1" }, +] +native = [ + { name = "accelerate", specifier = "==0.20.3" }, + { name = "datasets", specifier = "==2.14.7" }, + { name = "huggingface-hub", specifier = "==0.36.0" }, + { name = "pyarrow", specifier = "==17.0.0" }, + { name = "transformers", specifier = "==4.28.1" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pandas" +version = "3.0.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e2/17/d7b106e05bfa642e8694451e7d3d759c6a241c5386a5d962e4f66c047e06/pandas-3.0.6.tar.gz", hash = "sha256:66b07ef7315a31bfe1089cd3d71a7de781c9dca986762d0b4fe7c0ef17465d10", size = 4667686, upload-time = "2026-09-17T23:23:18.345Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7d/48/88e8d250d28efa8163294f6809a71683c7ee67f63ac7c33021c0503b3547/pandas-3.0.6-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:085e3786ae6b2e82b406266bce36690f72b9dc1421903ba9296b2981a9fcf586", size = 10391798, upload-time = "2026-09-17T23:20:20.96Z" }, + { url = "https://files.pythonhosted.org/packages/55/a6/39db5d41f3eb5d7846626312cb30e0cea48e988fc47a3725698bc931ad3c/pandas-3.0.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:d7564d86a94c2eb8ab290b07f63ddaae5c032fa53897c29a2ff2197d43aee8af", size = 10023718, upload-time = "2026-09-17T23:20:25.094Z" }, + { url = "https://files.pythonhosted.org/packages/54/b7/707e966129f77ee8a39d41a41bbd989b790b3fef581c6e26b821315cba6b/pandas-3.0.6-cp311-cp311-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1e7c0afdcaf6661d795fcefc2f647ddd1136f62cdc153fba177c685d97a87808", size = 10612800, upload-time = "2026-09-17T23:20:27.99Z" }, + { url = "https://files.pythonhosted.org/packages/63/be/dfb6cc9329d0bbe76dadda8a1113d026bb996ec76c509221368dc68349f4/pandas-3.0.6-cp311-cp311-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:47121f9571503f724c9b93e297ab6254ac99c77adf5e9ed085ea419fd585c258", size = 11108900, upload-time = "2026-09-17T23:20:30.65Z" }, + { url = "https://files.pythonhosted.org/packages/1a/6f/3d58f15bbe972f3d7bfa13ee06d731785a76fe8d232c92b2655a8de14127/pandas-3.0.6-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:994a79608263fe1c14cc48ffa7300e2b834b7d1cb406ffe96a08828cb0cdd79b", size = 11630226, upload-time = "2026-09-17T23:20:33.582Z" }, + { url = "https://files.pythonhosted.org/packages/58/54/9b494de4a3dd92fc6eb19187db1b21afb50fdc21962f32ea1aca9f270cb2/pandas-3.0.6-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:a3a22e07fe75347eaacc75b0e85297947af4fba6b4aae23916bd8b6828d0bba3", size = 12146942, upload-time = "2026-09-17T23:20:36.792Z" }, + { url = "https://files.pythonhosted.org/packages/d3/dc/d2df02854aec5d47659acfb2be352eecc691845b2f86e99c84f1010a8671/pandas-3.0.6-cp311-cp311-win_amd64.whl", hash = "sha256:2e5fa32ff162dfdbc280157d664f44d23049ae414725af9676df339c501d82cd", size = 9859246, upload-time = "2026-09-17T23:20:43.976Z" }, + { url = "https://files.pythonhosted.org/packages/79/1e/2a30df0d7dede5c195300a1820b0bc21cea3aa24e4c8b6c4431565ecc79a/pandas-3.0.6-cp311-cp311-win_arm64.whl", hash = "sha256:5e75072773c1b2f7cb63faa3a6f562aede11f3976f68ed34cb538bc091a28171", size = 9106923, upload-time = "2026-09-17T23:20:46.611Z" }, +] + +[[package]] +name = "pillow" +version = "13.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6c/d7/af6af1b8cc55e07cb0489d5b0950bf5a9bb1461eeba825700b6d8d0e26ea/pillow-13.0.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:6f38f3f885a09cafc93fd667b1173a92f379e43785d635e7983c893f0da319fb", size = 5592324, upload-time = "2026-10-16T22:15:24.672Z" }, + { url = "https://files.pythonhosted.org/packages/0b/d2/2c12cb4fbb5d95f38d1001ff3d95fafcb830077018cba40e56a8f932dfbc/pillow-13.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:37290fbef0c73e2d51d594eb78fded7dc7170d1c3ad0a890269e6fd8c8c4e061", size = 4856298, upload-time = "2026-10-16T22:15:27.669Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/229b27472483a4801ea94990815e710391836afdf987b4b722b62bd75db6/pillow-13.0.0-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7c88c10dd432f3b39ccdafc9ed81d0c21b8fd634502574da76d1bfa4fe2c76d0", size = 6517304, upload-time = "2026-10-16T22:15:29.43Z" }, + { url = "https://files.pythonhosted.org/packages/36/46/f509b74787f40ce0627501089d630b2c741b63b244c1f40b640b3b01e181/pillow-13.0.0-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a625df9a2a5597fa5e5266e01aefc82604bb85d291e3547981e863560d75da6c", size = 7140667, upload-time = "2026-10-16T22:15:31.368Z" }, + { url = "https://files.pythonhosted.org/packages/aa/a4/5a398b8ec2c37145397d6461c0b551c23ec03072aa64f357aed25e582b00/pillow-13.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:10b5019883c98f1dd819ca48ffc6f33a91cee04948fe637c605f4345c7cafd6f", size = 6610583, upload-time = "2026-10-16T22:15:34.025Z" }, + { url = "https://files.pythonhosted.org/packages/4f/7b/f2f1109b230fd4e2d57ab2305de31adc37ea9b4ff8719436c623cb484415/pillow-13.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:f391dc92a015c478745192fe4f2e120c2af2aba18d9fe0616341cbf537599806", size = 7218241, upload-time = "2026-10-16T22:15:36.214Z" }, + { url = "https://files.pythonhosted.org/packages/ab/d3/069edb9083b267746baf59756282cacef904d3475c5288c7216fb5195a98/pillow-13.0.0-cp311-cp311-win32.whl", hash = "sha256:6a0920cb55df5a4d3f6862964908078c0bd59332bdd1bcd20d14e8c70ef27cc5", size = 6515278, upload-time = "2026-10-16T22:15:38.129Z" }, + { url = "https://files.pythonhosted.org/packages/7d/f6/6e2d96413e4c9dbec12ea584d9e646d602877d4cce3ea669099f959deac6/pillow-13.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:d7710eb676e9bb68965cb045be0d333b4c0d7f9dfbaa7fbf121385b1588683d3", size = 7278471, upload-time = "2026-10-16T22:15:40.286Z" }, + { url = "https://files.pythonhosted.org/packages/70/e7/baff21f8cb60496c8c250609501b88919eeedb4088d3da106f6c62f3f3c0/pillow-13.0.0-cp311-cp311-win_arm64.whl", hash = "sha256:12fbb851cf323cc19aac3eea1df5ad17b57e91e9fe3cfd06100dba7bb8208c13", size = 2698981, upload-time = "2026-10-16T22:15:42.637Z" }, + { url = "https://files.pythonhosted.org/packages/68/c0/fb7b1caf25ed5ac5d46116f09b8b0706b9559833c65c667cecb1a53153f2/pillow-13.0.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:405be6058e206a86fedce2f715ecc2343f94072d7925251632dffa2c05f70dca", size = 5521630, upload-time = "2026-10-16T22:17:50.008Z" }, + { url = "https://files.pythonhosted.org/packages/1a/e6/4d11d5b1137f4fc080605cce410cfaae4f303ad400bdec75d27d3083fa29/pillow-13.0.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:b84be41387fc00db28c13c02e30d42b02d8d8f6a4a741a1aee6012ca7f1f6039", size = 4806023, upload-time = "2026-10-16T22:17:51.932Z" }, + { url = "https://files.pythonhosted.org/packages/f1/45/0923202a658e8ff6aafd72c1a4395ebadcdebaa182c437d8595d3dd3db32/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:a192360d512305fe92d3053e4f7627bbad1f7708f1f4ad38cccd9336acabe9ad", size = 5464831, upload-time = "2026-10-16T22:17:53.742Z" }, + { url = "https://files.pythonhosted.org/packages/07/52/d3e38f0cad1dadea2a658b9a7d6ba8a04048f5ae14f011b806e5c3bd6bcb/pillow-13.0.0-pp311-pypy311_pp80-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:83b37abd87b590acd8f47ca8a61f70893322b11834d36e07c2298dacad4d14d2", size = 6043133, upload-time = "2026-10-16T22:17:55.625Z" }, + { url = "https://files.pythonhosted.org/packages/c4/f9/2ed7685980c1d64f8131a7d87a19c369424747577152622b73ddeff163b7/pillow-13.0.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:73ee25cf8cf8b75d5a5aeed7cb6588f5e5dbfbb0fde51707b630bbb23897645c", size = 7365208, upload-time = "2026-10-16T22:17:57.509Z" }, +] + +[[package]] +name = "platformdirs" +version = "4.14.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d7/9a/8475be631fb33ca1466915e70fd594c42a4e84b512db650eaa14f90fe75d/platformdirs-4.14.5.tar.gz", hash = "sha256:32e9921db7385aa8169bee4fe9501923e5715ba9fb7ea3b9c69b0d8e0639f7a1", size = 71464, upload-time = "2026-11-04T16:54:50.358Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7c/ae/ecbbbfd0e4343a6a521d49b3c8656fb4643dee2a4f6eaf941cf3280391a8/platformdirs-4.14.5-py3-none-any.whl", hash = "sha256:8e778c6fa421516f4d3369449f8df3b0e1b72c0e0005fe88e3ec772d0a14e750", size = 35402, upload-time = "2026-11-04T16:54:48.875Z" }, +] + +[[package]] +name = "propcache" +version = "0.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b3/9a/9fbf4e4ec0c2d7f1c32519fff782ef467859b8faa9fbc5331a96f6395d43/propcache-0.5.4.tar.gz", hash = "sha256:ff6b113f50bc066a698db5d944d2c6dc7507168dd3341e255a8892fd0715a558", size = 61545, upload-time = "2026-09-16T00:17:14.386Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/40/14b21e505b7921617466576423f188a5c9caddfdaa1cf4b2b8a83d8fe216/propcache-0.5.4-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:897d1ddf6716e8f47200f7aad9a0efa6cc7586df66c6defa572f9eab379c078e", size = 86393, upload-time = "2026-09-16T00:14:06.9Z" }, + { url = "https://files.pythonhosted.org/packages/e7/4b/5a52e1a7b43563f7d408814194bb23cc8bf214eb6b86639b667a33a8d0d0/propcache-0.5.4-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9cbfff4423eef4cc6cafc021469641a2b835f610b2647a6c5281903e21b8670d", size = 50431, upload-time = "2026-09-16T00:14:08.025Z" }, + { url = "https://files.pythonhosted.org/packages/05/cf/b5248180bf056cc76acc60c9c6e8c0ebbfdbd1c6cffd31fd14996927b7c8/propcache-0.5.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:3fc24f209c1b7f7f688b66b98293954f5504279760999b58920ee12dd8471c1d", size = 52116, upload-time = "2026-09-16T00:14:09.114Z" }, + { url = "https://files.pythonhosted.org/packages/86/a8/7c6cd6bfead1a11f2e411e688640e6d26574cb0bde7dcaa7423b0b65ed7a/propcache-0.5.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:62530ca89187827e4a4fe733f971abe81a7542eeea48ff61995f19b64d7199c8", size = 238729, upload-time = "2026-09-16T00:14:10.357Z" }, + { url = "https://files.pythonhosted.org/packages/5c/b4/442715b2e980df51be52d203549279e027728f24c80b00b5e525e31cd5ea/propcache-0.5.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:56fc3f7599528db40b1efa0889a620116e2704144495273d66066e8164e45838", size = 246121, upload-time = "2026-09-16T00:14:11.735Z" }, + { url = "https://files.pythonhosted.org/packages/bc/5d/df0684fc2b1732a01a7bec26d7897369022712422d25b09c37ce7dbc88a2/propcache-0.5.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:4f2d880ff60f45898f4acfa152aac8d04e3ee627d90ff4003491bf92239d5757", size = 251735, upload-time = "2026-09-16T00:14:13.053Z" }, + { url = "https://files.pythonhosted.org/packages/c7/06/519a5ebb48b6f94beb48396e55c905f12246a25c3a3608a7ec7bceabf50e/propcache-0.5.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6e9368e87a3efc285e559131092c5db643eb8e56de4ee42064d5baec22ef2bb5", size = 235381, upload-time = "2026-09-16T00:14:14.398Z" }, + { url = "https://files.pythonhosted.org/packages/3c/07/1e0a9bb310830f2245edbd5cd3c6d24a783c053c4efd8e08e386e513c940/propcache-0.5.4-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:004e685b315646c410771836e72a44f143bbe624f29653a42687815069a303d5", size = 208973, upload-time = "2026-09-16T00:14:15.715Z" }, + { url = "https://files.pythonhosted.org/packages/62/5c/9324fab27d6088eecc47fe4332bf7aaf8c1ded93c36f558391e8a06d41a7/propcache-0.5.4-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:594eb4c6ec35e7179b058481f4e9f02521b56de16fa577c4b85c76fb1bf8a9f8", size = 233897, upload-time = "2026-09-16T00:14:17.25Z" }, + { url = "https://files.pythonhosted.org/packages/9c/a3/570d92fc952eae93b676f3a1568f4b89264102abd3c982ab6a9ebec58dcf/propcache-0.5.4-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:2dba2f02d2d5c09ef8a0e6c1a42aeaa451f4be9898cb00b04fe98717da2eb23b", size = 223512, upload-time = "2026-09-16T00:14:18.87Z" }, + { url = "https://files.pythonhosted.org/packages/65/47/26810d889d89bba31db397e6a88f8984af775f5ed6bad0a29dce84324cff/propcache-0.5.4-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:c3ef2818d63bc86071e9d2989ae75a1bc32b8f7059cfd9f5abbbee70c32e2ed6", size = 239043, upload-time = "2026-09-16T00:14:20.366Z" }, + { url = "https://files.pythonhosted.org/packages/89/2d/f9c47691aa024c8299a3afacd78d22a01ab57eb627b481b6089708e71017/propcache-0.5.4-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:dd2ac8f5b643454c2cc6b6118b13da16e88f4a6434fc3ba61aca384029f04f36", size = 208218, upload-time = "2026-09-16T00:14:21.801Z" }, + { url = "https://files.pythonhosted.org/packages/74/6b/d510c0c378cabbf9d0ac7b663af6d00f2e9074073d93b20c85f24aa5c071/propcache-0.5.4-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:4054acf80d40456a0537f2913b349718649d8d6458a14ab7f48d0ce28c30869d", size = 240301, upload-time = "2026-09-16T00:14:23.121Z" }, + { url = "https://files.pythonhosted.org/packages/3d/80/c80f6adaaa1e51f0db2dce8c9b3714d94ec45e358a21f9a1910b10b40a80/propcache-0.5.4-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:40e94adb1e7d39ff28a8bd8d8b8fbd1df6b9f40976dbe379134f1ce058e532dd", size = 230785, upload-time = "2026-09-16T00:14:24.458Z" }, + { url = "https://files.pythonhosted.org/packages/d9/e2/c32a7df3f39caa7f11b2eb37ea5b6960a6946f2bc7c4b8ff97bbdf6d6b6e/propcache-0.5.4-cp311-cp311-win32.whl", hash = "sha256:9f86f7259efe2c951f43e57d471c9b41daa5bfc7db9f67189059cf1ae6d77fd9", size = 42747, upload-time = "2026-09-16T00:14:25.715Z" }, + { url = "https://files.pythonhosted.org/packages/0a/8a/3db6a3543d8101263b4c52978b6276a04ead2caff2c5ab880d934f47bd89/propcache-0.5.4-cp311-cp311-win_amd64.whl", hash = "sha256:e904d4d01f36bd6e197590be1533c44e06058771e0746dd073a8ebb3ef880858", size = 46268, upload-time = "2026-09-16T00:14:26.996Z" }, + { url = "https://files.pythonhosted.org/packages/41/07/5222e2665bbf6e45847492ecbf3b9f3e4975a0ae300e5fd465df7d48ce55/propcache-0.5.4-cp311-cp311-win_arm64.whl", hash = "sha256:d42a9a856a4a6e2f6c10f1318c07e7daa498d6593abe745c71dae4521a26ca39", size = 43547, upload-time = "2026-09-16T00:14:28.143Z" }, + { url = "https://files.pythonhosted.org/packages/f5/cd/785c64ed382f3f04201870267b02783f63b4678c2acfddc177a3ebcc2727/propcache-0.5.4-py3-none-any.whl", hash = "sha256:62c60aec739ed00124573cce1178138fd690c7676352d67a37328c1cf51d7468", size = 16338, upload-time = "2026-09-16T00:17:13.106Z" }, +] + +[[package]] +name = "protobuf" +version = "6.33.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/66/70/e908e9c5e52ef7c3a6c7902c9dfbb34c7e29c25d2f81ade3856445fd5c94/protobuf-6.33.6.tar.gz", hash = "sha256:a6768d25248312c297558af96a9f9c929e8c4cee0659cb07e780731095f38135", size = 444531, upload-time = "2026-03-18T19:05:00.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fc/9f/2f509339e89cfa6f6a4c4ff50438db9ca488dec341f7e454adad60150b00/protobuf-6.33.6-cp310-abi3-win32.whl", hash = "sha256:7d29d9b65f8afef196f8334e80d6bc1d5d4adedb449971fefd3723824e6e77d3", size = 425739, upload-time = "2026-03-18T19:04:48.373Z" }, + { url = "https://files.pythonhosted.org/packages/76/5d/683efcd4798e0030c1bab27374fd13a89f7c2515fb1f3123efdfaa5eab57/protobuf-6.33.6-cp310-abi3-win_amd64.whl", hash = "sha256:0cd27b587afca21b7cfa59a74dcbd48a50f0a6400cfb59391340ad729d91d326", size = 437089, upload-time = "2026-03-18T19:04:50.381Z" }, + { url = "https://files.pythonhosted.org/packages/5c/01/a3c3ed5cd186f39e7880f8303cc51385a198a81469d53d0fdecf1f64d929/protobuf-6.33.6-cp39-abi3-macosx_10_9_universal2.whl", hash = "sha256:9720e6961b251bde64edfdab7d500725a2af5280f3f4c87e57c0208376aa8c3a", size = 427737, upload-time = "2026-03-18T19:04:51.866Z" }, + { url = "https://files.pythonhosted.org/packages/ee/90/b3c01fdec7d2f627b3a6884243ba328c1217ed2d978def5c12dc50d328a3/protobuf-6.33.6-cp39-abi3-manylinux2014_aarch64.whl", hash = "sha256:e2afbae9b8e1825e3529f88d514754e094278bb95eadc0e199751cdd9a2e82a2", size = 324610, upload-time = "2026-03-18T19:04:53.096Z" }, + { url = "https://files.pythonhosted.org/packages/9b/ca/25afc144934014700c52e05103c2421997482d561f3101ff352e1292fb81/protobuf-6.33.6-cp39-abi3-manylinux2014_s390x.whl", hash = "sha256:c96c37eec15086b79762ed265d59ab204dabc53056e3443e702d2681f4b39ce3", size = 339381, upload-time = "2026-03-18T19:04:54.616Z" }, + { url = "https://files.pythonhosted.org/packages/16/92/d1e32e3e0d894fe00b15ce28ad4944ab692713f2e7f0a99787405e43533a/protobuf-6.33.6-cp39-abi3-manylinux2014_x86_64.whl", hash = "sha256:e9db7e292e0ab79dd108d7f1a94fe31601ce1ee3f7b79e0692043423020b0593", size = 323436, upload-time = "2026-03-18T19:04:55.768Z" }, + { url = "https://files.pythonhosted.org/packages/c4/72/02445137af02769918a93807b2b7890047c32bfb9f90371cbc12688819eb/protobuf-6.33.6-py3-none-any.whl", hash = "sha256:77179e006c476e69bf8e8ce866640091ec42e1beb80b213c3900006ecfba6901", size = 170656, upload-time = "2026-03-18T19:04:59.826Z" }, +] + +[[package]] +name = "psutil" +version = "7.1.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e1/88/bdd0a41e5857d5d703287598cbf08dad90aed56774ea52ae071bae9071b6/psutil-7.1.3.tar.gz", hash = "sha256:6c86281738d77335af7aec228328e944b30930899ea760ecf33a4dba66be5e74", size = 489059, upload-time = "2025-11-02T12:25:54.619Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/94/46b9154a800253e7ecff5aaacdf8ebf43db99de4a2dfa18575b02548654e/psutil-7.1.3-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2bdbcd0e58ca14996a42adf3621a6244f1bb2e2e528886959c72cf1e326677ab", size = 238359, upload-time = "2025-11-02T12:26:25.284Z" }, + { url = "https://files.pythonhosted.org/packages/68/3a/9f93cff5c025029a36d9a92fef47220ab4692ee7f2be0fba9f92813d0cb8/psutil-7.1.3-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:bc31fa00f1fbc3c3802141eede66f3a2d51d89716a194bf2cd6fc68310a19880", size = 239171, upload-time = "2025-11-02T12:26:27.23Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b1/5f49af514f76431ba4eea935b8ad3725cdeb397e9245ab919dbc1d1dc20f/psutil-7.1.3-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3bb428f9f05c1225a558f53e30ccbad9930b11c3fc206836242de1091d3e7dd3", size = 263261, upload-time = "2025-11-02T12:26:29.48Z" }, + { url = "https://files.pythonhosted.org/packages/e0/95/992c8816a74016eb095e73585d747e0a8ea21a061ed3689474fabb29a395/psutil-7.1.3-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56d974e02ca2c8eb4812c3f76c30e28836fffc311d55d979f1465c1feeb2b68b", size = 264635, upload-time = "2025-11-02T12:26:31.74Z" }, + { url = "https://files.pythonhosted.org/packages/55/4c/c3ed1a622b6ae2fd3c945a366e64eb35247a31e4db16cf5095e269e8eb3c/psutil-7.1.3-cp37-abi3-win_amd64.whl", hash = "sha256:f39c2c19fe824b47484b96f9692932248a54c43799a84282cfe58d05a6449efd", size = 247633, upload-time = "2025-11-02T12:26:33.887Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ad/33b2ccec09bf96c2b2ef3f9a6f66baac8253d7565d8839e024a6b905d45d/psutil-7.1.3-cp37-abi3-win_arm64.whl", hash = "sha256:bd0d69cee829226a761e92f28140bec9a5ee9d5b4fb4b0cc589068dbfff559b1", size = 244608, upload-time = "2025-11-02T12:26:36.136Z" }, +] + +[[package]] +name = "pyarrow" +version = "17.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/27/4e/ea6d43f324169f8aec0e57569443a38bab4b398d09769ca64f7b4d467de3/pyarrow-17.0.0.tar.gz", hash = "sha256:4beca9521ed2c0921c1023e68d097d0299b62c362639ea315572a58f3f50fd28", size = 1112479, upload-time = "2024-07-17T10:41:25.092Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/46/ce89f87c2936f5bb9d879473b9663ce7a4b1f4359acc2f0eb39865eaa1af/pyarrow-17.0.0-cp311-cp311-macosx_10_15_x86_64.whl", hash = "sha256:1c8856e2ef09eb87ecf937104aacfa0708f22dfeb039c363ec99735190ffb977", size = 29028748, upload-time = "2024-07-16T10:30:02.609Z" }, + { url = "https://files.pythonhosted.org/packages/8d/8e/ce2e9b2146de422f6638333c01903140e9ada244a2a477918a368306c64c/pyarrow-17.0.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:2e19f569567efcbbd42084e87f948778eb371d308e137a0f97afe19bb860ccb3", size = 27190965, upload-time = "2024-07-16T10:30:10.718Z" }, + { url = "https://files.pythonhosted.org/packages/3b/c8/5675719570eb1acd809481c6d64e2136ffb340bc387f4ca62dce79516cea/pyarrow-17.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6b244dc8e08a23b3e352899a006a26ae7b4d0da7bb636872fa8f5884e70acf15", size = 39269081, upload-time = "2024-07-16T10:30:18.878Z" }, + { url = "https://files.pythonhosted.org/packages/5e/78/3931194f16ab681ebb87ad252e7b8d2c8b23dad49706cadc865dff4a1dd3/pyarrow-17.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0b72e87fe3e1db343995562f7fff8aee354b55ee83d13afba65400c178ab2597", size = 39864921, upload-time = "2024-07-16T10:30:27.008Z" }, + { url = "https://files.pythonhosted.org/packages/d8/81/69b6606093363f55a2a574c018901c40952d4e902e670656d18213c71ad7/pyarrow-17.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:dc5c31c37409dfbc5d014047817cb4ccd8c1ea25d19576acf1a001fe07f5b420", size = 38740798, upload-time = "2024-07-16T10:30:34.814Z" }, + { url = "https://files.pythonhosted.org/packages/4c/21/9ca93b84b92ef927814cb7ba37f0774a484c849d58f0b692b16af8eebcfb/pyarrow-17.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:e3343cb1e88bc2ea605986d4b94948716edc7a8d14afd4e2c097232f729758b4", size = 39871877, upload-time = "2024-07-16T10:30:42.672Z" }, + { url = "https://files.pythonhosted.org/packages/30/d1/63a7c248432c71c7d3ee803e706590a0b81ce1a8d2b2ae49677774b813bb/pyarrow-17.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:a27532c38f3de9eb3e90ecab63dfda948a8ca859a66e3a47f5f42d1e403c4d03", size = 25151089, upload-time = "2024-07-16T10:30:49.279Z" }, +] + +[[package]] +name = "pyarrow" +version = "20.0.0" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/a2/ee/a7810cb9f3d6e9238e61d312076a9859bf3668fd21c69744de9532383912/pyarrow-20.0.0.tar.gz", hash = "sha256:febc4a913592573c8d5805091a6c2b5064c8bd6e002131f01061797d91c783c1", size = 1125187, upload-time = "2025-04-27T12:34:23.264Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/47/a2/b7930824181ceadd0c63c1042d01fa4ef63eee233934826a7a2a9af6e463/pyarrow-20.0.0-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:24ca380585444cb2a31324c546a9a56abbe87e26069189e14bdba19c86c049f0", size = 30856035, upload-time = "2025-04-27T12:28:40.78Z" }, + { url = "https://files.pythonhosted.org/packages/9b/18/c765770227d7f5bdfa8a69f64b49194352325c66a5c3bb5e332dfd5867d9/pyarrow-20.0.0-cp311-cp311-macosx_12_0_x86_64.whl", hash = "sha256:95b330059ddfdc591a3225f2d272123be26c8fa76e8c9ee1a77aad507361cfdb", size = 32309552, upload-time = "2025-04-27T12:28:47.051Z" }, + { url = "https://files.pythonhosted.org/packages/44/fb/dfb2dfdd3e488bb14f822d7335653092dde150cffc2da97de6e7500681f9/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5f0fb1041267e9968c6d0d2ce3ff92e3928b243e2b6d11eeb84d9ac547308232", size = 41334704, upload-time = "2025-04-27T12:28:55.064Z" }, + { url = "https://files.pythonhosted.org/packages/58/0d/08a95878d38808051a953e887332d4a76bc06c6ee04351918ee1155407eb/pyarrow-20.0.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b8ff87cc837601532cc8242d2f7e09b4e02404de1b797aee747dd4ba4bd6313f", size = 42399836, upload-time = "2025-04-27T12:29:02.13Z" }, + { url = "https://files.pythonhosted.org/packages/f3/cd/efa271234dfe38f0271561086eedcad7bc0f2ddd1efba423916ff0883684/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:7a3a5dcf54286e6141d5114522cf31dd67a9e7c9133d150799f30ee302a7a1ab", size = 40711789, upload-time = "2025-04-27T12:29:09.951Z" }, + { url = "https://files.pythonhosted.org/packages/46/1f/7f02009bc7fc8955c391defee5348f510e589a020e4b40ca05edcb847854/pyarrow-20.0.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:a6ad3e7758ecf559900261a4df985662df54fb7fdb55e8e3b3aa99b23d526b62", size = 42301124, upload-time = "2025-04-27T12:29:17.187Z" }, + { url = "https://files.pythonhosted.org/packages/4f/92/692c562be4504c262089e86757a9048739fe1acb4024f92d39615e7bab3f/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:6bb830757103a6cb300a04610e08d9636f0cd223d32f388418ea893a3e655f1c", size = 42916060, upload-time = "2025-04-27T12:29:24.253Z" }, + { url = "https://files.pythonhosted.org/packages/a4/ec/9f5c7e7c828d8e0a3c7ef50ee62eca38a7de2fa6eb1b8fa43685c9414fef/pyarrow-20.0.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:96e37f0766ecb4514a899d9a3554fadda770fb57ddf42b63d80f14bc20aa7db3", size = 44547640, upload-time = "2025-04-27T12:29:32.782Z" }, + { url = "https://files.pythonhosted.org/packages/54/96/46613131b4727f10fd2ffa6d0d6f02efcc09a0e7374eff3b5771548aa95b/pyarrow-20.0.0-cp311-cp311-win_amd64.whl", hash = "sha256:3346babb516f4b6fd790da99b98bed9708e3f02e734c84971faccb20736848dc", size = 25781491, upload-time = "2025-04-27T12:29:38.464Z" }, +] + +[[package]] +name = "pyarrow-hotfix" +version = "0.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d2/ed/c3e8677f7abf3981838c2af7b5ac03e3589b3ef94fcb31d575426abae904/pyarrow_hotfix-0.7.tar.gz", hash = "sha256:59399cd58bdd978b2e42816a4183a55c6472d4e33d183351b6069f11ed42661d", size = 9910, upload-time = "2025-04-25T10:17:06.247Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2e/c3/94ade4906a2f88bc935772f59c934013b4205e773bcb4239db114a6da136/pyarrow_hotfix-0.7-py3-none-any.whl", hash = "sha256:3236f3b5f1260f0e2ac070a55c1a7b339c4bb7267839bd2015e283234e758100", size = 7923, upload-time = "2025-04-25T10:17:05.224Z" }, +] + +[[package]] +name = "pydantic" +version = "2.14.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "annotated-types" }, + { name = "pydantic-core" }, + { name = "typing-extensions" }, + { name = "typing-inspection" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b4/fc/1203d011145c98ddce3cd2f505bb54375ef8d43223053df6bfcf3c746f46/pydantic-2.14.3.tar.gz", hash = "sha256:1054f237f4d4733e5a30e1e2333bd33a2004ab9ab1510bd053a9a31bb48e232d", size = 925636, upload-time = "2026-11-05T09:17:04.686Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/b8/b864503789ef5c58597d2a7b4adbee62c26440ab1e682581fc6838df8947/pydantic-2.14.3-py3-none-any.whl", hash = "sha256:3f7b347782ab7e4cf4c798496ae3a82787d9f21ec12676a9c564355eeef8daa8", size = 494071, upload-time = "2026-11-05T09:17:02.426Z" }, +] + +[[package]] +name = "pydantic-core" +version = "2.50.4" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9c/0f/34f9ce4ba701dd0b815033ef94d99b56f66200e578ee6052aa3ac26f064e/pydantic_core-2.50.4.tar.gz", hash = "sha256:aead3b74b68396bf0feab5d57e050b730ded7df55853c1e048a87e00aaf033c6", size = 522249, upload-time = "2026-11-05T09:15:26.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/00/85e80811834d7cbd9bc228f9b5cdf8ec0edd69b55351ad720aac8c412d8c/pydantic_core-2.50.4-cp311-cp311-macosx_10_12_x86_64.whl", hash = "sha256:3e547ceec1da7382f01f9e13963023e53367a71802c88778b21b9645a077cbdf", size = 2170584, upload-time = "2026-11-05T09:11:41.139Z" }, + { url = "https://files.pythonhosted.org/packages/a3/f1/438de1fb99d717dcc6521922478dc16ef7b757302d4fc1f7faba3aaeac09/pydantic_core-2.50.4-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:c813ada7a651193acda85b6bc1cf12abd4b37cd25c7c6a75d7183512cc374969", size = 2128471, upload-time = "2026-11-05T09:11:42.65Z" }, + { url = "https://files.pythonhosted.org/packages/b7/74/f21ab568c6d3f315988b40e53f809c95b63fafc5403332963aa6dfc2c054/pydantic_core-2.50.4-cp311-cp311-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:57fa0a9490785139f1a4e4f43891830d55dfe4408845c0c9cb5eff4aeaf75f69", size = 2281509, upload-time = "2026-11-05T09:11:44.359Z" }, + { url = "https://files.pythonhosted.org/packages/a1/42/24ed3ea8e2fb6463c9ba5b8b1f089e69040905c7fd81dcfa6f52fcc692d5/pydantic_core-2.50.4-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:30d4dc35bc0eea52202a90b3820445ee0072c820241bfa710a623a078c9b267b", size = 2128064, upload-time = "2026-11-05T09:11:46.01Z" }, + { url = "https://files.pythonhosted.org/packages/d6/d1/44f541b2c18a46df6f18281a557acefeb5bbf0733a0b80b0a5e835e10ee4/pydantic_core-2.50.4-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.whl", hash = "sha256:789f88dea57841cdebef392b5d6e90444d767117e9ff2e0d9172df5c9de6690c", size = 2214472, upload-time = "2026-11-05T09:11:47.503Z" }, + { url = "https://files.pythonhosted.org/packages/bd/1b/e9a9ad8733e8051abca9e4acce37ba3ddd13930fd3b8730f4c7816fa979a/pydantic_core-2.50.4-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:d690121e80ab16e623415351ab24713534d4e500b3cadff216409cb6826063d4", size = 2401153, upload-time = "2026-11-05T09:11:49.403Z" }, + { url = "https://files.pythonhosted.org/packages/79/84/d88e8e6aa42d4d677666d6625db9177ad6851be9e7564a25aeb0b0cbcaf2/pydantic_core-2.50.4-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:b42f64825f5d750228f08318a9bf4d723b7ecb4c472aedcb3013c3ec2dc1f949", size = 2453307, upload-time = "2026-11-05T09:11:51.118Z" }, + { url = "https://files.pythonhosted.org/packages/56/51/cbb7a1bc0196ff94d3478d265eed7449f811759988eb760d41f4edd0893b/pydantic_core-2.50.4-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0574866e05f6adeecc520d87e87dd06210c0a51706341f6ef8421572f5a64444", size = 2253434, upload-time = "2026-11-05T09:11:52.997Z" }, + { url = "https://files.pythonhosted.org/packages/9e/04/206b4881d631033ae88f005da6e11bd610c850e1850217342c03053d253b/pydantic_core-2.50.4-cp311-cp311-manylinux_2_31_riscv64.whl", hash = "sha256:dcf2c7eaaa4cafe8e49b017e5bb49e76e084ab6f0cd712ee4019c812b5cf68b8", size = 2279365, upload-time = "2026-11-05T09:11:54.822Z" }, + { url = "https://files.pythonhosted.org/packages/a1/7c/d815b5a3f83069b283d3b6a2e61de6e14baac3b20c6cd3418e9e629551cf/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:3b8ee2589a082739c522c1fe4be227412fcf108b903abb6672ae2f5570558882", size = 2319407, upload-time = "2026-11-05T09:11:56.46Z" }, + { url = "https://files.pythonhosted.org/packages/ee/00/c9a483276d1052d5142e1e01eccac97d939f83a3a3fd94c4766495a9b807/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_armv7l.whl", hash = "sha256:aec3c2d741a8e3ee993de7f95f37afb51e31b169c95dbd29da4cf6688f340914", size = 2489900, upload-time = "2026-11-05T09:11:58.102Z" }, + { url = "https://files.pythonhosted.org/packages/2d/b5/8cd8ee29a1d63ad47f95593384df92476cef6896c644f280db0748b8e76b/pydantic_core-2.50.4-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8923fcd49f875e8a0448d7223d1fdf1a9973ae2d1f20d4158753ceb8909facd2", size = 2497732, upload-time = "2026-11-05T09:11:59.928Z" }, + { url = "https://files.pythonhosted.org/packages/60/31/050a48c0c373df16442ac07f3fa167414bb0e22f54a3e886f6d6cb7ad1d4/pydantic_core-2.50.4-cp311-cp311-win32.whl", hash = "sha256:fc04affef30be98c1f36f0c422a4061ef618fdc1dde79f5ad5458dd496fecffa", size = 2132347, upload-time = "2026-11-05T09:12:01.928Z" }, + { url = "https://files.pythonhosted.org/packages/c6/06/cebeeb7a8e87b42a3d8bc189d0d400e47df5d1736cb326764bae8a74c433/pydantic_core-2.50.4-cp311-cp311-win_amd64.whl", hash = "sha256:15bece43a02ad543c621c8305e67dedb5f27d378c5ba741e5a2c36523f8ef37f", size = 2255970, upload-time = "2026-11-05T09:12:03.888Z" }, + { url = "https://files.pythonhosted.org/packages/46/db/5b4bf14347da658c994483043fbabffedcab98929c41c261ec168c3c1f87/pydantic_core-2.50.4-cp311-cp311-win_arm64.whl", hash = "sha256:e498900bfbf7ddddd862f810440c09e9b81674739e8a11d619b40906dccd4a9a", size = 2196799, upload-time = "2026-11-05T09:12:05.389Z" }, + { url = "https://files.pythonhosted.org/packages/d8/18/3ca5b3b8ce7a540305e6856d013e9c6b9c0fef93258fef6038db0beb233a/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_10_12_x86_64.whl", hash = "sha256:39f489ce31272073e6e146f6781690f9c1ee8c126836e6403361ef91154d89fe", size = 2166960, upload-time = "2026-11-05T09:15:06.902Z" }, + { url = "https://files.pythonhosted.org/packages/a3/60/65d725001bffcde0170f6d37ae8bccce715e5311122eb6127f698115957e/pydantic_core-2.50.4-pp311-pypy311_pp73-macosx_11_0_arm64.whl", hash = "sha256:5b26e5f1793b96cdc60242bf38da86ff24a27a708aa396214cac9b534bf571c7", size = 2085636, upload-time = "2026-11-05T09:15:08.395Z" }, + { url = "https://files.pythonhosted.org/packages/ac/12/934cf1d44a3fee3c47231d4690dddee19264150c3aa59a3ddf66fa43454d/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux1_i686.manylinux_2_5_i686.whl", hash = "sha256:7210398a1607ad607dc73196e575b3148b00a333cbb602ddbe1b60ba54554f43", size = 2284621, upload-time = "2026-11-05T09:15:09.82Z" }, + { url = "https://files.pythonhosted.org/packages/c4/91/52248eee98d76f8d9239166d24928f805292df16729109f4f189cdb59be4/pydantic_core-2.50.4-pp311-pypy311_pp73-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2f42584e5785385f681163a42506cab0d51295e17599a648396c52a7046c1372", size = 2277673, upload-time = "2026-11-05T09:15:11.236Z" }, + { url = "https://files.pythonhosted.org/packages/9f/89/900a7970ef19843aa79522a95b461e9c365b7fedd7ee80ef28a84dae9a41/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:2039e323acee9abfec1fb5f661776e8965fe5928f3b7f8431900a774cba5c317", size = 2297354, upload-time = "2026-11-05T09:15:12.798Z" }, + { url = "https://files.pythonhosted.org/packages/de/ec/053d829437f70070cdd7116a0257cc0da651103328ff1e9e82954c45efd6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_armv7l.whl", hash = "sha256:71ade6d2e445839350d589ff99bbddfde16f3f32db28da5c894a09f99c8b2a03", size = 2469913, upload-time = "2026-11-05T09:15:14.319Z" }, + { url = "https://files.pythonhosted.org/packages/80/af/207c821cb0813e16d630660e0073491e3ab07370efaa6fa0b8b10fffb7b6/pydantic_core-2.50.4-pp311-pypy311_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:d7d406709ae924cf0b08b8282ca2f0e1c90526911d93bc040557cbc83b74c55f", size = 2503746, upload-time = "2026-11-05T09:15:15.736Z" }, + { url = "https://files.pythonhosted.org/packages/e7/ca/8a053f24e22d8150349cabaecb2f35c89dcf07fbaadb5e48295184dd0e5b/pydantic_core-2.50.4-pp311-pypy311_pp73-win_amd64.whl", hash = "sha256:7472c39480ccc11dda69a196d1b7c7a6b48eb6594b77f05d945599d3e47f731c", size = 2333540, upload-time = "2026-11-05T09:15:17.883Z" }, + { url = "https://files.pythonhosted.org/packages/ac/9d/41b374c62cdb87f84081e2ef2963a115eacc6284a26dbc96bb83568e83ec/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_10_12_x86_64.whl", hash = "sha256:b67d38e8bb0ade7e6e84575e4bb153fab35b122458077273aeb08fdf12be9d2c", size = 2166962, upload-time = "2026-11-05T09:15:20.276Z" }, + { url = "https://files.pythonhosted.org/packages/9a/4f/51ef440ee346d4388a2c4a3ac4b271fcc7b1d3ff68be8da2ed2be4d488b0/pydantic_core-2.50.4-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:4eda7e3fdef382b7d4492745988a5baaf6953923a337f8b9dde5f76fa8afde20", size = 2085634, upload-time = "2026-11-05T09:15:21.953Z" }, + { url = "https://files.pythonhosted.org/packages/4b/5f/c9ed62b96beb9050db221d29e81856b6e28f277db601f8b0c3a08f8cf913/pydantic_core-2.50.4-pp311-pypy311_pp80-manylinux_2_28_x86_64.whl", hash = "sha256:474f7e598c7902165662a5d5160d3fce31037890a2975a9871ebf7c05862300b", size = 2277804, upload-time = "2026-11-05T09:15:23.836Z" }, + { url = "https://files.pythonhosted.org/packages/63/bd/b912a5e251ef10ed7be5e543a2bfbeebb0c79bf6302bee786f8dc3bf4341/pydantic_core-2.50.4-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:3e0b395648c6cb871bceb2906907f255dc876ec425f2d5b024e129985cea8519", size = 2333539, upload-time = "2026-11-05T09:15:25.354Z" }, +] + +[[package]] +name = "pyparsing" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/11/b213bebff182584360cb8d17c72c1677fec5c5c228de439e63bcf8ab1c8f/pyparsing-3.3.3.tar.gz", hash = "sha256:928ae7e20211f3b6f3915a72f06a0cfd29ab9d24279dd6346b6b1a7146397d36", size = 1050487, upload-time = "2026-09-20T20:59:05.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" }, +] + +[[package]] +name = "python-dateutil" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/16/a95b6757765b7b031c9374925bb718d55e0a9ba8a1b6a12d25962ea44347/pyyaml-6.0.3-cp311-cp311-macosx_10_13_x86_64.whl", hash = "sha256:44edc647873928551a01e7a563d7452ccdebee747728c1080d881d68af7b997e", size = 185826, upload-time = "2025-09-25T21:31:58.655Z" }, + { url = "https://files.pythonhosted.org/packages/16/19/13de8e4377ed53079ee996e1ab0a9c33ec2faf808a4647b7b4c0d46dd239/pyyaml-6.0.3-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:652cb6edd41e718550aad172851962662ff2681490a8a711af6a4d288dd96824", size = 175577, upload-time = "2025-09-25T21:32:00.088Z" }, + { url = "https://files.pythonhosted.org/packages/0c/62/d2eb46264d4b157dae1275b573017abec435397aa59cbcdab6fc978a8af4/pyyaml-6.0.3-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:10892704fc220243f5305762e276552a0395f7beb4dbf9b14ec8fd43b57f126c", size = 775556, upload-time = "2025-09-25T21:32:01.31Z" }, + { url = "https://files.pythonhosted.org/packages/10/cb/16c3f2cf3266edd25aaa00d6c4350381c8b012ed6f5276675b9eba8d9ff4/pyyaml-6.0.3-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:850774a7879607d3a6f50d36d04f00ee69e7fc816450e5f7e58d7f17f1ae5c00", size = 882114, upload-time = "2025-09-25T21:32:03.376Z" }, + { url = "https://files.pythonhosted.org/packages/71/60/917329f640924b18ff085ab889a11c763e0b573da888e8404ff486657602/pyyaml-6.0.3-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b8bb0864c5a28024fac8a632c443c87c5aa6f215c0b126c449ae1a150412f31d", size = 806638, upload-time = "2025-09-25T21:32:04.553Z" }, + { url = "https://files.pythonhosted.org/packages/dd/6f/529b0f316a9fd167281a6c3826b5583e6192dba792dd55e3203d3f8e655a/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:1d37d57ad971609cf3c53ba6a7e365e40660e3be0e5175fa9f2365a379d6095a", size = 767463, upload-time = "2025-09-25T21:32:06.152Z" }, + { url = "https://files.pythonhosted.org/packages/f2/6a/b627b4e0c1dd03718543519ffb2f1deea4a1e6d42fbab8021936a4d22589/pyyaml-6.0.3-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:37503bfbfc9d2c40b344d06b2199cf0e96e97957ab1c1b546fd4f87e53e5d3e4", size = 794986, upload-time = "2025-09-25T21:32:07.367Z" }, + { url = "https://files.pythonhosted.org/packages/45/91/47a6e1c42d9ee337c4839208f30d9f09caa9f720ec7582917b264defc875/pyyaml-6.0.3-cp311-cp311-win32.whl", hash = "sha256:8098f252adfa6c80ab48096053f512f2321f0b998f98150cea9bd23d83e1467b", size = 142543, upload-time = "2025-09-25T21:32:08.95Z" }, + { url = "https://files.pythonhosted.org/packages/da/e3/ea007450a105ae919a72393cb06f122f288ef60bba2dc64b26e2646fa315/pyyaml-6.0.3-cp311-cp311-win_amd64.whl", hash = "sha256:9f3bfb4965eb874431221a3ff3fdcddc7e74e3b07799e0e84ca4a0f867d449bf", size = 158763, upload-time = "2025-09-25T21:32:09.96Z" }, +] + +[[package]] +name = "regex" +version = "2026.11.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/61/27/a5afeb952577b84ee5fe48b8b9ce47ae662dbb69cc5b76c28eff98f83b1e/regex-2026.11.9.tar.gz", hash = "sha256:316a70fbd70e999c9664681cb0eb5b4982b2cc0f623c7c86a8a112e1bd4c6277", size = 419513, upload-time = "2026-11-09T00:42:09.786Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/cd/83393cd04d1cdafb07dc6d3e4f6f40455c7d54edcfb7513a51c632a2fa32/regex-2026.11.9-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:bc0414bae708e91fa635af848ea1fdc13e442f30497077da562014f88ac67436", size = 496166, upload-time = "2026-11-09T00:39:39.152Z" }, + { url = "https://files.pythonhosted.org/packages/13/90/65cd23cc77094ea6953a7f4f9808539611b71881b7d91729243fcaa43109/regex-2026.11.9-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:26f5137412492f043d13903b8ee3bbc464a73c67ec9432e187f5a5eef25c398f", size = 295747, upload-time = "2026-11-09T00:39:40.41Z" }, + { url = "https://files.pythonhosted.org/packages/3d/61/6523251b377f38be938342fd52da4aead1a1d1b79ce137d4412e5b1eb79e/regex-2026.11.9-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:cf8ba77a8d23fac7912cd9890a49d8f006106147bb80312c9954558b24ec7f95", size = 292719, upload-time = "2026-11-09T00:39:41.711Z" }, + { url = "https://files.pythonhosted.org/packages/97/5c/59cceda8ed285cb277f90f22b220c89576a38ebd1f2d7f0af198af98a5c7/regex-2026.11.9-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c876a5e3992b5f14709c7260188929174247485ed3f940bd94d4beb70abbfed3", size = 799904, upload-time = "2026-11-09T00:39:43.023Z" }, + { url = "https://files.pythonhosted.org/packages/9b/d0/498c4f67179885a4baf3b4500ea371d671180c20e136844065c239fe95d4/regex-2026.11.9-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:49eecd9b855cc9e683fed1b258d4e22dcb8e7b3c82f09c5778ce154359607f09", size = 874027, upload-time = "2026-11-09T00:39:44.36Z" }, + { url = "https://files.pythonhosted.org/packages/33/b9/61d474ad8aa93022edb00f13fcaac44678a5ef858801c804ad7d201d048b/regex-2026.11.9-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2405a0e564a5a1226427b21ee02a70c64f33a10015a18e480039c8ddb46b4f00", size = 915647, upload-time = "2026-11-09T00:39:45.587Z" }, + { url = "https://files.pythonhosted.org/packages/82/14/ec0c0f9e600f308280b901b46dd6e0095b56017fc2216b2abe6182009655/regex-2026.11.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0447593c5f4e2b88446da7466c83fc913ddf191600bbb7aebc6c8856595ccfb1", size = 805976, upload-time = "2026-11-09T00:39:47.654Z" }, + { url = "https://files.pythonhosted.org/packages/5e/de/bf7d2789051771e637d36aab03adea41b1e5729fe0c2a3d1df5e85a422bb/regex-2026.11.9-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:727989b08b98af7592eb86af12ca4227c017579094d5893a76fdd20b319cd8cd", size = 807143, upload-time = "2026-11-09T00:39:48.999Z" }, + { url = "https://files.pythonhosted.org/packages/0d/14/1a62ebd94dc36f74e2bb7f37bb7d7faf3bfc013cc90c1b1463d157e20136/regex-2026.11.9-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:b886e1b7be6c392ea99d1c04de9b7adb4774038a1041514dfc6d0c5fb1bee6c5", size = 780582, upload-time = "2026-11-09T00:39:50.189Z" }, + { url = "https://files.pythonhosted.org/packages/3e/9b/42ce68062387ad6cbc4e2c5dc36d7f25d7a4d7621b5a67b8cd1a913ff2b4/regex-2026.11.9-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:f1ec6903dc8054129ccc9404a5aaf19e4fab9af98b03604c69db903da3c045a4", size = 788733, upload-time = "2026-11-09T00:39:51.267Z" }, + { url = "https://files.pythonhosted.org/packages/ff/17/8e5268e78894c2a979a1599f9261eb0ede9952028d0a2689fbd80f2998b5/regex-2026.11.9-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:5c31a4e92c02f5c9e85c37a3851b9f83a36d2afdaaa88368f0d29ac56d8c81b8", size = 863625, upload-time = "2026-11-09T00:39:52.437Z" }, + { url = "https://files.pythonhosted.org/packages/97/0a/82e544ef361afc84e85a47907210bd9d1ef5c887b11ae3e091317c699327/regex-2026.11.9-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:3dbccc60fa24fa1bab1cffe580c9bcd6467a885b6260d5e419f6d13db8c3596f", size = 766599, upload-time = "2026-11-09T00:39:54.03Z" }, + { url = "https://files.pythonhosted.org/packages/bf/4b/6484189c5f81e668059464780802b4bd6023415655c9410e8668a0a52a29/regex-2026.11.9-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:b5ce8fd914c9eaedfefa444ed329fc5a80c723136bda90e9e69159c536854c52", size = 855980, upload-time = "2026-11-09T00:39:55.184Z" }, + { url = "https://files.pythonhosted.org/packages/59/f8/954254f0c28b8113b304f0a9fec86274ad043b997161bb019ece9a00e5b8/regex-2026.11.9-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:ff675c20d54564cb2b6c480c2e4b362dcc3ce74887ee2d2e63037658a0f01ab5", size = 793610, upload-time = "2026-11-09T00:39:56.351Z" }, + { url = "https://files.pythonhosted.org/packages/d9/2e/c30c186c8e0d55f4fa6cc882fb3f7eb3731ad70ffc5f99d40e99f261fadc/regex-2026.11.9-cp311-cp311-win32.whl", hash = "sha256:dd679c8172c94291ccee40e17b03b6e34c553ad855a57dc52e811c3bb83403f1", size = 269436, upload-time = "2026-11-09T00:39:57.808Z" }, + { url = "https://files.pythonhosted.org/packages/b5/6a/c23207465db6bb7a98211e82e5f79dc5473abea56464960f1c705bda888a/regex-2026.11.9-cp311-cp311-win_amd64.whl", hash = "sha256:b75ea29155c988eb375325a9fd9270a550ea3427acf275d350538c5f83571abc", size = 281159, upload-time = "2026-11-09T00:39:58.824Z" }, + { url = "https://files.pythonhosted.org/packages/df/7e/fe3c59e5adec098cddf9d65ed5f6543c070a344527a20d20e6731d4e57da/regex-2026.11.9-cp311-cp311-win_arm64.whl", hash = "sha256:b9c9746f25607eabe931c42f25535c9461589e25a80879a361f9c02f7abb6dce", size = 279986, upload-time = "2026-11-09T00:39:59.892Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "rouge" +version = "1.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/db/e4/3420a1ab1e82a280fb6107f7ae99e88eb12383c978fe573c0c64d0327d6b/rouge-1.0.1.tar.gz", hash = "sha256:12b48346ca47d6bcf3c45061f315452b9ccec0620ee895ec85b7efc3d54aae34", size = 14292, upload-time = "2021-07-20T08:45:56.53Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/7c/650ae86f92460e9e8ef969cc5008b24798dcf56a9a8947d04c78f550b3f5/rouge-1.0.1-py3-none-any.whl", hash = "sha256:28d118536e8c774dc47d1d15ec266479b4dd0914c4672ce117d4002789bdc644", size = 13725, upload-time = "2021-07-20T08:45:54.605Z" }, +] + +[[package]] +name = "safetensors" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/a0/f718cda65b05407d228f97602cf60dca269c979867aa5beb25410de26cd3/safetensors-0.8.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0", size = 473568, upload-time = "2026-06-09T07:52:18.829Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b1/fa7c600e7dceae12e9606c7578cbc9ff1e1ed55844883ee5c92205e86226/safetensors-0.8.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25", size = 484562, upload-time = "2026-06-09T07:52:17.518Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" }, + { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" }, + { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" }, + { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" }, + { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" }, + { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" }, + { url = "https://files.pythonhosted.org/packages/0d/49/1e15de264dcc3b77943d2d0c56a95809956883b1c2d6d585c792523f180b/safetensors-0.8.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca", size = 559930, upload-time = "2026-06-09T07:52:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" }, + { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" }, + { url = "https://files.pythonhosted.org/packages/29/4b/1c19c509d56e01f4fbb3d0a2e597450f6cc04d1d56cf52defb0a62dfd715/safetensors-0.8.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d", size = 765683, upload-time = "2026-06-09T07:52:22.594Z" }, + { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" }, + { url = "https://files.pythonhosted.org/packages/8e/3f/73ccf82579412b4a71c4ca673f10b5f1f888d7cf5af7fe24f27d30307be4/safetensors-0.8.0-cp310-abi3-win32.whl", hash = "sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d", size = 342401, upload-time = "2026-06-09T07:52:28.895Z" }, + { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" }, + { url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" }, +] + +[[package]] +name = "scikit-learn" +version = "1.7.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "joblib" }, + { name = "numpy" }, + { name = "scipy" }, + { name = "threadpoolctl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/c2/a7855e41c9d285dfe86dc50b250978105dce513d6e459ea66a6aeb0e1e0c/scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda", size = 7193136, upload-time = "2025-09-09T08:21:29.075Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/83/564e141eef908a5863a54da8ca342a137f45a0bfb71d1d79704c9894c9d1/scikit_learn-1.7.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c7509693451651cd7361d30ce4e86a1347493554f172b1c72a39300fa2aea79e", size = 9331967, upload-time = "2025-09-09T08:20:32.421Z" }, + { url = "https://files.pythonhosted.org/packages/18/d6/ba863a4171ac9d7314c4d3fc251f015704a2caeee41ced89f321c049ed83/scikit_learn-1.7.2-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:0486c8f827c2e7b64837c731c8feff72c0bd2b998067a8a9cbc10643c31f0fe1", size = 8648645, upload-time = "2025-09-09T08:20:34.436Z" }, + { url = "https://files.pythonhosted.org/packages/ef/0e/97dbca66347b8cf0ea8b529e6bb9367e337ba2e8be0ef5c1a545232abfde/scikit_learn-1.7.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:89877e19a80c7b11a2891a27c21c4894fb18e2c2e077815bcade10d34287b20d", size = 9715424, upload-time = "2025-09-09T08:20:36.776Z" }, + { url = "https://files.pythonhosted.org/packages/f7/32/1f3b22e3207e1d2c883a7e09abb956362e7d1bd2f14458c7de258a26ac15/scikit_learn-1.7.2-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:8da8bf89d4d79aaec192d2bda62f9b56ae4e5b4ef93b6a56b5de4977e375c1f1", size = 9509234, upload-time = "2025-09-09T08:20:38.957Z" }, + { url = "https://files.pythonhosted.org/packages/9f/71/34ddbd21f1da67c7a768146968b4d0220ee6831e4bcbad3e03dd3eae88b6/scikit_learn-1.7.2-cp311-cp311-win_amd64.whl", hash = "sha256:9b7ed8d58725030568523e937c43e56bc01cadb478fc43c042a9aca1dacb3ba1", size = 8894244, upload-time = "2025-09-09T08:20:41.166Z" }, +] + +[[package]] +name = "scipy" +version = "1.17.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7a/97/5a3609c4f8d58b039179648e62dd220f89864f56f7357f5d4f45c29eb2cc/scipy-1.17.1.tar.gz", hash = "sha256:95d8e012d8cb8816c226aef832200b1d45109ed4464303e997c5b13122b297c0", size = 30573822, upload-time = "2026-02-23T00:26:24.851Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/df/75/b4ce781849931fef6fd529afa6b63711d5a733065722d0c3e2724af9e40a/scipy-1.17.1-cp311-cp311-macosx_10_14_x86_64.whl", hash = "sha256:1f95b894f13729334fb990162e911c9e5dc1ab390c58aa6cbecb389c5b5e28ec", size = 31613675, upload-time = "2026-02-23T00:16:00.13Z" }, + { url = "https://files.pythonhosted.org/packages/f7/58/bccc2861b305abdd1b8663d6130c0b3d7cc22e8d86663edbc8401bfd40d4/scipy-1.17.1-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:e18f12c6b0bc5a592ed23d3f7b891f68fd7f8241d69b7883769eb5d5dfb52696", size = 28162057, upload-time = "2026-02-23T00:16:09.456Z" }, + { url = "https://files.pythonhosted.org/packages/6d/ee/18146b7757ed4976276b9c9819108adbc73c5aad636e5353e20746b73069/scipy-1.17.1-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:a3472cfbca0a54177d0faa68f697d8ba4c80bbdc19908c3465556d9f7efce9ee", size = 20334032, upload-time = "2026-02-23T00:16:17.358Z" }, + { url = "https://files.pythonhosted.org/packages/ec/e6/cef1cf3557f0c54954198554a10016b6a03b2ec9e22a4e1df734936bd99c/scipy-1.17.1-cp311-cp311-macosx_14_0_x86_64.whl", hash = "sha256:766e0dc5a616d026a3a1cffa379af959671729083882f50307e18175797b3dfd", size = 22709533, upload-time = "2026-02-23T00:16:25.791Z" }, + { url = "https://files.pythonhosted.org/packages/4d/60/8804678875fc59362b0fb759ab3ecce1f09c10a735680318ac30da8cd76b/scipy-1.17.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:744b2bf3640d907b79f3fd7874efe432d1cf171ee721243e350f55234b4cec4c", size = 33062057, upload-time = "2026-02-23T00:16:36.931Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/af933f0f6e0767995b4e2d705a0665e454d1c19402aa7e895de3951ebb04/scipy-1.17.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:43af8d1f3bea642559019edfe64e9b11192a8978efbd1539d7bc2aaa23d92de4", size = 35349300, upload-time = "2026-02-23T00:16:49.108Z" }, + { url = "https://files.pythonhosted.org/packages/b4/3d/7ccbbdcbb54c8fdc20d3b6930137c782a163fa626f0aef920349873421ba/scipy-1.17.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:cd96a1898c0a47be4520327e01f874acfd61fb48a9420f8aa9f6483412ffa444", size = 35127333, upload-time = "2026-02-23T00:17:01.293Z" }, + { url = "https://files.pythonhosted.org/packages/e8/19/f926cb11c42b15ba08e3a71e376d816ac08614f769b4f47e06c3580c836a/scipy-1.17.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:4eb6c25dd62ee8d5edf68a8e1c171dd71c292fdae95d8aeb3dd7d7de4c364082", size = 37741314, upload-time = "2026-02-23T00:17:12.576Z" }, + { url = "https://files.pythonhosted.org/packages/95/da/0d1df507cf574b3f224ccc3d45244c9a1d732c81dcb26b1e8a766ae271a8/scipy-1.17.1-cp311-cp311-win_amd64.whl", hash = "sha256:d30e57c72013c2a4fe441c2fcb8e77b14e152ad48b5464858e07e2ad9fbfceff", size = 36607512, upload-time = "2026-02-23T00:17:23.424Z" }, + { url = "https://files.pythonhosted.org/packages/68/7f/bdd79ceaad24b671543ffe0ef61ed8e659440eb683b66f033454dcee90eb/scipy-1.17.1-cp311-cp311-win_arm64.whl", hash = "sha256:9ecb4efb1cd6e8c4afea0daa91a87fbddbce1b99d2895d151596716c0b2e859d", size = 24599248, upload-time = "2026-02-23T00:17:34.561Z" }, +] + +[[package]] +name = "sentencepiece" +version = "0.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/15/15/2e7a025fc62d764b151ae6d0f2a92f8081755ebe8d4a64099accc6f77ba6/sentencepiece-0.2.1.tar.gz", hash = "sha256:8138cec27c2f2282f4a34d9a016e3374cd40e5c6e9cb335063db66a0a3b71fad", size = 3228515, upload-time = "2025-08-12T07:00:51.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d8/15/46afbab00733d81788b64be430ca1b93011bb9388527958e26cc31832de5/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:6356d0986b8b8dc351b943150fcd81a1c6e6e4d439772e8584c64230e58ca987", size = 1942560, upload-time = "2025-08-12T06:59:25.82Z" }, + { url = "https://files.pythonhosted.org/packages/fa/79/7c01b8ef98a0567e9d84a4e7a910f8e7074fcbf398a5cd76f93f4b9316f9/sentencepiece-0.2.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:8f8ba89a3acb3dc1ae90f65ec1894b0b9596fdb98ab003ff38e058f898b39bc7", size = 1325385, upload-time = "2025-08-12T06:59:27.722Z" }, + { url = "https://files.pythonhosted.org/packages/bb/88/2b41e07bd24f33dcf2f18ec3b74247aa4af3526bad8907b8727ea3caba03/sentencepiece-0.2.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:02593eca45440ef39247cee8c47322a34bdcc1d8ae83ad28ba5a899a2cf8d79a", size = 1253319, upload-time = "2025-08-12T06:59:29.306Z" }, + { url = "https://files.pythonhosted.org/packages/a0/54/38a1af0c6210a3c6f95aa46d23d6640636d020fba7135cd0d9a84ada05a7/sentencepiece-0.2.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:0a0d15781a171d188b661ae4bde1d998c303f6bd8621498c50c671bd45a4798e", size = 1316162, upload-time = "2025-08-12T06:59:30.914Z" }, + { url = "https://files.pythonhosted.org/packages/ef/66/fb191403ade791ad2c3c1e72fe8413e63781b08cfa3aa4c9dfc536d6e795/sentencepiece-0.2.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4f5a3e0d9f445ed9d66c0fec47d4b23d12cfc858b407a03c194c1b26c2ac2a63", size = 1387785, upload-time = "2025-08-12T06:59:32.491Z" }, + { url = "https://files.pythonhosted.org/packages/a9/2d/3bd9b08e70067b2124518b308db6a84a4f8901cc8a4317e2e4288cdd9b4d/sentencepiece-0.2.1-cp311-cp311-win32.whl", hash = "sha256:6d297a1748d429ba8534eebe5535448d78b8acc32d00a29b49acf28102eeb094", size = 999555, upload-time = "2025-08-12T06:59:34.475Z" }, + { url = "https://files.pythonhosted.org/packages/32/b8/f709977f5fda195ae1ea24f24e7c581163b6f142b1005bc3d0bbfe4d7082/sentencepiece-0.2.1-cp311-cp311-win_amd64.whl", hash = "sha256:82d9ead6591015f009cb1be1cb1c015d5e6f04046dbb8c9588b931e869a29728", size = 1054617, upload-time = "2025-08-12T06:59:36.461Z" }, + { url = "https://files.pythonhosted.org/packages/7a/40/a1fc23be23067da0f703709797b464e8a30a1c78cc8a687120cd58d4d509/sentencepiece-0.2.1-cp311-cp311-win_arm64.whl", hash = "sha256:39f8651bd10974eafb9834ce30d9bcf5b73e1fc798a7f7d2528f9820ca86e119", size = 1033877, upload-time = "2025-08-12T06:59:38.391Z" }, +] + +[[package]] +name = "sentry-sdk" +version = "2.74.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/8e/7f/1b16ab4aee53cc5db976bac12e6df5d562aae3880965200cef812e7121d9/sentry_sdk-2.74.0.tar.gz", hash = "sha256:dd91d75aacaef636006b579ac3ddb2fdbc9dce35f00f4b353b6b1b110c6b256a", size = 1081514, upload-time = "2026-11-05T14:50:27.444Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/55/b1/736d4b4b308694b0071844a533522ac06669ad61751687b94edfbf863f17/sentry_sdk-2.74.0-py3-none-any.whl", hash = "sha256:40b205af015649df3ec9986e057ce24ce85956bee3fb75efa72c93aa7036bdff", size = 549800, upload-time = "2026-11-05T14:50:25.767Z" }, +] + +[[package]] +name = "setuptools" +version = "80.9.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/18/5d/3bf57dcd21979b887f014ea83c24ae194cfcd12b9e0fda66b957c69d1fca/setuptools-80.9.0.tar.gz", hash = "sha256:f36b47402ecde768dbfafc46e8e4207b4360c654f1f3bb84475f0a28628fb19c", size = 1319958, upload-time = "2025-05-27T00:56:51.443Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a3/dc/17031897dae0efacfea57dfd3a82fdd2a2aeb58e0ff71b77b87e44edc772/setuptools-80.9.0-py3-none-any.whl", hash = "sha256:062d34222ad13e0cc312a4c02d73f059e86a4acbfbdea8f8f76b28c99f306922", size = 1201486, upload-time = "2025-05-27T00:56:49.664Z" }, +] + +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + +[[package]] +name = "smmap" +version = "5.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1f/ea/49c993d6dfdd7338c9b1000a0f36817ed7ec84577ae2e52f890d1a4ff909/smmap-5.0.3.tar.gz", hash = "sha256:4d9debb8b99007ae47165abc08670bd74cb74b5227dda7f643eccc4e9eb5642c", size = 22506, upload-time = "2026-03-09T03:43:26.1Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c1/d4/59e74daffcb57a07668852eeeb6035af9f32cbfd7a1d2511f17d2fe6a738/smmap-5.0.3-py3-none-any.whl", hash = "sha256:c106e05d5a61449cf6ba9a1e650227ecfb141590d2a98412103ff35d89fc7b2f", size = 24390, upload-time = "2026-03-09T03:43:24.361Z" }, +] + +[[package]] +name = "sympy" +version = "1.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mpmath" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, +] + +[[package]] +name = "threadpoolctl" +version = "3.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/56/97/b4748951a683e369513691c8eea33d100298d556308dcb0ab66b132a67f0/threadpoolctl-3.8.0.tar.gz", hash = "sha256:01080674ad7ac6182429c918a79de92da789bb448acc02fc0b620b1abd6b6137", size = 39424, upload-time = "2026-11-05T11:08:51.112Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/1b/831f2de4840a25db1dd7b1afea433ccafe6bb10aca07e13264f2079462d0/threadpoolctl-3.8.0-py3-none-any.whl", hash = "sha256:f1b49c82704d50f13ffae019c727b0fa4f6791a58f48f06a09c45face1be66da", size = 32091, upload-time = "2026-11-05T11:08:49.773Z" }, +] + +[[package]] +name = "tokenizers" +version = "0.13.3" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +sdist = { url = "https://files.pythonhosted.org/packages/29/9c/936ebad6dd963616189d6362f4c2c03a0314cf2a221ba15e48dd714d29cf/tokenizers-0.13.3.tar.gz", hash = "sha256:2e546dbb68b623008a5442353137fbb0123d311a6d7ba52f2667c8862a75af2e", size = 314856, upload-time = "2023-04-05T08:16:06.94Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7a/fe/003cb6ed585f1879d0eb5bedf80c0261efc351885027dffefbd86202d463/tokenizers-0.13.3-cp311-cp311-macosx_10_11_universal2.whl", hash = "sha256:56b726e0d2bbc9243872b0144515ba684af5b8d8cd112fb83ee1365e26ec74c8", size = 3975604, upload-time = "2023-04-05T08:15:33.475Z" }, + { url = "https://files.pythonhosted.org/packages/0c/e0/f51b2d52fcc2c64e0b81da0a1c68d57b3859212143dbc64b0d175ed78693/tokenizers-0.13.3-cp311-cp311-macosx_12_0_arm64.whl", hash = "sha256:cc5c022ce692e1f499d745af293ab9ee6f5d92538ed2faf73f9708c89ee59ce6", size = 3896389, upload-time = "2023-04-05T08:15:34.885Z" }, + { url = "https://files.pythonhosted.org/packages/09/6c/68f532b76033b7ef745777955ad0645069baa80cc0e47363432817323c53/tokenizers-0.13.3-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f55c981ac44ba87c93e847c333e58c12abcbb377a0c2f2ef96e1a266e4184ff2", size = 7450422, upload-time = "2023-04-05T10:13:20.375Z" }, + { url = "https://files.pythonhosted.org/packages/a6/cb/5ea65756be1cd97582fa0d3e466d20e041cf7e21ae47e5032a2b0c8a86db/tokenizers-0.13.3-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f247eae99800ef821a91f47c5280e9e9afaeed9980fc444208d5aa6ba69ff148", size = 8606313, upload-time = "2023-04-05T10:13:22.974Z" }, + { url = "https://files.pythonhosted.org/packages/92/85/74b09728fc3a34991595b103fb5d2c00801e2106f57b4306a4beab39354d/tokenizers-0.13.3-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:4b3e3215d048e94f40f1c95802e45dcc37c5b05eb46280fc2ccc8cd351bff839", size = 8204210, upload-time = "2023-04-05T10:13:25.001Z" }, + { url = "https://files.pythonhosted.org/packages/e9/d9/660f08ecd88bed54df9f85cab44e01184733c8e42d79b583fb985f1dc412/tokenizers-0.13.3-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9ba2b0bf01777c9b9bc94b53764d6684554ce98551fec496f71bc5be3a03e98b", size = 7778045, upload-time = "2023-04-05T08:15:37.039Z" }, + { url = "https://files.pythonhosted.org/packages/85/6d/5401879fc61526a48c20576ea85b8c6acfc0a67afdec18353522380e2e44/tokenizers-0.13.3-cp311-cp311-win32.whl", hash = "sha256:cc78d77f597d1c458bf0ea7c2a64b6aa06941c7a99cb135b5969b0278824d808", size = 3211955, upload-time = "2023-04-05T08:15:38.604Z" }, + { url = "https://files.pythonhosted.org/packages/62/41/93d3135ec30f596a71490ce11a73572190fe80e85a2aea18f116a520cc41/tokenizers-0.13.3-cp311-cp311-win_amd64.whl", hash = "sha256:ecf182bf59bd541a8876deccf0360f5ae60496fd50b58510048020751cf1724c", size = 3469503, upload-time = "2023-04-05T08:15:40.169Z" }, +] + +[[package]] +name = "tokenizers" +version = "0.22.2" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "huggingface-hub" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/97/5dbfabf04c7e348e655e907ed27913e03db0923abb5dfdd120d7b25630e1/tokenizers-0.22.2-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:544dd704ae7238755d790de45ba8da072e9af3eea688f698b137915ae959281c", size = 3100275, upload-time = "2026-01-05T10:41:02.158Z" }, + { url = "https://files.pythonhosted.org/packages/2e/47/174dca0502ef88b28f1c9e06b73ce33500eedfac7a7692108aec220464e7/tokenizers-0.22.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:1e418a55456beedca4621dbab65a318981467a2b188e982a23e117f115ce5001", size = 2981472, upload-time = "2026-01-05T10:41:00.276Z" }, + { url = "https://files.pythonhosted.org/packages/d6/84/7990e799f1309a8b87af6b948f31edaa12a3ed22d11b352eaf4f4b2e5753/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2249487018adec45d6e3554c71d46eb39fa8ea67156c640f7513eb26f318cec7", size = 3290736, upload-time = "2026-01-05T10:40:32.165Z" }, + { url = "https://files.pythonhosted.org/packages/78/59/09d0d9ba94dcd5f4f1368d4858d24546b4bdc0231c2354aa31d6199f0399/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:25b85325d0815e86e0bac263506dd114578953b7b53d7de09a6485e4a160a7dd", size = 3168835, upload-time = "2026-01-05T10:40:38.847Z" }, + { url = "https://files.pythonhosted.org/packages/47/50/b3ebb4243e7160bda8d34b731e54dd8ab8b133e50775872e7a434e524c28/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bfb88f22a209ff7b40a576d5324bf8286b519d7358663db21d6246fb17eea2d5", size = 3521673, upload-time = "2026-01-05T10:40:56.614Z" }, + { url = "https://files.pythonhosted.org/packages/e0/fa/89f4cb9e08df770b57adb96f8cbb7e22695a4cb6c2bd5f0c4f0ebcf33b66/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1c774b1276f71e1ef716e5486f21e76333464f47bece56bbd554485982a9e03e", size = 3724818, upload-time = "2026-01-05T10:40:44.507Z" }, + { url = "https://files.pythonhosted.org/packages/64/04/ca2363f0bfbe3b3d36e95bf67e56a4c88c8e3362b658e616d1ac185d47f2/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:df6c4265b289083bf710dff49bc51ef252f9d5be33a45ee2bed151114a56207b", size = 3379195, upload-time = "2026-01-05T10:40:51.139Z" }, + { url = "https://files.pythonhosted.org/packages/2e/76/932be4b50ef6ccedf9d3c6639b056a967a86258c6d9200643f01269211ca/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:369cc9fc8cc10cb24143873a0d95438bb8ee257bb80c71989e3ee290e8d72c67", size = 3274982, upload-time = "2026-01-05T10:40:58.331Z" }, + { url = "https://files.pythonhosted.org/packages/1d/28/5f9f5a4cc211b69e89420980e483831bcc29dade307955cc9dc858a40f01/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:29c30b83d8dcd061078b05ae0cb94d3c710555fbb44861139f9f83dcca3dc3e4", size = 9478245, upload-time = "2026-01-05T10:41:04.053Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fb/66e2da4704d6aadebf8cb39f1d6d1957df667ab24cff2326b77cda0dcb85/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:37ae80a28c1d3265bb1f22464c856bd23c02a05bb211e56d0c5301a435be6c1a", size = 9560069, upload-time = "2026-01-05T10:45:10.673Z" }, + { url = "https://files.pythonhosted.org/packages/16/04/fed398b05caa87ce9b1a1bb5166645e38196081b225059a6edaff6440fac/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:791135ee325f2336f498590eb2f11dc5c295232f288e75c99a36c5dbce63088a", size = 9899263, upload-time = "2026-01-05T10:45:12.559Z" }, + { url = "https://files.pythonhosted.org/packages/05/a1/d62dfe7376beaaf1394917e0f8e93ee5f67fea8fcf4107501db35996586b/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38337540fbbddff8e999d59970f3c6f35a82de10053206a7562f1ea02d046fa5", size = 10033429, upload-time = "2026-01-05T10:45:14.333Z" }, + { url = "https://files.pythonhosted.org/packages/fd/18/a545c4ea42af3df6effd7d13d250ba77a0a86fb20393143bbb9a92e434d4/tokenizers-0.22.2-cp39-abi3-win32.whl", hash = "sha256:a6bf3f88c554a2b653af81f3204491c818ae2ac6fbc09e76ef4773351292bc92", size = 2502363, upload-time = "2026-01-05T10:45:20.593Z" }, + { url = "https://files.pythonhosted.org/packages/65/71/0670843133a43d43070abeb1949abfdef12a86d490bea9cd9e18e37c5ff7/tokenizers-0.22.2-cp39-abi3-win_amd64.whl", hash = "sha256:c9ea31edff2968b44a88f97d784c2f16dc0729b8b143ed004699ebca91f05c48", size = 2747786, upload-time = "2026-01-05T10:45:18.411Z" }, + { url = "https://files.pythonhosted.org/packages/72/f4/0de46cfa12cdcbcd464cc59fde36912af405696f687e53a091fb432f694c/tokenizers-0.22.2-cp39-abi3-win_arm64.whl", hash = "sha256:9ce725d22864a1e965217204946f830c37876eee3b2ba6fc6255e8e903d5fcbc", size = 2612133, upload-time = "2026-01-05T10:45:17.232Z" }, +] + +[[package]] +name = "torch" +version = "2.13.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-bindings", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "nvidia-nvshmem-cu13", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "triton", marker = "sys_platform == 'linux' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, + { name = "typing-extensions" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/5b/fe/cba54dc58523434919b66f13a667e36e436deddd77ca519e96553617d4ec/torch-2.13.0-cp311-cp311-macosx_14_0_arm64.whl", hash = "sha256:e76f9bcecc52b8ff711239a2f7547d5353df95878ab232f0773c1d95928b92f8", size = 111187938, upload-time = "2026-07-08T16:05:17.065Z" }, + { url = "https://files.pythonhosted.org/packages/c2/59/1e3160e18e12aa3038390efab3ce02b36a9d4d6a527ecdd8520dca2e68d8/torch-2.13.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:092790c696a760c729fd5722835f50b9d81fd7c8f141571f3f3cf4081a8f664c", size = 427199369, upload-time = "2026-07-08T16:04:51.054Z" }, + { url = "https://files.pythonhosted.org/packages/01/79/1f2d34ad7034ee1c7ffc1cf8bf0f8213af2a81df6ecdb3997ecec107c09d/torch-2.13.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:60fcdcb2f3876e21146cb4524ef06397d727ca9ad5f020818547e25075fe3cb7", size = 526574961, upload-time = "2026-07-08T16:04:07.075Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fd/0f2ce40f58aefbdb3392f9acce3c8171940943ae2d661f70558bfa73befb/torch-2.13.0-cp311-cp311-win_amd64.whl", hash = "sha256:a0d8b11f16a48d60e2015d8213aa0390744cbebb98e58b62b3514dddc656e330", size = 122015870, upload-time = "2026-07-08T16:05:27.59Z" }, +] + +[[package]] +name = "tqdm" +version = "4.70.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32' or (extra == 'group-24-official-mezo-experiment-modern' and extra == 'group-24-official-mezo-experiment-native')" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0d/ea/b2a5bd54b28a324dae8211928b2d730b6547500342c7e6c6dea08bd0a485/tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4", size = 171846, upload-time = "2026-09-11T07:25:16.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" }, +] + +[[package]] +name = "transformers" +version = "4.28.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "filelock" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "requests" }, + { name = "tokenizers", version = "0.13.3", source = { registry = "https://pypi.org/simple" } }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0d/9f/0d27dec00839c14866d03c9992542d31992ef94d496765789234c9593e94/transformers-4.28.1.tar.gz", hash = "sha256:7334f8730cff7ac31d9ba5c12f2113fcb7a7a5b61eeb5dbbdb162117c3aaa2d1", size = 6007419, upload-time = "2023-04-14T16:55:55.624Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d8/a7/a6ff727fd5d96d6625f4658944a2ae230f0c75743a9a117fbda013b03d3d/transformers-4.28.1-py3-none-any.whl", hash = "sha256:f30a006220d0475789ac0e7c874f51bf5143956797616d89975b637883ce0be6", size = 6952278, upload-time = "2023-04-14T16:55:50.932Z" }, +] + +[[package]] +name = "transformers" +version = "4.57.1" +source = { registry = "https://pypi.org/simple" } +resolution-markers = [ + "sys_platform == 'linux'", + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'linux' and sys_platform != 'win32'", +] +dependencies = [ + { name = "filelock" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "requests" }, + { name = "safetensors" }, + { name = "tokenizers", version = "0.22.2", source = { registry = "https://pypi.org/simple" } }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/68/a39307bcc4116a30b2106f2e689130a48de8bd8a1e635b5e1030e46fcd9e/transformers-4.57.1.tar.gz", hash = "sha256:f06c837959196c75039809636cd964b959f6604b75b8eeec6fdfc0440b89cc55", size = 10142511, upload-time = "2025-10-14T15:39:26.18Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/d3/c16c3b3cf7655a67db1144da94b021c200ac1303f82428f2beef6c2e72bb/transformers-4.57.1-py3-none-any.whl", hash = "sha256:b10d05da8fa67dc41644dbbf9bc45a44cb86ae33da6f9295f5fbf5b7890bd267", size = 11990925, upload-time = "2025-10-14T15:39:23.085Z" }, +] + +[[package]] +name = "triton" +version = "3.7.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/f9/19d842d06a08559534fa1eaab6ca551b1bcf40f06620bddec1babaa2772d/triton-3.7.1-cp311-cp311-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d4a0e1cd4c4a76370ed74a8432a53cea28716827d19e40ffc732233e35ceb3f6", size = 184664887, upload-time = "2026-06-17T20:03:42.913Z" }, + { url = "https://files.pythonhosted.org/packages/cd/5e/fce69606f7f240297f163e25539906732b199530d486ce67ae319877e821/triton-3.7.1-cp311-cp311-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6744957e9fd610a29680ec2346057d0c86948ed3812468670719f391e94b44a5", size = 197701306, upload-time = "2026-06-17T19:53:13.673Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "typing-inspection" +version = "0.4.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ff/50/0195198eb1d75bab716bb0a813abea4cc394bfa17a92a189f021a34859af/typing_inspection-0.4.5.tar.gz", hash = "sha256:7f16c411e7930dc79596d42ab44672a3fe5f60eb34b781a1647e7872363120c7", size = 81194, upload-time = "2026-11-04T14:13:23.774Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/de/0c/ea2544850a7c135e15033a5c7a8e7211136184b7ae63e2239d557c2b3019/typing_inspection-0.4.5-py3-none-any.whl", hash = "sha256:bc210535442b39e1bf2805e0c7a17dfd6a4ace760c84c7f7d16245d23a6b1c39", size = 14874, upload-time = "2026-11-04T14:13:22.616Z" }, +] + +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + +[[package]] +name = "wandb" +version = "0.23.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "click" }, + { name = "gitpython" }, + { name = "packaging" }, + { name = "platformdirs" }, + { name = "protobuf" }, + { name = "pydantic" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "sentry-sdk" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0a/cc/770ae3aa7ae44f6792f7ecb81c14c0e38b672deb35235719bb1006519487/wandb-0.23.1.tar.gz", hash = "sha256:f6fb1e3717949b29675a69359de0eeb01e67d3360d581947d5b3f98c273567d6", size = 44298053, upload-time = "2025-12-03T02:25:10.79Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/12/0b/c3d7053dfd93fd259a63c7818d9c4ac2ba0642ff8dc8db98662ea0cf9cc0/wandb-0.23.1-py3-none-macosx_12_0_arm64.whl", hash = "sha256:358e15471d19b7d73fc464e37371c19d44d39e433252ac24df107aff993a286b", size = 21527293, upload-time = "2025-12-03T02:24:48.011Z" }, + { url = "https://files.pythonhosted.org/packages/ee/9f/059420fa0cb6c511dc5c5a50184122b6aca7b178cb2aa210139e354020da/wandb-0.23.1-py3-none-macosx_12_0_x86_64.whl", hash = "sha256:110304407f4b38f163bdd50ed5c5225365e4df3092f13089c30171a75257b575", size = 22745926, upload-time = "2025-12-03T02:24:50.519Z" }, + { url = "https://files.pythonhosted.org/packages/96/b6/fd465827c14c64d056d30b4c9fcf4dac889a6969dba64489a88fc4ffa333/wandb-0.23.1-py3-none-manylinux_2_28_aarch64.whl", hash = "sha256:6cc984cf85feb2f8ee0451d76bc9fb7f39da94956bb8183e30d26284cf203b65", size = 21212973, upload-time = "2025-12-03T02:24:52.828Z" }, + { url = "https://files.pythonhosted.org/packages/5c/ee/9a8bb9a39cc1f09c3060456cc79565110226dc4099a719af5c63432da21d/wandb-0.23.1-py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:67431cd3168d79fdb803e503bd669c577872ffd5dadfa86de733b3274b93088e", size = 22887885, upload-time = "2025-12-03T02:24:55.281Z" }, + { url = "https://files.pythonhosted.org/packages/6d/4d/8d9e75add529142e037b05819cb3ab1005679272950128d69d218b7e5b2e/wandb-0.23.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:07be70c0baa97ea25fadc4a9d0097f7371eef6dcacc5ceb525c82491a31e9244", size = 21250967, upload-time = "2025-12-03T02:24:57.603Z" }, + { url = "https://files.pythonhosted.org/packages/97/72/0b35cddc4e4168f03c759b96d9f671ad18aec8bdfdd84adfea7ecb3f5701/wandb-0.23.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:216c95b08e0a2ec6a6008373b056d597573d565e30b43a7a93c35a171485ee26", size = 22988382, upload-time = "2025-12-03T02:25:00.518Z" }, + { url = "https://files.pythonhosted.org/packages/c0/6d/e78093d49d68afb26f5261a70fc7877c34c114af5c2ee0ab3b1af85f5e76/wandb-0.23.1-py3-none-win32.whl", hash = "sha256:fb5cf0f85692f758a5c36ab65fea96a1284126de64e836610f92ddbb26df5ded", size = 22150756, upload-time = "2025-12-03T02:25:02.734Z" }, + { url = "https://files.pythonhosted.org/packages/05/27/4f13454b44c9eceaac3d6e4e4efa2230b6712d613ff9bf7df010eef4fd18/wandb-0.23.1-py3-none-win_amd64.whl", hash = "sha256:21c8c56e436eb707b7d54f705652e030d48e5cfcba24cf953823eb652e30e714", size = 22150760, upload-time = "2025-12-03T02:25:05.106Z" }, + { url = "https://files.pythonhosted.org/packages/30/20/6c091d451e2a07689bfbfaeb7592d488011420e721de170884fedd68c644/wandb-0.23.1-py3-none-win_arm64.whl", hash = "sha256:8aee7f3bb573f2c0acf860f497ca9c684f9b35f2ca51011ba65af3d4592b77c1", size = 20137463, upload-time = "2025-12-03T02:25:08.317Z" }, +] + +[[package]] +name = "xxhash" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c9/b5/3d11d3830ace56d67ea83136c24385c3b07da5a9bc62b73b0b94ac096da3/xxhash-4.1.0.tar.gz", hash = "sha256:c9b288e4c1f5dae54417bc8a05e6f6daf505783d916b4783f4dd2f2e7d5db486", size = 114122, upload-time = "2026-11-09T13:47:33.276Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d2/cb/da501f3abc32f8c3a6f0fb24f1988ec6b862897034a6f44bff92e06b6f29/xxhash-4.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:cf3e28ee18b17d253d85c0a0b3608b9b54f765df4af207722c1ce851f386a26d", size = 51515, upload-time = "2026-11-09T13:46:45.912Z" }, + { url = "https://files.pythonhosted.org/packages/5c/1d/112856c31d49a814854f19b3ecf8d81196a5b2d0c8cccbbe5a0cfe571e86/xxhash-4.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:796b8e5212ba90ebc8afac5ae3615502acd0d65363730cccd1d629b0fe7e87f6", size = 36825, upload-time = "2026-11-09T13:46:48.399Z" }, + { url = "https://files.pythonhosted.org/packages/40/37/fb258a692f0ecd93ff3af8f77a0122db1e33853f6c6c433cb841f46da13f/xxhash-4.1.0-cp311-cp311-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:822f6aa36f336f65188ae987b9627e843b6963f749d8a2a187f5b6fd72715088", size = 448119, upload-time = "2026-11-09T13:46:48.427Z" }, + { url = "https://files.pythonhosted.org/packages/2f/be/4e9efad09e3152cd437a6ad46148a9fe992f9bdfc1117808e71bc02178c4/xxhash-4.1.0-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f948b71013e0a0922176563dd4538967e2d7717b845bd61e0407f2e410962050", size = 274457, upload-time = "2026-11-09T13:46:46.078Z" }, + { url = "https://files.pythonhosted.org/packages/3a/11/177b6b4a781ae0a38e2d335b2a6bfe4e70c3e8edace541b1615da408d4ef/xxhash-4.1.0-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3fbf446e75b80f2a605b4b1637cb5bfdad5c317bc54ecd91ac7cb9e28314fe4b", size = 296295, upload-time = "2026-11-09T13:46:48.728Z" }, + { url = "https://files.pythonhosted.org/packages/30/d7/d59d72875eb268e83743ce507de3ce983a611e18c79d4d4169500932a747/xxhash-4.1.0-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:586ce49f8d73dc214f9da8e87824f332f2b4ddb7d15534736a2f906373b2030d", size = 273599, upload-time = "2026-11-09T13:46:49.98Z" }, + { url = "https://files.pythonhosted.org/packages/10/8a/3c85277e544cae7f6fa1dad71e23485b21d5695d3ac69a10ea46d3257896/xxhash-4.1.0-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b6b09351f73f6d0a3df59b02b9d2154a66fcc716fae8f0b8b2bdd63c42a1d2f6", size = 506958, upload-time = "2026-11-09T13:46:47.172Z" }, + { url = "https://files.pythonhosted.org/packages/b6/4f/5b195a79fafb6e9ab8e95229cc5346572a6cc40d6d6ed9227183a25315ea/xxhash-4.1.0-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5e713f5db9e1a8aafac59a45cc1ffce11ca507730f5dc12e212ea7b73d9debde", size = 471448, upload-time = "2026-11-09T13:46:47.314Z" }, + { url = "https://files.pythonhosted.org/packages/d8/6d/c34662fae63220b90d6803dab8fdc9240cf6cef06fbdea73fef0750ff438/xxhash-4.1.0-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:eadb2724470fd9507cb8f864c969d761dac7d549223ff15ff998c1c3c8e134d5", size = 337233, upload-time = "2026-11-09T13:46:49.72Z" }, + { url = "https://files.pythonhosted.org/packages/86/f7/7def1a3b835ef30b8f1a192405dd99db448922aeda8f45eb0359f00613c0/xxhash-4.1.0-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0119cf9ae630c5365596dd9dccf29932f364e8ef0f9162e1d7ef9df3e15ccb8e", size = 270274, upload-time = "2026-11-09T13:46:50.189Z" }, + { url = "https://files.pythonhosted.org/packages/bf/fb/677fef1a69b67c62eb12f71b7f49f801db1191df2f336d2930608f61c9f4/xxhash-4.1.0-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:3f580ff0d8dec8b495c6c6b281a89be3913158b01937281006993168b4375f84", size = 297452, upload-time = "2026-11-09T13:46:47.438Z" }, + { url = "https://files.pythonhosted.org/packages/95/15/5017ecacab16636c244e2cbd014cc56e17528caa736abcea4e151102e514/xxhash-4.1.0-cp311-cp311-musllinux_1_2_i686.whl", hash = "sha256:6179c5e008d2f1ca3a2e9c7935c021f84c5dc7516dfe5c9ee3edc0e9f26d20f0", size = 442167, upload-time = "2026-11-09T13:46:50.278Z" }, + { url = "https://files.pythonhosted.org/packages/45/0d/29c13f74ac43011aaafff9d9b23effefdf9243fcce764fed17087b1bd12c/xxhash-4.1.0-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:bdeaa333f8fbc237c5e62e0fb70e694dbfde62d15e242be23ba491ecd706e520", size = 271153, upload-time = "2026-11-09T13:46:51.737Z" }, + { url = "https://files.pythonhosted.org/packages/ef/89/d01eedb87d3ef1f7ec81080a160acd7ba42f29a43706b36d7fb4a8192706/xxhash-4.1.0-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:7c6bcd4eeeb5411a176b1a63dc505de99cd6182e88b02722d4407f96cf082e62", size = 327241, upload-time = "2026-11-09T13:46:48.482Z" }, + { url = "https://files.pythonhosted.org/packages/69/6a/82eb13aff0e06861cf2ff7a5b4e91092a3e7f7da5442c8be19e4c876d1a4/xxhash-4.1.0-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:9f200a2bc05bade88e7c50c28d2a6637468ff0bacbcf1720928ae55b905bb1af", size = 474740, upload-time = "2026-11-09T13:46:48.76Z" }, + { url = "https://files.pythonhosted.org/packages/64/eb/0859f45d7b690f44704f3d8dc9a6a00eea931bcb0f3c5f5da7799a8740bb/xxhash-4.1.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:e8b54cf9df8802572be9b8af0e3c1bc9eae80f653cd16f97d340a0098c48bb9c", size = 453590, upload-time = "2026-11-09T13:46:51.495Z" }, + { url = "https://files.pythonhosted.org/packages/18/99/e74773a5bc7b8decc874f0c74fb13e2058259101c6f54f87ecf07709e030/xxhash-4.1.0-cp311-cp311-win32.whl", hash = "sha256:b0042c684cf5739352d47afa77d387300805773a756f3677c1113481015934d6", size = 45112, upload-time = "2026-11-09T13:46:51.691Z" }, + { url = "https://files.pythonhosted.org/packages/5d/5f/299d6c8733add97f1b3e25f102dc473cd25b7ca147e6a828ec560c9740f2/xxhash-4.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:306a5538aa1152a3c411ebcce31a824721159495f391290ddcfa5b3f07c051a5", size = 48163, upload-time = "2026-11-09T13:46:48.804Z" }, + { url = "https://files.pythonhosted.org/packages/49/ee/e6d087e0fb37800c84ad842a4f6989ae3bc24964b63440fef1c89ec7f0e9/xxhash-4.1.0-cp311-cp311-win_arm64.whl", hash = "sha256:bf3ebcbed4efff1ec177385e4b906c8ba75881d975ea59f49aa6edc2d37752aa", size = 33410, upload-time = "2026-11-09T13:46:51.735Z" }, + { url = "https://files.pythonhosted.org/packages/c0/41/89fa8c4f2d1190f8a9efca46f5779bdb4481356aec35119529e1ba91d35c/xxhash-4.1.0-pp311-pypy311_pp80-macosx_10_15_x86_64.whl", hash = "sha256:d7a55bb01f866f948a4439e325e3e92645d97ca22c43777d2a71e7e51b63a986", size = 47341, upload-time = "2026-11-09T13:49:04.925Z" }, + { url = "https://files.pythonhosted.org/packages/93/5c/aa12a2f255cceb0941fa706d802bd502f64d42a76f17ea68ad62d860499b/xxhash-4.1.0-pp311-pypy311_pp80-macosx_11_0_arm64.whl", hash = "sha256:50e76857c8c47d8feb48ff1de711eaccfc5d28d97a5b1f7bd449b20796ecbf2b", size = 33938, upload-time = "2026-11-09T13:47:34.712Z" }, + { url = "https://files.pythonhosted.org/packages/c8/d1/d009e49747f1344c5c6fce52d67dfd53dfd0a0e75c4525abfc1dac44380b/xxhash-4.1.0-pp311-pypy311_pp80-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:49471b564ebae5d664daae4ecb2a02b03dc2e86f2065ed49f85e9367e8ca1428", size = 61619, upload-time = "2026-11-09T13:49:08.256Z" }, + { url = "https://files.pythonhosted.org/packages/9f/b7/473abf21c56969387bf90ac1d36bfbef620776bbe43a66ab4b1dc9fe0f1a/xxhash-4.1.0-pp311-pypy311_pp80-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2967f41d315ef1f9530af306ab79af7e5e6f3a4fdb3f02228bfc39414c11c273", size = 42795, upload-time = "2026-11-09T13:47:27.548Z" }, + { url = "https://files.pythonhosted.org/packages/e8/91/7981fb798edebeb130f95bd062f71f2512178af37925da889638ad63eb64/xxhash-4.1.0-pp311-pypy311_pp80-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0dcfb880344d6f1ed6feb867a898031b942f9c158f777c9ad678c078d7614b99", size = 47906, upload-time = "2026-11-09T13:47:30.555Z" }, + { url = "https://files.pythonhosted.org/packages/30/01/3876a8938f4dab623b501c77e874d7b3ac211fb1871e3bb236815dc66499/xxhash-4.1.0-pp311-pypy311_pp80-win_amd64.whl", hash = "sha256:100efa355bcc08b60a719926f9ce3c9ebf21cfa61db0a3bf43ebf64686d66ea3", size = 95476, upload-time = "2026-11-09T13:47:35.059Z" }, +] + +[[package]] +name = "yarl" +version = "1.25.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/75/16/e8be8e2fb175bbf41a0680381a319f1199fae256588241a2ac8677eafb49/yarl-1.25.1.tar.gz", hash = "sha256:03dd38de09bc213e9a8b29761eec33ee1d5318dac0e49d8af36e4d27830e23a7", size = 246245, upload-time = "2026-09-15T19:35:02.264Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/83/b3/2cea721d495ca57f8f414aa4867ee263f486b274e07463158cf52f02ba7f/yarl-1.25.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:9d693bf4bf534e9ba3ae2780cfd577f5135629f7b5ac653490859d0b77864865", size = 143794, upload-time = "2026-09-15T19:30:26.946Z" }, + { url = "https://files.pythonhosted.org/packages/55/e6/cd145cff8e5cf60b8b3c41fbecfa2a45028a8dec3fbc52bec03595ff3d3b/yarl-1.25.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:ab2054c5531af2a9ba7b69b8ec91e4f884420e83a8c5e579b013084cb57e5e5d", size = 103993, upload-time = "2026-09-15T19:30:28.661Z" }, + { url = "https://files.pythonhosted.org/packages/ce/7c/fbb40fe2d53747c40aa36a9e2bd2178a202f942bda0b670f3306d4aefbce/yarl-1.25.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:564fdc7085d2245ab84f88882fdb1d6ac0723124bff6ded35bfb1c00f812630d", size = 104010, upload-time = "2026-09-15T19:30:31.069Z" }, + { url = "https://files.pythonhosted.org/packages/f0/0b/5a516f70641092283f57cf3670bdb75e7327bcc0dcb5038697e4dfbfd569/yarl-1.25.1-cp311-cp311-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:acae6b45d1ace09b6ba3876da43b88366ef368f73b988c7f57e14231753d4420", size = 116444, upload-time = "2026-09-15T19:30:32.894Z" }, + { url = "https://files.pythonhosted.org/packages/b6/8a/d1a627f827b0a404ae0f5647cab0534959081cde13b0756a783469fb3b5e/yarl-1.25.1-cp311-cp311-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:1fb2a01ba8cd9c5d2c5dc1ec35e0fc951d04b4f037541d4ac090c993ce58b3d7", size = 107565, upload-time = "2026-09-15T19:30:35.188Z" }, + { url = "https://files.pythonhosted.org/packages/aa/cf/c8e0aaec886840a6c4480fe44eaec7cd4319f79a563b79321473be79c56f/yarl-1.25.1-cp311-cp311-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:e92b6bcc741b86d67606c40d3cb9c7cc8e6c737f81e31f4a94efc204456c92e3", size = 125006, upload-time = "2026-09-15T19:30:37.1Z" }, + { url = "https://files.pythonhosted.org/packages/50/26/0cce366d54a93cdc8342965dc7663385e4db161625cc1e8b18e786753d24/yarl-1.25.1-cp311-cp311-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:72c34ac7ad4314c19362d5ce27626dcc8429bd30bbf8c179f4234078851f9492", size = 128717, upload-time = "2026-09-15T19:30:38.904Z" }, + { url = "https://files.pythonhosted.org/packages/95/0c/a71501bbc1a674ff72c4d6c2b75f4d9a5af819f5244c3a7558080a8802c5/yarl-1.25.1-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d5add7b4ca7afeea91d52e4d4e4db3b1fe9885b71f07054560d8c4296b7441a2", size = 117728, upload-time = "2026-09-15T19:30:40.809Z" }, + { url = "https://files.pythonhosted.org/packages/e7/6f/c3267ca01defeed9ed9c4ff9b17bd54915432c405945233265b707475d1c/yarl-1.25.1-cp311-cp311-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:def538065f9e4d4cf1ae164bd59aba00dfa84f03923e0de4c3788f252d6bcd17", size = 116224, upload-time = "2026-09-15T19:30:42.818Z" }, + { url = "https://files.pythonhosted.org/packages/8f/69/fad57ee52d648431718ee0f1f68966a99c1352c3924688ffbdcc9d3fe51a/yarl-1.25.1-cp311-cp311-musllinux_1_2_aarch64.whl", hash = "sha256:0a191bfdb30a79b98e5d175d75285f9fcb78bf0e46ba5efda042e1c72071a0de", size = 116299, upload-time = "2026-09-15T19:30:44.966Z" }, + { url = "https://files.pythonhosted.org/packages/2a/d4/6a8c1e29f33338687ca278cba0a8fbf6525a322c2c02a9a500ccbe041152/yarl-1.25.1-cp311-cp311-musllinux_1_2_armv7l.whl", hash = "sha256:71f42c5b9a948c113bbdebfa544598321431d064ff959d32e99b1feb61d68345", size = 108625, upload-time = "2026-09-15T19:30:46.874Z" }, + { url = "https://files.pythonhosted.org/packages/e8/d2/3a35ae791c9cb6522c106923ff25c3230d999091e5e65511bca23bbd9914/yarl-1.25.1-cp311-cp311-musllinux_1_2_ppc64le.whl", hash = "sha256:72849d892954be4d09e569b8b831ac39ce58417fedc767d4308a0fe542018a40", size = 124515, upload-time = "2026-09-15T19:30:49.082Z" }, + { url = "https://files.pythonhosted.org/packages/be/fd/2b022109a6b4af0f7dc371cf7500af380b0d4f034010243e1b0ce218dc93/yarl-1.25.1-cp311-cp311-musllinux_1_2_riscv64.whl", hash = "sha256:efb01a106f971cb3752856bca2318bbdf7f01bd8823779c461586cbe5ffd5258", size = 115711, upload-time = "2026-09-15T19:30:51.208Z" }, + { url = "https://files.pythonhosted.org/packages/18/59/f7586271136c3ddb0126bbfe661844699369b76b555fe38c4efe86870b2e/yarl-1.25.1-cp311-cp311-musllinux_1_2_s390x.whl", hash = "sha256:a1daf47cd95a7c3a63456336bc5aaa8c86dd3a47d07ed3d0e76132ae4666a5a1", size = 122751, upload-time = "2026-09-15T19:30:53.535Z" }, + { url = "https://files.pythonhosted.org/packages/a0/0b/07f7a2d881f7e16c385b47fc1753382600847cad305dcc7fa0c25828acf8/yarl-1.25.1-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:9489e6abf47ba37f332075a91444c7cfedb03e6ce99fbb2f116bfe1ce810da3b", size = 117983, upload-time = "2026-09-15T19:30:55.277Z" }, + { url = "https://files.pythonhosted.org/packages/aa/9d/8cdceec66a9b940700cb45931741403f045b162afd79bcb93c41cadd0972/yarl-1.25.1-cp311-cp311-win_amd64.whl", hash = "sha256:d7306dee25b8a0e737363f347362b875094b4dc4e367311470656ae420fdbf8e", size = 102894, upload-time = "2026-09-15T19:30:57.606Z" }, + { url = "https://files.pythonhosted.org/packages/17/f1/7ec357db1d3ad2863542d71e8fe64a126bbec17b134cd7d30951196809a5/yarl-1.25.1-cp311-cp311-win_arm64.whl", hash = "sha256:abb1384477f5901d436b5d2e5465954de46ea6098f59163d243660b5c4461d35", size = 98609, upload-time = "2026-09-15T19:30:59.705Z" }, + { url = "https://files.pythonhosted.org/packages/54/22/318c7980066769c6bcd9221ed2248294f5698811da099013098c670565ed/yarl-1.25.1-py3-none-any.whl", hash = "sha256:681c758b0490f9e96b78e5fa8e8dc6e648e9185bb6eaebe73183c33ea0c445f3", size = 63617, upload-time = "2026-09-15T19:34:59.616Z" }, +] diff --git a/methods/CURVATURE_DESCENT_PLAN.md b/methods/CURVATURE_DESCENT_PLAN.md new file mode 100644 index 0000000..46865c1 --- /dev/null +++ b/methods/CURVATURE_DESCENT_PLAN.md @@ -0,0 +1,551 @@ +# Curvature-aware descent: derivation and implementation contract + +Current engineering execution: section 8 records the user's authorization to use +explicit local-curvature approximations and proceed with real-model experiments. +Certified reference status: a conditional forward-query algorithm is derived in section 6 and implemented +as OurTrainer.curvature_refresh / curvature_step, without enabling the real-model CLI. Its effective +upper-bound certificate is not established for the real model. No production implementation +or hyperparameter search may substitute unverified quantities for this contract. +The earlier `descent_gradient_proxy_v1` is withdrawn and is not a test of this theory. + +## 0. 对用户补充全文的核对(2026-11-12) + +原文假设 1.1 将 H 定义为分析用的有效二次上界,没有要求每个 ZO 算法 +显式构建 H。不能把“未计算出完整 H”作为所有实模实验的统一禁止条件。 +只有当算法声称实际优化给定各向异性 H 下的式 (2.3) 时,才需要给出该目标 +及其梯度所需量的获取方式。分析假设与算法实际调用的量必须分别列明。 + +全文给出了比较框架,而没有给出最大化 (2.3) 的低查询选基算法。 +以下两种目标不可混称为同一算法: + +- 采用 H=L I、固定参数子空间秩 k:式 (2.9) 的系数为正时,最大化 + D(P) 严格等价于最大化 s(P)。这是文档已证明的各向同性特例,不是 + 各向异性曲率目标的代理。若采用,必须明确声明该特例、学习率条件与 k。 +- 保留各向异性 (2.3):必须推导完整的选基估计器,不能用局部三点曲率 + 自动代替上界 H,也不能只实现 G'Gd 而宣称已优化全部曲率项。 + +单边误差已有原文接口,不必把理想公式硬说成精确有限差分公式。下面补出 +可直接代入 (1.9)-(1.10) 的一组充分条件,常数较松但每一步均可验证。 + +### 0.1 固定当前子空间下的单边与 batch 误差界 + +条件于选基历史及 U,要求当前训练 batch xi 与选基样本独立,方向独立于 +两者;U'U=I_k,z_i 独立同分布于 N(0,I_k)。以下期望、无偏条件 +E[g_xi]=g 及 Cov(g_xi)=Sigma 均条件于当前 +历史、theta 和 U;且各样本目标在所有查询线段上有 +统一梯度 Lipschitz 常数 L_f。对于无界高斯,该条件不能仅限于一个未控制 +逃逸概率的有限邻域。设 F 满足原文 H 的上界条件,H 在上述条件下固定且 +历史可测。 + +记 k=rank(P)、s=g'Pg、L_U=||U'HU||op、tau=tr(PH),并定义 + + B_mu = L_f^2 * mu^2/4 * k(k+2)(k+4) + C0 = (1+1/n)*L_U + tau/n + N_xi = (1+1/n)*tr(P H P Sigma) + tau/n * tr(P Sigma). + +同一个 batch 用于本次 n 个方向;各方向使用同一 batch 的 clean/plus 差分。 +把估计器写成 ghat=ghat_batch_ideal+r_mu。Taylor 余项满足 + + |e_i| <= L_f*mu/2 * ||z_i||^2 + E||r_mu||^2 <= B_mu. + +第二式用平均向量的 Jensen 不等式与高斯六阶径向矩成立,并没有假设 +e_i 条件零均值,也没有错误地将其均值按 1/n 消去。 +先对 batch 和方向精确取矩,再用 Cauchy-Schwarz/Young: + + A >= s - sqrt(s B_mu) >= s/2 - B_mu/2 + C_batch_ideal <= C0*s + N_xi + C <= 2*C0*s + 2*N_xi + 2*L_U*B_mu. + +故在相应常数沿轨迹有统一上界时,主定理接口可取 + + c = 1/2, C_master = 2*C0, + delta = B_mu/2, nu = 2*N_xi + 2*L_U*B_mu. + +这是充分上界,不是对 OPT 的常数估计或学习率建议,也不声称该界紧。 +浮点查询误差、额外函数噪声若存在,还要进入 r_mu 并控制相应矩。 + +非二次例子 F(x)=sin(x)、theta=0、P=1 满足全局 L_f=1,且 H=1 是 +有效上界。单边估计的均值为 exp(-mu^2/2),不同于真实梯度 1,故不能 +把一般 r_mu 的均值或与理想估计的交叉项设为零。测试用高阶高斯求积 +核对该解析均值及上述误差界;它不依赖二次函数的奇偶抵消。 + +### 0.2 选择与训练 batch 的独立性 + +原文 (2.16)-(2.19) 已明确:同一当前 batch 上先选 P 再训练,会产生 h_t。 +独立的方向 seed 只能消除选基与训练方向的复用,不能消除 batch 耦合。 +因此,若要使用 0.1 的独立性结论,刷新需要独立的选基样本,不能复用训练 +batch 的 f0 来节省一次 forward。若仍复用,必须控制 h_t 以及相应的 C_t。 +此前宣称“额外 4 次前向”并不能同时作为独立 batch 方案的预算。 + +HF RandomSampler 的 epoch 内无放回采样也不能直接认作条件独立的 iid +随机梯度 oracle。保持作者数据流时,要将随机重排分析作为额外理论任务, +或仅报告实验协议,不宣称上述条件收敛保证已经在实模上核验。 + +### 0.3 实验推进的准确门槛 + +继续保留单边 SGD。第 6 节保留各向异性目标,给出一种有证明的 H 构造和 +对应估计器;其全局光滑常数证书仍须针对实模建立。各向同性特例仍是另一 +明确目标,不能悄然替换。不能以未知 H 为由否定所有 ZO 实验。 +现有训练入口的 fix/adjust/历史 node 不因此自动成为命题 (2.3) 的优化器。 +只有在新选基步骤明确并通过对应测试后,才继续既定的调度和刷新参数实验。 + +## 1. Given-subspace objective (Proposition 2.1) + +At a fixed parameter point, let g be the objective gradient, H the symmetric effective +quadratic upper-bound matrix, P an orthogonal projector, and n the number of independent +Gaussian directions averaged in one weight update. n is not the batch size or refresh interval. +Set s = g'Pg, t = tr(PH), alpha = eta(1+1/n)/2, beta = eta/(2n). + + D(P) = s - alpha g'PHPg - beta s t + M(P) = gg' - alpha(HPgg' + gg'PH) - beta(t gg' + s H) + +M is the Euclidean projection gradient. P is constrained; M=0 is not the condition. +For P=UU', the tangent gradient is 2(I-P) M U. g and H stay fixed during selection. +This objective does not require third derivatives merely to differentiate P. + +## 2. Actual Linear parameterization + +For W with m output rows and k input columns, use row-major vectorization: + + P(d) = I_m kron (d d'), ||d||=1, rank(P)=m, s=||Gd||^2. + +This is not a rank-one parameter-space projector. Within a full-model block projector, +all other parameter blocks stay present. Contract the relevant diagonal output blocks +of M into C = sum_a M[a,:,a,:]. Then + + grad_d D = 2 C d + tangent_grad_d D = grad_d D - d (d' grad_d D) + d_next = normalize(d + rho tangent_grad_d D). + +Keep gradient magnitudes. No sign replacement, fixed-angle substitution, clipping, +or sampling normalization without a derivation and an explicitly agreed algorithm. +Updating d must not change W. Fresh training noise is independent of selection noise. + +## 3. Single-sided finite differences are an additional theory obligation + +Proposition 2.1 assumes ideal linear directional observations. Production training uses +`(F(theta+mu*u)-F(theta))/mu`. These are not identical at nonzero mu. + +On an exact quadratic whose Hessian equals H, write a=g'u and c=u'Hu. The observed +response is a+mu*c/2. Gaussian symmetry gives an exact corrected objective: + + D_mu(P) = D(P) - eta*mu^2/(8*n) T3(P) + T3 = t^3 + 6*t*tr((PH)^2) + 8*tr((PH)^3) + grad_P T3 = (3*t^2 + 6*tr((PH)^2))*H + + 12*t*HPH + 24*HPHPH. + +If H is merely an upper bound and K is the actual quadratic Hessian, the additional +moment is E[(u'Ku)^2 (u'Hu)], not E[(u'Hu)^3]. Do not silently identify H with K. +For nonquadratic losses, derive/control the remaining finite-difference bias and moments. + +Specifically, let ghat_0 denote the averaged ideal estimator and r the averaged +observation-error contribution, so ghat_mu=ghat_0+r. The same upper-bound argument gives + + D_bound(P) = D(P) + g' E[r] - eta E[ghat_0' H r] + - eta/2 E[r' H r] + E[F(theta_next)] <= F(theta) - eta D_bound(P). + +Replacing D(P) in the original guaranteed inequality by the displayed +expression is valid under the same upper-bound assumption; equality of this expression +with actual descent is not claimed. These extra terms cannot simply be omitted or +declared zero for a general neural-network loss. + +Counterexample to ignoring this issue: F(theta)=theta^2/2, theta=0, n=1. +Ideal D=0, but single-sided Gaussian SGD has +E[F(theta_next)] = 15*eta^2*mu^2/8 > 0. + +## 4. Real-model requirements for optimizing anisotropic (2.3) + +Section 6 resolves the formal estimator under stated oracle assumptions; it does not +establish those assumptions or a useful upper-bound certificate for OPT/SST2. + +Before exposing a new training mode, specify all of the following: + +1. Which objective g refers to (population/full training objective versus one batch). + A batch-dependent squared gradient includes covariance terms and cannot silently + replace a squared mean gradient. +2. For this anisotropic selection objective, how the chosen effective upper-bound H, + its required actions, and trace information are obtained within budget. H is not + automatically a runtime requirement of every algorithm covered by the framework. + A three-point directional curvature is + a local Hessian measurement; it is not a verified upper bound over actual updates. +3. A derived estimator for the complete structured basis gradient, with its sampling + covariance, normalization, finite-mu error, finite-delta error if used, and batch noise. +4. Actual forwards for each quantity, including any cross-moments and selection queries. + The old claim of four extra forwards is not a budget proof for this implementation. + +No full model snapshots, full-model stored noise, diagnostic backprop in training, or +unbudgeted oracle calls. Dense reference matrices are permitted only in small numerical tests. + +## 5. Acceptance tests and execution order + +Numerical reference tests (CPU float64; no model training/evaluation queries): + +- Evaluate Proposition 2.1 and independently differentiate with autograd in tests. +- Check structured basis gradient against directional finite differences, including + cross-output and fixed auxiliary blocks in the full P. +- Check the ideal Gaussian descent moments and the finite-mu correction using exact + Gauss-Hermite integration on small quadratic objectives. +- Check shared-batch covariance terms and the sufficient finite-difference bounds; + include a smooth nonquadratic example with analytically nonzero estimator bias. +- Verify the selection–batch coupling identity and the declared isotropic special case. +- Integrate the three-batch forward score against the complete anisotropic objective; + verify its 13-query selection cost, joint basis gradient limit, and nonquadratic bias. +- Verify the upper-bound inequality with a known PSD slack H-K, where applicable. +- Check basis retraction preserves unit norm, moves uphill locally for a small step, + and preserves the gradient's magnitude scaling. + +For a new mode claiming to optimize anisotropic (2.3), resolve section 4 first; +implement the complete agreed estimator in trainer.py; compare it to the reference +under controlled known models; verify budget, restoration, tied weights, and independent +RNG; perform a real-model short check. An explicitly chosen isotropic special case or +another algorithm must be validated against its own stated objective and assumptions. +After the chosen algorithm passes these checks, perform the authorized experiment +sequence: same-LR constant controls, +cosine starts at main query 3600/4200, matched fix control, refresh interval/basis-step +study, and finally separately derived weight decay. Keep 6000-query budgets and choose +hyperparameters with development data only. Do not mix historical protocols. + +The numerical reference does not establish section 4 for OPT/SST2 and must not be +presented as a production algorithm or a validation of real-model convergence. + +Verified on 2026-11-12: independent autograd, exact Gaussian quadrature, structured +directional finite differences, known-upper-bound inequality, and the single-sided +finite-radius counterexample pass. Test code is `tests/test_curvature_theory.py`; +the small-matrix reference is in `trainer.py`. Autograd is used only in these tests. + +## 6. 完整条件算法:各向异性上界目标的前向选基梯度 + +本节对应当前每步一个 Gaussian 方向,即 n=1。固定刷新时刻的 theta、eta, +令所有候选基共同使用同一个 H。目标仍为命题 (2.3),没有改成单 batch +梯度平方、实际虚拟更新收益或局部 Hessian 目标。训练继续使用单边差分。 + +### 6.1 先把完整目标写成可估计的标量期望 + +令 u=U(d)z,z~N(0,I_k),a=g'u,h=u'Hu。高斯矩给出 + + E[a^2] = s(P) + E[a^2 h] = 2*g'PHPg + s(P)*tr(PH). + +因此,在 n=1 时精确有 + + D(P) = E_z[a^2*(1-eta*h/2)]. (6.1) + +这同时保留方向曲率和曲率迹项,不需要分别存储 g、H 或 P。 +Linear 的 u_l=z_l d_l',z_l~N(0,I_out);dense 辅助参数保留完整高斯方向。 +两侧候选基必须使用同一个潜变量 z,包括所有固定基和 dense 辅助块。 +不能再将 u 归一化,否则 (6.1) 的高斯矩发生变化。 + +### 6.2 一种合法的可查询 H 构造 + +原文没有指定唯一 H。本节额外明确以下充分假设:F 二阶可微,且已知 +经过证明的全局常数 L>0,满足 ||Hess F(x)||op<=L;F 的函数值可由无偏 +独立训练 batch 查询。L 是上界证书,不是从几个观测拟合后随意调节的超参数。 +定义 K=Hess F(theta),并选择 + + H = K + 2*L*I. (6.2) + +由于 -L I <= K <= L I,对任意 x 都有 + + Hess F(x) <= L I <= H, L I <= H <= 3 L I. + +沿更新线段积分即得原文 (1.5),所以 H 为有效 PSD 全局上界,也适用于 +无界 Gaussian 更新。它保留 K 的各向异性,但通常保守;不宣称是最紧上界。 +这是本节新给出的充分构造,不是原文已提供的实模曲率结论。 + +只需估计 u'Ku,再加 2L||u||^2。若已有更紧且能合法查询 u'Hu 的 H, +可直接使用 (6.1),无需上述构造。仅函数查询不能识别任意选定的上界: +例如 F(x)=||x||^2/2 同时容许 H=I 和 H=diag(1,4),但两者给出不同 D。 +有限局部查询也不能验证未知函数在未查询区域的全局 L。 + +### 6.3 用独立 batch 的乘积估计总体目标 + +从训练分布独立抽取 A、B、C,三个 batch 的损失均满足 E[f_X(x)]=F(x)。 +独立抽样允许碰巧重叠;强制互斥抽样不自动等于独立。对固定 u 定义 + + a_A(u) = [f_A(theta+mu*u)-f_A(theta-mu*u)]/(2*mu) + a_B(u) = [f_B(theta+mu*u)-f_B(theta-mu*u)]/(2*mu) + c_C(u) = [f_C(theta+mu*u)-2*f_C(theta)+f_C(theta-mu*u)]/mu^2 + Y_mu(u) = a_A(u)*a_B(u)*[1-eta/2*(c_C(u)+2*L*||u||^2)]. (6.3) + +A、B 的独立性使方向响应的乘积估计总体响应平方,而不是其二阶矩。 +C 与 A、B 独立,使曲率乘积不再包含额外的 batch 协方差。不能把它们换成 +同 batch 的 a^2*c 而仍声称估计原式。两侧基允许共享同一组 A、B、C, +以减少差分方差;A、B、C 在组内仍独立。额外模型随机性必须纳入 oracle, +各组保持独立,组内各扰动查询配对固定随机性。 + +设总体中心差分均值为 a+b_mu、总体三点曲率为 u'Ku+e_mu,则条件于 u: + + E_ABC[Y_mu(u)] = (a+b_mu)^2 * [1-eta/2*(h+e_mu)]. (6.4) + +理想导数极限下 b_mu=e_mu=0,因此 E_zABC Y_0=D(P)。在精确二次目标上, +中心响应和曲率差分对任意非零 mu 都精确(精确算术下),故该恒等式直接成立。 +中心差分只用于选基目标的估计,不改变权重训练的单边更新。 + +### 6.4 有限 mu 的误差与所需矩条件 + +额外假设沿查询线段存在统一三、四阶导数界 M3、M4,或足够的高斯可积包络。 +仅 C4 和 L-smooth 并不自动提供有限全局 M3、M4。Taylor 展开给出 + + |b_mu| <= B(u) = M3*mu^2*||u||^3/6 + |e_mu| <= E(u) = M4*mu^2*||u||^4/12. + +由 (6.4),相对理想标量 a^2*(1-eta*h/2) 的误差至多 + + |1-eta*h/2|*(2*|a|*B+B^2) + eta/2*E*(|a|+B)^2. (6.5) + +对 z 积分得到 |D_mu(P)-D(P)|<=epsilon_mu,固定维度和上述常数时为 O(mu^2)。 +有限半径估计有显式可控偏差,不称作原 D 的有限半径无偏估计。 +还需 batch 方向响应及曲率的足够矩,令 Y_mu 和后续梯度估计二阶矩有限。 +总体 F 光滑并不自动保证随机 oracle 的方差有限。 +不对可能为负的随机曲率取绝对值、截断或裁剪,否则会改变期望目标。 + +### 6.5 联合切空间梯度估计 + +对所有拟更新的输入基 d_l 独立采 eps_l~N(0,I_in),投影到切空间: + + v_l = (I-d_l d_l') eps_l + d_l,+ = normalize(d_l+delta*v_l) + d_l,- = normalize(d_l-delta*v_l). + +不再归一化 v_l。用同一个内层 z 分别生成 u_+、u_-,并用同一组独立 +A、B、C 计算 (6.3)。定义 + + q = [Y_mu(u_+)-Y_mu(u_-)]/(2*delta) + b_hat_l = q*v_l + d_l,new = normalize(d_l+rho*b_hat_l). (6.6) + +保留 q 的大小与符号。rho 为基的学习率,delta 为基查询半径,mu 为权重 +查询半径;三者作用不同。换基不修改 W。可联合更新全部 Linear 基;若只 +选择部分层,须声明优化的是其余基固定后的限制问题,不能冒充全基优化。 + +证明其对应梯度:在当前 d 的联合切空间取正交坐标 x,维度 +p=sum_l(in_l-1),令 R_d(x) 为逐层归一化,f_mu(x)=D_mu(P(R_d(x)))。 +在交换微分和期望合法时,Gaussian 分部积分与对称性给出 + + E[b_hat] = grad_x E_v[f_mu(x+delta*v)] at x=0. (6.7) + +所以有限 delta 时,它对固定切空间坐标下的 Gaussian 平滑目标梯度无偏。 +不是对原始 D 的球面梯度无偏。若理想 pullback 的三阶导数范数上界为 T3, +则平滑偏差至多 T3*delta^2*p/2;若 (6.5) 对候选基一致成立,保守的总偏差为 + + ||E[b_hat]-grad_tangent D|| + <= T3*delta^2*p/2 + epsilon_mu*sqrt(p)/delta. (6.8) + +因此取 delta->0 且 mu^2/delta->0 可消除该偏差;没有额外 C1 误差证明时, +不能直接写 O(mu^2+delta^2)。浮点损失误差还会被 1/mu、1/mu^2、1/delta +放大,必须实测,不能被这段精确算术推导覆盖。 + +即使没有内层噪声,线性极限的单次 Gaussian 梯度估计也满足 +E||b_hat||^2=(p+2)||b||^2。联合多层并不增加前向次数,但可能显著增加方差。 +本流程每次只有一个联合方向,不擅自增加重复试探、筛选或确认步骤。 + +### 6.6 为什么这是改进方向,保证到什么程度 + +记真实切向梯度为 b,估计偏差上界为 e,E||b_hat||^2<=V,且当前 +retraction pullback 在更新范围满足梯度 Lipschitz 常数 L_D。则一次选基满足 + + E[D(P_new)-D(P)] + >= rho*||b||^2-rho*||b||*e-rho^2*L_D*V/2 + >= rho/2*||b||^2-rho/2*e^2-rho^2*L_D*V/2. (6.9) + +因此在偏差和方差代价足够小时,小步可提高期望理论下降量;单次随机基 +更新不保证一定提高 D,也不保证实际训练 loss 必降或得到全局最优基。 +原文理想权重更新的下降保证仍为 -eta*D(P_new)。实际单边 batch SGD +还包含第 0.1 节的误差与噪声,选基原 D 不等于自动优化这些附加项。 +已知 H<=3LI 时,理想条件可用 C<=3L(k+2);第 0.1 节那组保守有限差分 +常数允许 eta<=1/[12L(k+2)]。这些是充分界,不是 OPT 的学习率建议。 + +### 6.7 完整算法与查询预算 + +输入:初始化基、eta、rho、mu、delta、刷新间隔 r、主查询预算,以及已验证 +的 L/上界 oracle 条件。所有选择 batch 来自训练分布,不使用 dev/val。 + + 初始化各 Linear 的单位输入基;构基前向计入主预算。 + for t = 0, 1, ...: + 若达到刷新点且剩余预算容纳 13+2 次前向: + 固定当前 theta、eta、所有原基。 + 独立抽 A、B、C;采各层切向 v 和一个全模型潜变量 z。 + 构造基 d_+、d_-;按相同 z 生成 u_+、u_-。 + 查询 (6.3),得到 Y_+、Y_-;所有扰动均逆向恢复到 theta。 + q = (Y_+-Y_-)/(2*delta)。 + 每层 d <- normalize(d+rho*q*v),权重不变。 + 独立抽训练 batch 和新的 Gaussian 潜变量 z_train。 + u_train = U(d)*z_train。 + s_train = [f_train(theta+mu*u_train)-f_train(theta)]/mu。 + theta <- theta-eta*s_train*u_train。 + 记录训练/选基主查询;评估查询单独记录。 + +正常权重更新为 2 次。刷新时 A、B 各查询两基的 +/- 扰动,共 8 次; +C 查询两基的 +/- 扰动共 4 次,共享一次 f_C(theta),合计选基 13 次, +刷新步连同正常训练合计 15 次。R 次刷新、T 次权重更新且初始化 1 次时, +主预算为 Q=1+2T+13R。若已给出不需要 F 查询的精确 u'Hu oracle,选基 +降为 8 次 F 查询加 2 次上界 oracle 调用;不能把后者的真实成本隐去。 +确定性 F 没有 batch 乘积偏差时,两侧各三点共享 f0,只需 5 次选择查询, +但若 F 需遍历全训练集,每次 F 的全部 batch 前向都必须计数。 + +所有权重扰动使用相同 seed 按参数再生噪声并原地逆向恢复。不保存全模型 +副本、全模型噪声或反向图。只保存小基及其切向量、标量、种子。FP32 恢复 +允许舍入误差,不能声称逐位恢复。联合探测覆盖的方向及 ||u||^2 可流式计算。 + +当前保留 HF RandomSampler 的原训练协议;它不是本节条件 iid oracle 的 +自动实现。未来落地必须显式声明采样协议,不能暗改作者数据流以声称定理成立。 +本节给出了理论上闭合的条件流程;真实模型的 L/上界证书、可接受的方差和 +有限精度误差尚未建立,因此没有启动这套流程的实模调参。 + +实现对应:`curvature_refresh` 实现 (6.3)-(6.6),流式计算 Gaussian 方向范数, +只保存基、切向量与标量;`curvature_step` 实现刷新间隔、15 次预算预留、 +独立选择 seed 和普通单边权重更新。三个独立 batch 由调用方提供,函数无法 +仅凭张量值检查统计独立性。`certified_smoothness` 只检查数值合法性,不虚构证明。 +实际训练循环保持原协议,尚未分派到这个条件 API。 +`tests/test_curvature_steps.py` 用具有解析全局上界的二次模型验证真实函数实现, +覆盖分数、基更新、权重更新、预算、异常恢复、RNG 隔离及无完整权重克隆; +这些是数值验收而非 LLM 性能代理实验。 + +本轮数值验证:全套 68 项测试通过;新增三 batch 纯函数值查询与完整 D +的高斯矩核对、13 次选择查询计数、包含跨层曲率与 dense 辅助块的联合 +双基梯度极限、非二次 sin 目标的误差界及 O(mu^2) 收缩检验。主模型查询 +与评估模型查询均为 0。证明和测试不能替代真实模型上界证书。 + +## 7. 去掉全局 L 前提:可以推到哪里,哪些量仍不可省略 + +L 是第 6 节为实现 H 而引入的充分条件,不是用户需要提供的原始输入,也不是 +所有 ZO 实验的必要条件。原文需要有效 H;具体算法是否需要查询它取决于实际 +更新公式。MeZO 的分析使用局部曲率假设,权重更新本身不调用完整曲率上界。 +本项目新选基步骤直接优化 D_H,因而必须明确 H,不能把分析量的存在当作 +对算法查询的实现。以下是新的推导,尚未替换第 6 节条件 API。 + +### 7.1 未指定的上界不能从目标中一般性消去 + +令 K 为真实二次 Hessian,H_lambda=K+lambda I,投影秩 k 固定。则 + + D_lambda(P) = [1-eta*lambda/2*(1+(k+1)/n)]*s(P) + -eta/2*[(1+1/n)*g'PKPg+s(P)/n*tr(PK)]. + +lambda 乘的是随 P 改变的 s(P),不是可删除的常数。例: +K=diag(100,1),g=(sqrt(1.1),1),n=k=1,eta=0.0005。 +P0=e2 e2',P1=e1 e1'。H0=K 与 H500=K+500I 都是有效全局上界。 + + lambda=0: D(P0)=0.99925, D(P1)=1.0175 + lambda=500: D(P0)=0.62425, D(P1)=0.605. + +两种情形都满足所用投影上的保守 eta<=1/C 条件,但排序不同。即使函数值 +全部已知,也不能确定未指定的 H。改变 eta 抵消该系数同时改变权重更新, +不能称为原学习率下同一目标。优化实际虚拟更新收益也一般不是优化 D_H。 + +### 7.2 当前 OPT 的结构性全局增长包络 + +检查本地 config 与安装的源码:OPT-1.3B 使用 ReLU,decoder 有最终 LayerNorm, +hidden_size=word_embed_proj_dim=2048,没有 project_out。不能把 C4 全局 +光滑假设直接应用到 ReLU 参数空间。也不能仅因全局 Hessian 不有界就断言 +当前点不存在相切二次上界;以下拼接恰好可以绕开该过强要求。 + +LayerNorm 的归一化部分满足 ||q||2<=sqrt(h)。设输出头行范数最大值为 A, +最终 LayerNorm 参数为 gamma,beta,T=sqrt(h)||gamma||inf+||beta||2, +c=sqrt(h)+1。对唯一参数空间中任意 ||Delta||2=r(绑定权重只计一次): + + max_j ||W_j+Delta W_j||2 <= A+r + ||LN_output||2 <= T+c*r + ||logits||inf <= (A+r)*(T+c*r). + +token CE <= log(V)+2||logits||inf。当前 SST2 作者 wrapper 对平均 token +log-prob 做二选项 CE;每个 option 分数在 [-log(V)-2||logits||inf,0], +因此 loss <= log(2)+log(V)+2||logits||inf。故其总体目标有 + + 0 <= F(theta+Delta) <= a0+a1*r+a2*r^2 + a0=log(2)+log(V)+2*A*T + a1=2*(A*c+T), a2=2*c. (7.1) + +该界不要求内部注意力/MLP 权重有界,因为最终归一化控制了输出;不能应用 +到去掉最终 LN、有额外可训练 project_out 或其他未核对的架构。 +对当前检查点的只读分块扫描得到(浮点数是分析记录,不是向上舍入证书): +A≈3.55166360,||gamma||inf=1,||beta||2≈4.35554257, +a0≈363.91708848,a1≈427.78397403,a2≈92.50966799。 +未执行训练/评估模型前向。这个包络不是相切上界,不能直接作为第 6 节 L。 + +### 7.3 局部证书与全局包络拼接 + +假设在当前 theta 能由模型结构验证 R>0、ell_R>=0、G>=||g||,满足 + + F(theta+Delta)<=F(theta)+g'Delta+ell_R/2*||Delta||^2 + for ||Delta||<=R. + +令 + + q=max(ell_R, 2*a2+2*(a1+G)/R+2*a0/R^2). (7.2) + +内球由局部证书成立。外部 r>=R,由 (7.1)、F(theta)>=0 和 +-g'Delta<=G*r 得到余项/r^2<=a2+(a1+G)/R+a0/R^2。 +因此 H_iso=q I 是当前点对所有 Delta 有效的相切 PSD 上界。 +若当前点 Hessian K 存在且已证 ||K||op<=kappa,则 + + H=K+(q+kappa)I >= q I (7.3) + +是可用的各向异性上界。只需三点估 u'Ku 再加 (q+kappa)||u||^2, +无需全局光滑常数 L。它定义了一个明确的合法 D_H;不保证等于先前某个 +未被指定/验证的 H 所对应的目标。实现时必须明确推广为“已认证 shift”, +不能把 (q+kappa)/2 传作虚构的全局 L。 + +剩余证书不是从几个三点值取最大:对有限训练样本,可尝试验证所有 ReLU +preactivation 在半径 R 内保持符号,再对 smooth DAG(attention、LN、CE) +传播一、二阶算子界。需包括所有 token 和样本、LN epsilon、绑定权重及损失 +归一化。如果某点确在 kink,原文 g/K 或 C4 误差论证可能不成立,不能默认 +存在正半径。当前未完成这套 24 层网络的局部证书;(7.2) 中的 R、ell_R、G、 +kappa 不可用经验最大曲率代替。小 R 还可能令 1/R^2 项极大,证书即使成立 +也未必有用。尚不能据此宣布实模可运行。 + +### 7.4 选基差分不必要求全空间 C4,但需要局部/尾部误差分析 + +若当前点有上述无 kink 局部球,则在 ||u||<=R/mu 上使用局部 M3/M4 余项。 +外部用 (7.1) 控制函数值:记 A_mu=a0+a1*mu*||u||+a2*mu^2*||u||^2, +中心响应绝对值 <=A_mu/(2mu),三点曲率绝对值 <=2*A_mu/mu^2。 +于是误差可分为局部多项式 O(mu^2) 项与 Gaussian 尾部上的多项式矩。 +固定 R>0 时,该尾项随 mu->0 比任何 mu 幂更快消失;有限 mu 时必须显式 +计入,不能声称所有 Gaussian 查询都位于局部球。该论证适用于当前有限 +样本损失的统一包络/局部界,不自动替代 batch 独立性与有限精度验收。 + +### 7.5 实验与证明的结论 + +不需要用户给 L,也不必要求训练算法都计算全局上界。需要区分: +原文给定的 D_H 优化器需要可定义且可查询的 H;未知 H 不能保持原目标同时 +被删除。全局 L 可被 (7.1)-(7.3) 的结构证书替代,但本项目的局部证书尚未 +建立。当前已获得真实模型的增长包络,而不是完成了实模曲率认证。 +因此仍不将已有条件代码的数值验收称为正式实模实验,也不以三点局部曲率 +或实测最大值冒充原文上界。此前“实验都必须先知道全局 L”的表述撤回。 + +核对来源(只用于模型结构/现有方法事实,以上界与反例均为本项目推导): +- MeZO 原文 Assumption 1:https://openreview.net/pdf?id=CcsdvOOzMp +- LayerNorm 公式:https://docs.pytorch.org/docs/stable/generated/torch.nn.modules.normalization.LayerNorm.html +- OPT 官方源码:https://github.com/huggingface/transformers/blob/main/src/transformers/models/opt/modeling_opt.py + +## 8. 当前工程实验约定(用户澄清,2026-11-12) + +用户明确接受理论公式与工程实现有出入,以理论解释实测现象,允许开始实模实验。 +据此启用独立命名的 local_curvature_gradient_v1,不再以全局上界证书为开跑条件。 +第 6-7 节保留为严格保证的分析,不再将其中未满足的认证条件作为该工程变体的 +启动门槛。历史 sign/固定角度结果仍不能评价当前幅值梯度方案。 + +当前工程目标明确为 n=1 下的局部二阶下降模型: + + J_local(P)=s(P)-eta/2*[2*g'P K P g+s(P)*tr(P K)], K=Hess F(theta). + +在理想方向观测下,它等于 E[(g'u)^2*(1-eta*u'Ku/2)];对精确二次目标 +等于理想 ZO 的期望下降/eta。对非二次模型只作为局部 Taylor 模型解释, +不将 K 叫作 PSD 上界,也不把实训单边/batch 噪声省略后声称精确等式。 +复用第 6 节的三个独立 batch 与联合切空间估计,不添加 2L||u||^2 项。 +在ReLU场景仍采用有限查询响应,数值估计质量由真实刷新日志和开发集曲线检验。 + +实现入口为 `--trainer node --node_update local_curvature`。默认工程试验 +rho=1e-5、delta=1e-3、mu=1e-3、r=128;rho/delta 是显式工程参数, +不是从小二次测试推断的 LLM 最优常数。保留差商的幅值,不归一化 Gaussian +切向量,不裁剪或取绝对值处理曲率,不加入新旧基 gate。 + +数据样本、模板、损失及 HF RandomSampler 保持 MeZO 协议。独立选择 batch +来自训练池自己的 RNG;不用 dev/val 选基。全部 144 个 Linear 输入基联合更新, +每次刷新 13 次主前向,正常训练 2 次。评估单独计数。 + +执行顺序:300 主查询试跑验证实际刷新;3000 查询比较 eta=[1,1.5,2,3]e-6 +且固定其他参数与 constant schedule;仅按开发集末点 loss 选 eta;从原始检查点 +重新训练 6000 查询并保存标准 HF 权重。若真实试跑暴露工程问题,先记录并修正, +不得静默改成 sign、固定角度或隐藏额外查询。旧理论未认证不等于该工程研究不可执行。 diff --git a/methods/HISTORY_FREE_COVERAGE.md b/methods/HISTORY_FREE_COVERAGE.md new file mode 100644 index 0000000..206081f --- /dev/null +++ b/methods/HISTORY_FREE_COVERAGE.md @@ -0,0 +1,152 @@ +# 不依赖历史梯度的当前覆盖梯度估计 + +本方案的查询 API 为 `OurTrainer.coverage_gradient_probe`,完整更新为 `coverage_step`;显式入口 `--trainer node --node_update history_free`。原默认 node 仍使用回退后的历史构基。本文件的自动微分仅用于独立验证真值。2026-11-12 用户授权按短训选参、随后长训的顺序开展实模实验。 + +## 1. 固定什么,对什么求导 + +固定当前实际权重 θ 和当前 batch ξ 的标量损失 fξ。目标层 ℓ 的权重为 Wℓ∈R^(mℓ×pℓ),输入基 dℓ∈R^pℓ、||dℓ||=1,Gℓ=∇Wℓ fξ(θ)。定义 + + sℓ(dℓ)=||Gℓ dℓ||², + Πℓ=I-dℓ dℓᵀ, + grad sℓ=2 Πℓ GℓᵀGℓ dℓ. (1) + +对多个基的目标为这些覆盖量之和;其他固定基和 dense 部分的覆盖为常数。对 d 求导时 θ 固定,不对整个训练轨迹求导。输入侧 rank-1 基对应参数投影 I_m⊗ddᵀ,其参数子空间维度为 m。 + +旧方法先将历史系数梯度的 EMA 归一化成 p,再估计 Gᵀp。只有 p 对齐当前 Gd 时,才对应 GᵀG 的幂迭代。这里直接构造式 (1) 的估计,不使用历史梯度。 + +## 2. 两次普通训练查询提供什么 + +沿现有训练方向生成独立标准高斯系数 z_j:Linear 权重方向为 z_j d_jᵀ,dense 参数为原形状 Gaussian。把所有系数记为 Z,方向记为 u=UZ;在固定单位基和无重复参数条件下 U 是等距映射。记 a=Uᵀ∇fξ,其第 ℓ 块 aℓ=Gℓdℓ。 + + f0=fξ(θ), + fW=fξ(θ+μu), + rμ=(fW-f0)/μ. (2) + +两次前向后恢复权重。理想线性响应为 r0=aᵀZ。于是 E[r0²]=||a||²,E[r0 zℓ]=Gℓdℓ;但横向的 Gℓᵀ 作用仍未观测。 + +例如 d=e1、G1=(1,0)、G2=(1,c),训练方向都给出 r0=z,而球面梯度分别为 0 和 (0,2c)。因此仅由这两个函数查询不能一般恢复式 (1)。 + +## 3. clean 前向中的输入压缩 + +把目标层所有实际执行位置(包含 batch 行和 token)展开:Xℓ∈R^(Nℓ×pℓ) 为输入,Aℓ∈R^(Nℓ×mℓ) 为标量损失对节点输出的导数,则 + + Gℓ=AℓᵀXℓ. + +每层每个位置独立采样 Rademacher 符号 ηℓ,t∈{-1,+1},与 Z 独立。在式 (2) 的原始 clean 前向中计算并仅保存 + + vℓ=Xℓᵀηℓ=Σ_t ηℓ,t xℓ,t. (3) + +这只保存每层 pℓ 维向量。不能在后面的联合节点扰动前向中重新计算式 (3):下游输入已受到上游扰动。 + +fξ 是当前训练协议的实际标量 loss。batch/token 的平均已经包含在 Aℓ 内,式 (3) 必须求和,不能再次平均。MeZO SST2 实际有 2N 条候选输入,直接沿用作者标量 loss,不使用旧 residual×margin 近似。所有实际节点位置均取符号;排除 padding 只有在被排除位置的损失导数确实为零时才保持完整 Gℓ。 + +## 4. 一次联合节点查询 + +权重恢复到 θ 后,同时在选中的各层输出注入 + + hℓ,t ← hℓ,t + ε ηℓ,t zℓ, + fN=fξ(带上述节点注入的计算图), + nε=(fN-f0)/ε. (4) + +这里 zℓ 必须与式 (2) 的权重查询完全相同;各层 ηℓ 必须独立。η 可按层重放 seed,无需保存整个符号张量。理想节点响应为 + + n0=Σ_j η_jᵀ A_j z_j. + +由 E[ηℓηℓᵀ]=I、不同层符号零相关, + + Eη[n0 vℓ | Z]=XℓᵀAℓ zℓ=Gℓᵀzℓ. (5) + +定义最终估计 + + ĝ_dℓ = 2 Πℓ rμ nε vℓ. (6) + +理想线性响应下,先对 η 再对 Z 取期望: + + E[ĝ_dℓ]=2Πℓ Gℓᵀ E[zℓ Zᵀ] a + =2Πℓ GℓᵀGℓdℓ=grad sℓ. + +其他层和 dense 参数在权重响应中的贡献,因 Gaussian 块独立且零均值而消失,但仍增加方差。若节点使用独立 Gaussian z'ℓ,则希望得到的交叉矩消失,理想梯度均值变成零。 + +## 5. 单边查询的有限差分偏差 + +令节点注入函数为 φ(εV),V 的各块为 ηℓ zℓᵀ。vℓ 始终来自 clean,和 Z 无关。把所有 η 同时取反,则 V、vℓ 同时取反。因此精确成立 + + Eη[nε⁺vℓ | Z] = Eη[nεᶜvℓ | Z], + +其中 c 表示中心差分。这个条件均值关于全局 Z→-Z 为奇函数,再利用 Gaussian 对称性得到 + + E[rμ⁺ nε⁺ vℓ] = E[rμᶜ nεᶜ vℓ]. (7) + +这是均值恒等式,单个样本仍含单边误差,数值舍入也不会被精确消去。不需要为实现式 (6) 增加负扰动前向。 + +若权重切片和节点切片满足可积的三阶导数界 MW、MN,则中心差分余项满足 + + |er|≤MW μ²||u||³/6, + |en|≤MN ε²||V||³/6. + +式 (6) 的均值偏差范数上界为 + + MW μ²/3 E[||u||³ |n0| ||Πℓvℓ||] + + MN ε²/3 E[|r0| ||V||³ ||Πℓvℓ||] + + MW MN μ²ε²/18 E[||u||³ ||V||³ ||Πℓvℓ||]. (8) + +故偏差为 O(μ²+ε²+μ²ε²)。两个切片都恰为二次函数时,精确算术下均值偏差为零。实际网络的局部光滑区间、Gaussian 尾部、ReLU 拐点及浮点差分误差需要另行评估;小模型结果不建立实模全局光滑假设。 + +## 6. 联合节点查询省预算,但增加方差 + +若各层分别查询节点,只需把 n0 换成本层 nℓ=ηℓᵀAℓzℓ,均值仍相同。理想响应下两种估计的每层协方差之差为 + + Cov(ĝℓ_joint)-Cov(ĝℓ_separate) + =4 Πℓ XℓᵀXℓ Πℓ + ×[||a||² Σ_(j≠ℓ)||Aj||F² + +2 Σ_(j≠ℓ)||Aj aj||²] ⪰ 0. (9) + +证明:其他层的节点响应均值为零,与本层符号独立,故与本层估计的交叉矩为零;新增二阶矩为 4E[r0² Σ_(j≠ℓ)||Ajzj||²]ΠXᵀXΠ,再用 Gaussian 四阶矩即可。 + +多组 η 的平均只能降低节点条件方差,不能消除共用 Z 的方向方差。联合查询不必然在相同查询预算下更差或更好,需要比较相同成本下的误差。 + +## 7. batch 目标 + +同 batch 复用严格对应当前 batch 的覆盖。若 ξ 随机,其期望目标为 + + Eξ||Gℓ,ξ dℓ||²=||Gℓ dℓ||²+dℓᵀΓℓdℓ, + Γℓ=E[(Gℓ,ξ-Gℓ)ᵀ(Gℓ,ξ-Gℓ)]. (10) + +因此它也偏好梯度噪声能量。若要求总体梯度覆盖,可将权重响应放在独立 batch A,节点响应和输入压缩放在独立 batch B;在两者对当前 θ 均为无偏独立 oracle 的条件下,理想均值恢复 2ΠGℓᵀGℓdℓ。一般相关 A/B 的目标为 E[dᵀG_BᵀG_A d],梯度需要两个交叉项;仅在 A/B 交换对称时,乘 2 的估计才与其梯度对应。HF RandomSampler 的训练历史不自动满足独立 oracle 假设。 + +## 8. 查询次数与复用时序 + +设刷新 K 层,每层/每组符号独立;下表包含正常训练查询,未包含初始化校准和评估。 + +| 流程 | 总前向 | 比普通训练增加 | +|---|---:|---:| +| 普通单边训练 | 2 | 0 | +| 复用响应,逐层一次节点查询 | 2+K | K | +| clean 提前记录压缩量,一次联合节点查询 | 3 | 1 | +| 同一次 clean 记录 q 组压缩量,q 次联合节点查询 | 2+q | q | +| clean 已结束且未记录压缩量,需补 clean | 3+q | 1+q | +| 独立 A/B,B 另有 clean,一次联合节点查询 | 4 | 2 | +| 选基后本步立即按新基训练,复用同点同 batch 的 clean,另查独立新方向 | 4 | 2 | + +最低成本的逐步流程为: + +1. 固定 θt 和旧基 dt;采样 Z、η,安装 clean 读取 hook。 +2. 前向 f0,同时计算 vℓ;删除读取 hook。 +3. 按正常训练扰动 θt+μu,查询 fW,原地逆扰动恢复;得到 rμ。 +4. 在 θt 做一次联合节点前向 fN;删除注入 hook,得到式 (6)。 +5. 保持旧基,用已有 rμ、同一 Z 完成本次正常权重 SGD。 +6. 如以后接入选基,以幅值梯度作 d'ℓ=normalize(dℓ+ρ ĝ_dℓ),在第 5 步之后安装供下一步使用。 + +基梯度在 θt 计算,用于 θt+1 的下一次查询,存在一次权重更新的漂移。不能先换基再用旧 rμ 更新权重,也不能先更新权重再测节点而仍称两者对应同一点的梯度。若要求新基本步生效,须重新查询该新基的独立训练方向;同点同 batch、关闭随机 dropout 时 f0 可复用,所以共 4 次。 + +有限 ρ 下不保证每次 s 增长;估计方差、半径和基步长仍需研究。式 (6) 未控制曲率代价,不提供式 (2.3) 的下降保证。这里不增加 gate 或虚拟更新测试。 + +## 9. 数值验收 + +`tests/test_history_free_coverage.py` 使用实际小模型前向:两层独立 Linear,已知单位基,全局 Gaussian 两维;每维四点 Gauss–Hermite 求积及全部 16 组节点符号,得到 256 组加权估计。每组实际执行 3 次前向。对所用四次多项式目标,该求积精确积分相关多项式矩,剩余误差来自 FP64 算术。 + +验证线性/二次目标均值、光滑非二次目标 μ/ε 分别减半的偏差阶、式 (9) 的协方差、球面切向性、原有训练响应与 SGD 更新复用、原地恢复、异常 hook 清理及全局 RNG 不变。完整回归命令为 `.venv/bin/python -m pytest -q tests`。结果记录由 `scripts/validate_history_free_coverage.py` 写入共享 E 盘,诊断前向与实模训练查询分开记录。 + +2026-11-12 验收:自有测试 86 项通过,其中新增 7 项。线性目标均值最大绝对误差 1.11e-16,二次目标为 4.86e-17。非二次目标在固定另一半径为 1e-5 时,μ 从 .08/.04/.02 依次减半,偏差为 4.32534e-5/1.08133e-5/2.70334e-6;ε 分别减半时为 1.59941e-4/3.99853e-5/9.99632e-6,相邻比值均约 4。联合相对逐层节点查询的协方差差值与式 (9) 在 1e-11 绝对容差内一致;深层测试另验证下游 sketch 必须取 clean 输入。 + +审计结果位于 `E:/Experiments/Assets/results/history_free_coverage_audit_20261112T071429Z/validation.json`。独立审计脚本实际调用小模型诊断前向 6144 次,训练与评估查询均为 0;pytest 的小模型查询另由测试各自计数,不混入该脚本计数。四点求积精确积分四次目标的均值及线性目标的协方差;不宣称四次目标的协方差也由四点求积精确积分。 diff --git a/methods/README.md b/methods/README.md new file mode 100644 index 0000000..9b79f69 --- /dev/null +++ b/methods/README.md @@ -0,0 +1,236 @@ +# fix / adjust / node + +三种方法共用根目录的 uv 环境和一个 MeZO 风格入口,通过 `--trainer fix|adjust|node` 选择算法。 +代码全部在 `methods/large_models/`,不再分设方案目录或包装入口。 + +## 入口与环境 + +在 WSL 项目根目录运行: + +```bash +cd ~/experiments_codebase +source scripts/env.sh +uv sync --locked + +uv run --locked python methods/large_models/run.py --trainer fix +uv run --locked python methods/large_models/run.py --trainer adjust --refresh_every 256 +uv run --locked python methods/large_models/run.py --trainer node --refresh_every 128 + +# 模块入口与脚本入口等价 +uv run --locked python -m methods.large_models.run --trainer node --help +``` + +各基线继续使用 `baselines/<方法>/` 内的独立环境,不与根环境混用。 +依赖以根 `pyproject.toml` 和 `uv.lock` 为准。默认资源目录: + +| 内容 | WSL 路径 | +|---|---| +| 模型 | `/mnt/e/Experiments/Assets/models` | +| 数据 | `/mnt/e/Experiments/Assets/data` | +| 训练输出、日志、检查点 | `/mnt/e/Experiments/Assets/results` | + +通过根 `.env` 或 `EXPERIMENT_ASSETS` / `EXPERIMENT_MODELS` / `EXPERIMENT_DATA` / `EXPERIMENT_RESULTS` 覆盖。 +输出目录必须位于配置的 results 内,且每次运行使用新目录。写入前检查 E 盘挂载。 + +## 从哪里读代码 + +```text +methods/ + README.md + __init__.py + large_models/ + run.py 参数解析、模型加载、Framework、训练/推理入口 + trainer.py fix_step / adjust_step / node_step,预算、日志与保存 + _upstream_run.py 复用的 MeZO Framework、OurArguments 与任务数据流 + tasks.py MeZO 任务定义、样本与抽样 + templates.py 任务模板 + utils.py 编码、collator、候选答案 loss wrapper + metrics.py 作者预测评分实现 + assets.py 连接共享本地数据 + data.py 数据协议适配、随机种子与旧协议 sampler + native_losses.py MeZO loss 与节点探测所需任务分数 + losses.py legacy 数据协议的 loss + logging_utils.py 日志、曲线和显存记录 + MEZO_REUSE.json 复用来源、文件哈希与兼容修改 + LICENSE.MeZO 上游许可证 +``` + +训练循环在 `trainer.py` 中直接分派到三个 step。选基在 `top_basis` / `collect_basis`, +单边差分在 `zo_step`,实际权重更新在 `zo_update`,临时扰动与恢复在 `shifted`。 +`subspace.py`、独立的方案入口和 provenance 源码目录均已移除。 + +## 三种算法 + +所有方法先用一次校准前向提取各 Linear 输入激活的未中心化主方向。每层基 `D` 的形状为 `[din, 1]`。 +普通训练均沿单个高斯方向做两次前向和 SGD: + +```python +s = (F_plus - F_zero) / mu +# Linear: z.shape == [dout, 1] +W.add_((s * z) @ D.T, alpha=-lr) +``` + +Embedding、Norm、bias 等其余参数使用原张量形状的高斯方向;绑定的 embedding/head 只更新一次。 +当前只保存实际权重 `W`、输入基和 node 的历史,不维护 `W0/C/B/warm`。 +换基只替换 `D`,已学到的更新留在 `W` 中。 + +| 方法 | 刷新流程 | 默认刷新间隔 | 算法变体 | +|---|---|---:|---| +| fix | 初始化后固定基 | 不刷新 | `fix` | +| adjust | 一个激活候选,一次新旧基虚拟更新比较;新基参考 loss 更低就接受 | 256 次更新 | `adjust_single_probe_v1` | +| node | 历史系数梯度与节点扰动构基;直接替换有效候选,不比较新旧基 | 128 次更新 | `node_unconditional_refresh_control_v1` | + +2026-11-12 回退:默认 `--node_update original` 恢复此前无条件刷新版本,作为重新研究覆盖目标的起点。 +当前曲率版本仍保留为显式选项;本次回退不启动训练,也未实现新的选基估计器。 +回退前源码及测试备份位于 `E:/Experiments/Assets/results/node_coverage_rollback_20261112T065520Z`。 + +不依赖历史梯度的当前覆盖估计,完整推导和查询时序见 [HISTORY_FREE_COVERAGE.md](HISTORY_FREE_COVERAGE.md)。 +`coverage_gradient_probe` 在 clean 前向读取压缩输入,再复用普通权重查询,最后做一次联合节点查询; +合计 3 次前向,返回球面基梯度和待消费的旧基训练响应。 +2026-11-12 已接入 `coverage_step`:`--trainer node --node_update history_free --basis_lr 1e-5 --node_epsilon 1e-3 --zo_schedule constant`。 +每 128 次更新同时刷新所有 untied Linear 基,先用旧基完成 SGD,再安装 `normalize(d + basis_lr * gradient)`。 +保留幅值,不归一化 Gaussian、不取 sign、不使用 EMA、曲率项或新旧基 gate。 +一次刷新总步成本 3 次(普通训练 2 次加节点 1 次);预算不足 3 次时继续普通 2 次更新。 +数值验证用 `.venv/bin/python scripts/validate_history_free_coverage.py`,相关回归位于 `tests/test_history_free_coverage.py`。 + +2026-11-12 检查点协议对齐:默认 `select_best_checkpoint=true`,按每次更新后 development 评估的最小 loss +保存 `best_model/`,相同 loss 保留较早检查点;训练初始评估不参与选择。 +训练继续沿当前权重进行,结束后将 development 最佳权重逐张量载回原模型,再评估 SST2 官方 validation。 +`best_checkpoint.json` 记录所选步数、实际主查询数和 development 指标;最终 `model/` 导出所选权重。 +`--no-save-checkpoint` 仅省略最终 `model/` 副本,仍保存选优所需的 `best_model/`。 +显式 `--select_best_checkpoint false` 可恢复旧的末点权重评估协议;两种协议的结果应分别标记。 +这些 HF 权重仅支持推理和评估,不包含子空间、sampler 或 RNG 的训练续跑状态。 + +2026-11-12:此前 `descent_gradient_proxy_v1` 未忠实实现约定推导,已撤下活动入口。其历史源码和结果仅作问题追溯,不能用于评价命题 2.1。曲率感知选基的推导、实现前提与验收计划见 [CURVATURE_DESCENT_PLAN.md](CURVATURE_DESCENT_PLAN.md)。 + +原文的 `H` 是分析用的有效二次上界,不要求所有训练算法显式计算它。 +若新选基算法要优化式 (2.3) 的各向异性目标,则仍须说明完整目标的估计方式。 +当前已补充单边差分与 batch 噪声的充分误差界,并用小规模数值测试验证;这不等于完成实模选基实现。 + +[计划第 6 节](CURVATURE_DESCENT_PLAN.md#6-完整条件算法各向异性上界目标的前向选基梯度) +现给出 `n=1` 的完整条件流程:在已知有效全局光滑常数 `L` 时,采用 +`H = Hess F(theta) + 2 L I`,用三个独立训练 batch 估计总体下降目标,再做联合切空间基梯度更新。 +一次选择需 13 次主前向,连同正常单边训练为 15 次。 +`trainer.py` 已实现条件 API `curvature_refresh` / `curvature_step`,包括完整预算预留、 +独立选择/训练 seed、分数差幅值更新及日志。调用者须提供三个独立 batch 和经过证明的 +`certified_smoothness`;数值为正不代表通过上界认证。 +该上界证书尚未针对实模建立,不能把 `L` 当作随意调节的参数;测试通过也不代表实模前提成立。 +全局 `L` 并非必要:计划第 7 节已从当前 OPT 的最终 LayerNorm 推导全局损失增长 +包络,并给出与局部证书拼接的有效上界构造。当前模型使用 ReLU,需要处理局部 +可微范围及 Gaussian 尾部,不能直接使用全局 C4 假设。局部证书尚未建立,包络 +系数不能冒充曲率常数。任意未知 `H` 也不能从式 (2.3) 中一般性消除。 +2026-11-12 用户进一步明确允许工程近似实验。当前可用 +`--trainer node --node_update local_curvature --basis_lr 1e-5 --basis_radius 1e-3` +运行 `local_curvature_gradient_v1`:以局部 Hessian 替代分析上界,不加未经证明的 +平移常数;保留完整基梯度幅值、三个独立选择 batch、全部 Linear 的联合基更新。 +权重训练继续使用作者 HF RandomSampler 和单边差分,选择 batch 独立抽样但不宣称 +整个训练历史满足 iid 条件。该工程目标用于检验覆盖/曲率权衡,不能宣称已验证 +命题的全局下降保证,也不复用历史 sign/固定角度代理结果。 +此前已完成该变体的短训选参和 6000 主查询长训;所有选择前向计入预算。 +以下默认 node 的历史构基与这一曲率变体是不同算法。 + +adjust 的一次比较使用配对随机方向,在训练池的参考 batch 上比较虚拟 SGD 更新后的 loss。 +node 用历史系数梯度方向和节点扰动为三个 `v_proj` 层产生候选;目标层由 `configure_history` 选择,并写入参数清单。 +`history_beta=0.9` 仅用于 node 选基,不是 SGD 动量。替换后清空所换层的历史;无有效候选的层保留原基和历史。 + +令当前单层梯度为 `G`、输入基为 `d`,旧构基的理想线性响应对应: + +```python +h = beta * h + (1 - beta) * coefficient_gradient_estimate # 当前目标为 G @ d +p = h / h.norm() +b = node_sketch(p) # 理想条件下估计 G.T @ p +d_new = b / b.norm() +``` + +每层两次节点扰动用于估计向量 `G.T @ p`,不是直接估计标量 `s(d) = ||G @ d||^2`。 +只有当 `p` 对齐当前 `G @ d` 且忽略估计误差时,归一化构基才对应一次 `G.T @ G` 幂迭代。 +历史梯度随参数、数据和基变化会失配;纯覆盖构基也没有控制有限学习率下的曲率代价。 +这两项是下一阶段需要推导和验证的问题,不能把回退当作已经修复它们。 +原来的三点 `descent_probe` 保留为数值参考;默认 node 不再调用它。 +当前没有半程插值、重复比较、SEM 门槛或独立复核;旧的 `probe_pairs`、`gate_k`、`gate_margin`、`node_variant` 参数已删除,传入会报错。 + +## 查询预算和显存 + +主预算为 `training + calibration`;评估查询独立计数。一次查询指对整个 collated batch 执行一次模型前向。 +MeZO SST2 中每个样本有两条候选序列,因此一次查询的耗时不能直接等同于单序列读出协议。 + +| 操作 | 主前向次数 | +|---|---:| +| 初始校准构基 | 1 | +| 普通参数更新 | 2 | +| adjust 一次刷新检测 | 1 次构基 + 5 次虚拟更新比较 = 6 | +| node 一次刷新 | 默认至多 7 次节点构基,无新旧基检测 | + +node 构基上界为 `1 + 目标层数 * node_queries`,默认三层、每层两次;开头的 1 次 clean 由各层共享。 +刷新前会预留完整构基预算和下一次更新的 2 次前向,不足时继续普通训练;实际成本写入 `refresh.jsonl`。 +`main_forward_budget` 是主要停止条件,`max_steps` 可进一步限制参数更新次数。 + +对当前训练方向,若已有 `F0/F+`,补 `F-` 只多一次前向。历史三点门控比较旧、新两个基需共享 +`F0` 加四次扰动查询,共五次,候选构造另计;回退后的默认 node 不支出这五次查询。 + +参数表示标记为 `direct_weights_inplace_v2`。扰动原地加到 `W`,随后按同一种子重新生成噪声并反向减回。 +不备份完整权重,不保存全模型噪声张量;前向异常时也执行反向恢复。 +FP32 加减不保证逐位恢复,误差会影响后续差分;当前没有真实模型峰值显存测量。 + +## 常用参数 + +| 参数 | 默认值或用途 | +|---|---| +| `trainer` | `fix`;可选 `adjust`、`node` | +| `model_name` / `task_name` | `facebook/opt-1.3b` / `SST2`;也支持本地模型目录、`Qwen/Qwen3-0.6B` 和 `DROP` | +| `data_protocol` | `mezo` | +| `main_forward_budget` | 6000,含构基和检测 | +| `num_train` / `num_dev` / `num_eval` | 1000 / 500 / 872 | +| `per_device_train_batch_size` / `per_device_eval_batch_size` | 16 / 16 | +| `calibration_samples` / `max_length` | 16 / 128 | +| `learning_rate` / `zo_schedule` | fix、adjust 为 `1e-6` / `constant`;node 为 `1.5e-6` / `cosine` | +| `decay_start` / `lr_min` | 主查询 3000 后开始余弦衰减,默认最低为初始学习率的 0.1 倍 | +| `zo_eps` | 权重扰动幅度,默认 `1e-3` | +| `node_queries` / `node_epsilon` | 每层节点探测次数 2 / 节点扰动幅度 `1e-3` | +| `eval_main_forwards` | 每到约 600 次主前向后评估;不是更新步数 | + +短参数 `--method/--model/--task/--budget/--lr/--mu` 仍有对应别名。完整参数以统一入口的 `--help` 为准。 +公平比较时显式对齐学习率、调度、刷新层范围、采样和总预算。 + +```bash +uv run --locked python methods/large_models/run.py --trainer node \ + --model_name Qwen/Qwen3-0.6B --task_name DROP \ + --per_device_train_batch_size 2 --per_device_eval_batch_size 2 --max_length 512 +``` + +## 数据协议 + +默认 `mezo` 使用作者的抽样、任务模板、候选编码和目标函数;调用复用的 `Framework.train`, +使用 HF RandomSampler,保留尾批。SST2 比较两个候选答案的似然,DROP 对有效答案 token 计算 batch loss。 +预测评分调用作者的 `Framework.evaluate/metrics.py`;其 DROP 文本 F1 不等于 DROP 专用数字/多跨度官方评分。 + +显式 `legacy` 使用旧数据抽样、PCG batch 顺序、padding 和 loss:SST2 双标签读出 CE,DROP 按样本平均答案 CE,丢弃尾批。 +它只切换数据协议,不恢复旧优化器或权重表示。旧的 `.pt` 检查点不受当前入口支持。 + +比较结果前对齐 seed/train_set_seed、样本量、长度和 batch size,并核对 `data_manifest.json`。 +不同数据协议、参数表示或算法变体的缓存不能混用。`reports/` 中早期系数实现的逐值等价结果属于历史记录。 + +## 输出与推理 + +每次运行保存有效参数、环境、协议变体、源码和数据指纹,以及: + +- `records.jsonl`:训练 loss、响应、更新范数、学习率、累计主查询数。 +- `refresh.jsonl`:候选检测结果、是否接受及实际查询成本。 +- `curve.json`、曲线图和 `progress.json/md`:评估点、耗时、显存及实际查询计数。 +- `query_ledger.json`、`summary.json`:主查询与 evaluation 等分类计数。 +- `model/`:默认直接调用 `save_pretrained` 保存标准 HF 模型;无偏移合并步骤。 + +`--no-save-checkpoint` 可只保存记录;当前检查点用于推理,不支持断点续训。 + +```bash +uv run --locked python methods/large_models/run.py --trainer node --action evaluate \ + --checkpoint /mnt/e/Experiments/Assets/results/RUN/model +uv run --locked python methods/large_models/run.py --trainer node --action generate \ + --checkpoint /mnt/e/Experiments/Assets/results/RUN/model --prompt 'Hello' +uv run --locked pytest tests +``` + +WSL 需正常的 NVIDIA 驱动和 git/curl/ca-certificates/libgomp/libstdc++;普通运行不要求 nvcc。 +只支持单设备 FP32、rank=q=1、无 weight decay、裁剪和梯度累积。继承的 HF 参数不代表所有 HF 功能都可用。 +MeZO 原版 Trainer 依赖旧私有 API;当前继承受支持的 HF Trainer,保留作者 `zo_forward`,兼容修改见 `MEZO_REUSE.json`。 +测试验证数值机制和入口行为,不代表完整 benchmark 或论文性能复现。 diff --git a/methods/__init__.py b/methods/__init__.py new file mode 100644 index 0000000..8405c88 --- /dev/null +++ b/methods/__init__.py @@ -0,0 +1 @@ +"""MeZO-style implementation of fix, adjust and node.""" diff --git a/methods/large_models/LICENSE.MeZO b/methods/large_models/LICENSE.MeZO new file mode 100644 index 0000000..61d8849 --- /dev/null +++ b/methods/large_models/LICENSE.MeZO @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Princeton Natural Language Processing + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/methods/large_models/MEZO_REUSE.json b/methods/large_models/MEZO_REUSE.json new file mode 100644 index 0000000..c587846 --- /dev/null +++ b/methods/large_models/MEZO_REUSE.json @@ -0,0 +1,96 @@ +{ + "commit": "552cb1b710767f9a6e1dc8f9645d7640376f9941", + "files": { + "templates.py": { + "upstream": "baselines/mezo/large_models/templates.py", + "upstream_sha256": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6", + "reused_sha256": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6", + "changes": [] + }, + "metrics.py": { + "upstream": "baselines/mezo/large_models/metrics.py", + "upstream_sha256": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c", + "reused_sha256": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c", + "changes": [] + }, + "tasks.py": { + "upstream": "baselines/mezo/large_models/tasks.py", + "upstream_sha256": "693c28ccc7e02997a7dced601f15a89d67a514581f98d1bc642768ef3271ed58", + "reused_sha256": "11f2904364f63f462aebb64adc191dc59fb0e0ad632c474f80c1d8617af45376", + "changes": [ + { + "old": "from templates import *", + "new": "from .templates import *" + }, + { + "old": "from utils import temp_seed", + "new": "from .utils import temp_seed" + }, + { + "old": "from datasets import load_dataset", + "new": "from .assets import load_dataset" + } + ] + }, + "utils.py": { + "upstream": "baselines/mezo/large_models/utils.py", + "upstream_sha256": "04686e63041fcc9efce7284ead16c8b5a5aa6f6e648ede447b587cad9531b0aa", + "reused_sha256": "2b4df62167638e61f63ab7d90857d0d7114bb656f84b61f8e4f4ff68d0495570", + "changes": [ + { + "old": "if tokenizer.add_bos_token:", + "new": "if getattr(tokenizer, \"add_bos_token\", False):" + } + ] + }, + "_upstream_run.py": { + "upstream": "baselines/mezo/large_models/run.py", + "upstream_sha256": "00b864c0e53c28f02572a510e6d612bfcca38682be843054bc1806354815bd81", + "reused_sha256": "32d6dc17ab9da185912c813b80487ce2db28fd213ac31b03cab6c801e9d742ec", + "changes": [ + { + "old": "import tasks", + "new": "from . import tasks" + }, + { + "old": "from tasks import get_task", + "new": "from .tasks import get_task" + }, + { + "old": "from metrics import calculate_metric", + "new": "from .metrics import calculate_metric" + }, + { + "old": "from utils import *", + "new": "from .utils import *" + }, + { + "old": "from trainer import OurTrainer", + "new": "from .trainer import OurTrainer" + }, + { + "old": "free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3)", + "new": "free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) if torch.cuda.is_available() else 0" + }, + { + "old": "config=config,\n )", + "new": "config=config,\n torch_dtype=torch.float32, attn_implementation=\"eager\", local_files_only=True,\n )" + }, + { + "old": "tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast=False)", + "new": "tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast=\"qwen\" in self.args.model_name.lower(), local_files_only=True)\n if tokenizer.pad_token_id is None:\n tokenizer.pad_token = tokenizer.eos_token" + }, + { + "old": "if self.args.save_on_interrupt:\n trainer.add_callback", + "new": "self.trainer = trainer\n if self.args.save_on_interrupt:\n trainer.add_callback" + } + ] + } + }, + "trainer_reuse": { + "upstream": "baselines/mezo/large_models/trainer.py:OurTrainer.zo_forward", + "ast_identical": true, + "base": "transformers.Trainer (modern supported API)", + "reason": "MeZO 2023 copied Trainer imports removed private APIs; retain original zo_forward and Framework, replace only inner loop with structured branches" + } +} \ No newline at end of file diff --git a/methods/large_models/__init__.py b/methods/large_models/__init__.py new file mode 100644 index 0000000..1f46cf0 --- /dev/null +++ b/methods/large_models/__init__.py @@ -0,0 +1 @@ +"""MeZO-style shared implementation for our structured optimizers.""" diff --git a/methods/large_models/_upstream_run.py b/methods/large_models/_upstream_run.py new file mode 100644 index 0000000..64a497a --- /dev/null +++ b/methods/large_models/_upstream_run.py @@ -0,0 +1,532 @@ +import logging + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) +logger.setLevel(logging.INFO) + +import argparse +import time +from . import tasks +from transformers import AutoConfig, AutoTokenizer, AutoModelForCausalLM, Trainer, HfArgumentParser, Trainer, TrainingArguments, DataCollatorWithPadding, DataCollatorForTokenClassification +from typing import Union, Optional +import torch +from torch.nn.parameter import Parameter +import numpy as np +from dataclasses import dataclass, is_dataclass, asdict +from tqdm import tqdm +from .tasks import get_task +import json +import torch.nn.functional as F +from torch.utils.data import Dataset +from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP +from .metrics import calculate_metric +from .utils import * +from .trainer import OurTrainer +import random + +@dataclass +class OurArguments(TrainingArguments): + # dataset and sampling strategy + task_name: str = "SST2" # task name should match the string before Dataset in the Dataset class name. We support the following task_name: SST2, RTE, CB, BoolQ, WSC, WIC, MultiRC, Copa, ReCoRD, SQuAD, DROP + + # Number of examples + num_train: int = 0 # ICL mode: number of demonstrations; training mode: number of training samples + num_dev: int = None # (only enabled with training) number of development samples + num_eval: int = None # number of evaluation samples + num_train_sets: int = None # how many sets of training samples/demos to sample; if None and train_set_seed is None, then we will sample one set for each evaluation sample + train_set_seed: int = None # designated seed to sample training samples/demos + result_file: str = None # file name for saving performance; if None, then use the task name, model name, and config + + # Model loading + model_name: str = "facebook/opt-125m" # HuggingFace model name + load_float16: bool = False # load model parameters as float16 + load_bfloat16: bool = False # load model parameters as bfloat16 + load_int8: bool = False # load model parameters as int8 + max_length: int = 2048 # max length the model can take + no_auto_device: bool = False # do not load model by auto device; should turn this on when using FSDP + + # Calibration + sfc: bool = False # whether to use SFC calibration + icl_sfc: bool = False # whether to use SFC calibration for ICL samples + + # Training + trainer: str = "none" + ## options + ## - none: no training -- for zero-shot or in-context learning (ICL) + ## - regular: regular huggingface trainer -- for fine-tuning + ## - zo: zeroth-order (MeZO) training + only_train_option: bool = True # whether to only train the option part of the input + train_as_classification: bool = False # take the log likelihood of all options and train as classification + + # MeZO + zo_eps: float = 1e-3 # eps in MeZO + + # Prefix tuning + prefix_tuning: bool = False # whether to use prefix tuning + num_prefix: int = 5 # number of prefixes to use + no_reparam: bool = True # do not use reparameterization trick + prefix_init_by_real_act: bool = True # initialize prefix by real activations of random words + + # LoRA + lora: bool = False # whether to use LoRA + lora_alpha: int = 16 # alpha in LoRA + lora_r: int = 8 # r in LoRA + + # Generation + sampling: bool = False # whether to use sampling + temperature: float = 1.0 # temperature for generation + num_beams: int = 1 # number of beams for generation + top_k: int = None # top-k for generation + top_p: float = 0.95 # top-p for generation + max_new_tokens: int = 50 # max number of new tokens to generate + eos_token: str = "\n" # end of sentence token + + # Saving + save_model: bool = False # whether to save the model + no_eval: bool = False # whether to skip evaluation + tag: str = "" # saving tag + + # Linear probing + linear_probing: bool = False # whether to do linear probing + lp_early_stopping: bool = False # whether to do early stopping in linear probing + head_tuning: bool = False # head tuning: only tune the LM head + + # Untie emb/lm_head weights + untie_emb: bool = False # untie the embeddings and LM head + + # Display + verbose: bool = False # verbose output + + # Non-diff objective + non_diff: bool = False # use non-differentiable objective (only support F1 for SQuAD for now) + + # Auto saving when interrupted + save_on_interrupt: bool = False # save model when interrupted (useful for long training) + + +def parse_args(): + parser = argparse.ArgumentParser() + parser = HfArgumentParser(OurArguments) + args = parser.parse_args_into_dataclasses()[0] + print(args) + return args + + +def set_seed(seed: int): + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + +class Framework: + + def __init__(self, args, task): + self.args = args + self.task = task + self.model, self.tokenizer = self.load_model() + + + def load_model(self): + """ + Load HuggingFace models + """ + with count_time("Loading model with FP%d" % (16 if self.args.load_float16 else 32)): + free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) if torch.cuda.is_available() else 0 + config = AutoConfig.from_pretrained(self.args.model_name) + if self.args.untie_emb: + # Untie embeddings/LM head + logger.warn("Untie embeddings and LM head") + config.tie_word_embeddings = False + if self.args.head_tuning: + # Head tuning + from ht_opt import OPTForCausalLM + model = OPTForCausalLM.from_pretrained( + self.args.model_name, + config=config, + torch_dtype=torch.float32, attn_implementation="eager", local_files_only=True, + ) + elif self.args.no_auto_device: + # No auto device (use for FSDP) + model = AutoModelForCausalLM.from_pretrained( + self.args.model_name, + config=config, + torch_dtype=torch.float32, attn_implementation="eager", local_files_only=True, + ) + else: + # Auto device loading + torch_dtype = torch.float32 + if self.args.load_float16: + torch_dtype = torch.float16 + elif self.args.load_bfloat16: + torch_dtype = torch.bfloat16 + model = AutoModelForCausalLM.from_pretrained( + self.args.model_name, + config=config, + device_map='auto', + torch_dtype=torch_dtype, + max_memory={i: f'{free_in_GB-5}GB' for i in range(torch.cuda.device_count())}, + load_in_8bit=self.args.load_int8, + ) + model.eval() + + # Load tokenizer + tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast="qwen" in self.args.model_name.lower(), local_files_only=True) + if tokenizer.pad_token_id is None: + tokenizer.pad_token = tokenizer.eos_token + + # HF tokenizer bug fix + if "opt" in self.args.model_name: + tokenizer.bos_token_id = 0 + + if "llama" in self.args.model_name: + # LLaMA padding token + tokenizer.pad_token_id = 0 # technically + + # Prefix tuning/LoRA + if self.args.prefix_tuning: + from prefix import PrefixTuning + PrefixTuning(model, num_prefix=self.args.num_prefix, reparam=not self.args.no_reparam, float16=self.args.load_float16, init_by_real_act=self.args.prefix_init_by_real_act) + if self.args.lora: + from lora import LoRA + LoRA(model, r=self.args.lora_r, alpha=self.args.lora_alpha, float16=self.args.load_float16) + + if self.args.head_tuning: + if model.config.model_type == "opt": + head_name = "lm_head" if self.args.untie_emb else "embed_tokens" + else: + raise NotImplementedError + for n, p in model.named_parameters(): + if head_name not in n: + p.requires_grad = False + else: + logger.info(f"Only tuning {n}") + + return model, tokenizer + + + def forward(self, input_ids, option_len=None, generation=False): + """ + Given input_ids and the length of the option, return the log-likelihood of each token in the option. + For generation tasks, return the generated text. + This function is only for inference + """ + input_ids = torch.tensor([input_ids]).to(self.model.device) + + if generation: + args = self.args + # Autoregressive generation + outputs = self.model.generate( + input_ids, do_sample=args.sampling, temperature=args.temperature, + num_beams=args.num_beams, top_p=args.top_p, top_k=args.top_k, max_new_tokens=min(args.max_new_tokens, args.max_length - input_ids.size(1)), + num_return_sequences=1, eos_token_id=[self.tokenizer.encode(args.eos_token, add_special_tokens=False)[-1], self.tokenizer.eos_token_id], + ) + # For generation, directly return the text output + output_text = self.tokenizer.decode(outputs[0][input_ids.size(1):], skip_special_tokens=True).strip() + return output_text + else: + with torch.inference_mode(): + self.model.eval() + logits = self.model(input_ids=input_ids).logits + labels = input_ids[0, 1:] + logits = logits[0, :-1] + log_probs = F.log_softmax(logits, dim=-1) + + selected_log_probs = log_probs[torch.arange(len(labels)).to(labels.device), labels] + selected_log_probs = selected_log_probs.cpu().detach() + # Only return the option (candidate) part + return selected_log_probs[-option_len:] + + + def one_step_pred(self, train_samples, eval_sample, verbose=False): + """ + Return the prediction on the eval sample. In ICL, use train_samples as demonstrations + """ + verbose = verbose or self.args.verbose + if verbose: + logger.info("========= Example =========") + logger.info(f"Candidate: {eval_sample.candidates}") + logger.info(f"Correct candidate: {eval_sample.correct_candidate}") + + + # Encode (add prompt and tokenize) the sample; if multiple-choice/classification, encode all candidates (options) + encoded_candidates, option_lens = encode_prompt( + self.task, self.task.get_template(), train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length, + generation=self.task.generation, max_new_tokens=self.args.max_new_tokens + ) + + # Calibration + if self.args.sfc or self.args.icl_sfc: + sfc_encoded_candidates, sfc_option_lens = encode_prompt(self.task, self.task.get_template(), + train_samples, eval_sample, self.tokenizer, max_length=self.args.max_length, + sfc=self.args.sfc, icl_sfc=self.args.icl_sfc, generation=self.task.generation, + max_new_tokens=self.args.max_new_tokens + ) + + outputs = [] + if self.task.generation: + # For generation tasks, return the autoregressively-generated text + output_text = self.forward(encoded_candidates[0], generation=True) + if verbose: + logger.info("=== Prompt ===") + logger.info(self.tokenizer.decode(encoded_candidates[0])) + logger.info(f"Output: {output_text}") + return Prediction(correct_candidate=eval_sample.correct_candidate, predicted_candidate=output_text) + else: + # For classification/multiple-choice, calculate the probabilities of all candidates + for candidate_id, encoded_candidate in enumerate(encoded_candidates): + selected_log_probs = self.forward(encoded_candidate, option_len=option_lens[candidate_id]) + if verbose: + if candidate_id == 0: + logger.info("=== Candidate %d ===" % candidate_id) + logger.info(self.tokenizer.decode(encoded_candidate)) + else: + logger.info("=== Candidate %d (without context)===" % candidate_id) + logger.info(self.tokenizer.decode(encoded_candidate).split(self.task.train_sep)[-1]) + logger.info(f"Log probabilities of the option tokens: {selected_log_probs}") + + if self.args.sfc or self.args.icl_sfc: + sfc_selected_log_probs = self.forward(sfc_encoded_candidates[candidate_id], option_len=sfc_option_lens[candidate_id]) + if verbose: + logger.info("=== Candidate %d (without context) SFC ===" % candidate_id) + logger.info(self.tokenizer.decode(sfc_encoded_candidates[candidate_id]).split(self.task.train_sep)[-1]) + logger.info(f"Log probabilities of the option tokens: {sfc_selected_log_probs}") + + outputs.append({"log_probs": selected_log_probs, "sfc_log_probs": sfc_selected_log_probs if self.args.sfc or self.args.icl_sfc else None}) + + if self.args.sfc or self.args.icl_sfc: + # Calibrated probabilities (surface form competition; https://arxiv.org/pdf/2104.08315.pdf) + # log p(candidate | input) = log p_lm(candidate | input) - log p_lm(candidate | sfc prompt) + scores = [x['log_probs'].sum().item() - x['sfc_log_probs'].sum().item() for x in outputs] + else: + # (Default) length-normalized log probabilities + # log p(candidate | input) = log p_lm(candidate | input) / |candidate #tokens| + scores = [x['log_probs'].mean().item() for x in outputs] + + if verbose: + logger.info(f"Prediction scores: {scores}") + + if isinstance(eval_sample.correct_candidate, list): + # For some datasets there are multiple correct answers + correct_candidate_id = [eval_sample.candidates.index(c) for c in eval_sample.correct_candidate] + else: + correct_candidate_id = eval_sample.candidates.index(eval_sample.correct_candidate) + + return Prediction(correct_candidate=correct_candidate_id, predicted_candidate=int(np.argmax(scores))) + + + def evaluate(self, train_samples, eval_samples, one_train_set_per_eval_sample=False): + """ + Evaluate function. If one_train_set_per_eval_sample is True, then each eval sample has its own training (demonstration) set. + """ + if one_train_set_per_eval_sample: + logger.info(f"There are {len(eval_samples)} validation samples and one train set per eval sample") + else: + logger.info(f"There are {len(train_samples)} training samples and {len(eval_samples)} validation samples") + + # Prediction loop + predictions = [] + for eval_id, eval_sample in enumerate(tqdm(eval_samples)): + predictions.append( + self.one_step_pred(train_samples[eval_id] if one_train_set_per_eval_sample else train_samples, eval_sample, verbose=(eval_id < 3)) + ) + + # Calculate metrics + metric_name = getattr(self.task, "metric_name", "accuracy") + metrics = {metric_name: calculate_metric(predictions, metric_name)} + return metrics + + + def train(self, train_samples, eval_samples): + """ + Training function + """ + # Set tokenizer to left padding (so that all the options are right aligned) + self.tokenizer.padding_side = "left" + + class HFDataset(Dataset): + + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __getitem__(self, idx): + return self.data[idx] + + + def _convert(samples): + """ + Convert samples to HF-compatible dataset + """ + data = [] + for sample in samples: + encoded_candidates, option_lens = encode_prompt( + self.task, self.task.get_template(), [], sample, self.tokenizer, + max_length=self.args.max_length, generation=self.task.generation, generation_with_gold=True, + max_new_tokens=self.args.max_new_tokens + ) + if self.task.generation: + correct_candidate_id = 0 + elif isinstance(sample.correct_candidate, list): + correct_candidate_id = sample.candidates.index(sample.correct_candidate[0]) + else: + correct_candidate_id = sample.candidates.index(sample.correct_candidate) + + if self.args.non_diff: + # For non-differentiable objective, there is no teacher forcing thus the + # current answer part is removed + encoded_candidates[correct_candidate_id] = encoded_candidates[correct_candidate_id][:-option_lens[correct_candidate_id]] + + if self.args.train_as_classification: + # For classification, we provide the label as the correct candidate id + data.append([{"input_ids": encoded_candidates[_i], "labels": correct_candidate_id, "option_len": option_lens[_i], "num_options": len(sample.candidates)} for _i in range(len(encoded_candidates))]) + elif self.args.only_train_option: + # Otherwise, it is just LM-style teacher forcing + if self.args.non_diff: + # For non-differentiable objective, we need to provide the gold answer to calculate F1/acc + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id], "gold": sample.correct_candidate}) + else: + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id], "option_len": option_lens[correct_candidate_id]}) + else: + data.append({"input_ids": encoded_candidates[correct_candidate_id], "labels": encoded_candidates[correct_candidate_id]}) + return data + + with count_time("Tokenizing training samples"): + train_dataset = HFDataset(_convert(train_samples)) + eval_dataset = HFDataset(_convert(eval_samples)) + + if self.args.only_train_option and not self.args.non_diff: + # If --only_train_option and not with a non-differentiable objective, we wrap the forward function + self.model.original_forward = self.model.forward + self.model.forward = forward_wrap_with_option_len.__get__(self.model, type(self.model)) + + if self.args.non_diff: + collator = NondiffCollator + else: + collator = DataCollatorForTokenClassification + + trainer = OurTrainer( + model=self.model, + args=self.args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + tokenizer=self.tokenizer, + data_collator=DataCollatorWithPaddingAndNesting(self.tokenizer, pad_to_multiple_of=8) if self.args.train_as_classification else collator(self.tokenizer, pad_to_multiple_of=8), + ) + self.trainer = trainer + if self.args.save_on_interrupt: + trainer.add_callback(SIGUSR1Callback()) + + # Resume training from a last checkpoint + last_checkpoint = None + from transformers.trainer_utils import get_last_checkpoint + if os.path.isdir(self.args.output_dir) and not self.args.overwrite_output_dir: + last_checkpoint = get_last_checkpoint(self.args.output_dir) + if last_checkpoint is not None and self.args.resume_from_checkpoint is None: + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + if self.args.resume_from_checkpoint is not None: + last_checkpoint = self.args.resume_from_checkpoint + + trainer.train(resume_from_checkpoint=last_checkpoint) + + # Explicitly save the model + if self.args.save_model: + logger.warn("Save model..") + trainer.save_model() + + # FSDP compatibility + self.model = trainer.model + + # Reset the forward function for evaluation + if self.args.only_train_option and not self.args.non_diff: + if type(self.model) == FSDP: + logger.info("This is an FSDP model now. Be careful when assigning back the original forward function") + self.model._fsdp_wrapped_module.forward = self.model._fsdp_wrapped_module.original_forward + else: + self.model.forward = self.model.original_forward + + +def result_file_tag(args): + """ + Get the result file tag + """ + save_model_name = args.model_name.split("/")[-1] + sfc_tag = "-sfc" if args.sfc else "" + icl_sfc_tag = "-icl_sfc" if args.icl_sfc else "" + sample_eval_tag = "-sampleeval%d" % args.num_eval if args.num_eval is not None else "" + sample_train_tag = "-ntrain%d" % args.num_train if args.num_train > 0 else "" + sample_dev_tag = "-ndev%d" % args.num_dev if args.num_dev is not None else "" + customized_tag = f"-{args.tag}" if len(args.tag) > 0 else "" + return f"{args.task_name}-{save_model_name}" + sfc_tag + icl_sfc_tag + sample_eval_tag + sample_train_tag + sample_dev_tag + customized_tag + + +def main(): + args = parse_args() + + set_seed(args.seed) + task = get_task(args.task_name) + train_sets = task.sample_train_sets(num_train=args.num_train, num_dev=args.num_dev, num_eval=args.num_eval, num_train_sets=args.num_train_sets, seed=args.train_set_seed) + + # Initialize trainer and load model + framework = Framework(args, task) + + if args.train_set_seed is not None or args.num_train_sets is not None: + # Eval samples share one (or multiple) training set(s) + for train_set_id, train_samples in enumerate(train_sets): + train_set_seed = train_set_id if args.train_set_seed is None else args.train_set_seed + + # Sample eval samples + if args.num_eval is not None: + eval_samples = task.sample_subset(data_split="valid", seed=train_set_seed, num=args.num_eval) + else: + eval_samples = task.valid_samples + + if args.trainer != "none": + if args.num_dev is not None: + # Dev samples + dev_samples = train_samples[-args.num_dev:] + train_samples = train_samples[:-args.num_dev] + else: + dev_samples = None + + # Training + framework.train(train_samples, dev_samples if dev_samples is not None else eval_samples) + + if not args.no_eval: + metrics = framework.evaluate([], eval_samples) # No in-context learning if there is training + if dev_samples is not None: + dev_metrics = framework.evaluate([], dev_samples) + for m in dev_metrics: + metrics["dev_" + m] = dev_metrics[m] + else: + assert args.num_dev is None + # Zero-shot / in-context learning + metrics = framework.evaluate(train_samples, eval_samples) + + if not args.no_eval: + logger.info("===== Train set %d =====" % train_set_seed) + logger.info(metrics) + if args.local_rank <= 0: + write_metrics_to_file(metrics, "result/" + result_file_tag(args) + f"-trainset{train_set_id}.json" if args.result_file is None else args.result_file) + + else: + # For each eval sample, there is a training set. no training is allowed + # This is for in-context learning (ICL) + assert args.trainer == "none" + if args.num_eval is not None: + eval_samples = task.sample_subset(data_split="valid", seed=0, num=args.num_eval) + else: + eval_samples = task.valid_samples + + metrics = framework.evaluate(train_sets, eval_samples, one_train_set_per_eval_sample=True) + logger.info(metrics) + if args.local_rank <= 0: + write_metrics_to_file(metrics, "result/" + result_file_tag(args) + "-onetrainpereval.json" if args.result_file is None else args.result_file) + +if __name__ == "__main__": + main() diff --git a/methods/large_models/assets.py b/methods/large_models/assets.py new file mode 100644 index 0000000..b4f89ae --- /dev/null +++ b/methods/large_models/assets.py @@ -0,0 +1,9 @@ +"""MeZO's Dataset API backed by the shared local assets, without global monkeypatching.""" +from datasets import load_from_disk +from experiments_codebase.paths import paths + +def load_dataset(name,config=None,**kwargs): + alias='sst2' if name in ('glue','nyu-mll/glue') and config=='sst2' else ('drop' if name in ('drop','ucinlp/drop') else None) + if alias is None:raise ValueError('This audited integration supports SST2 and DROP only') + dataset=load_from_disk(str(paths()['data']/alias)) + return dataset[kwargs['split']] if 'split' in kwargs else dataset diff --git a/methods/large_models/data.py b/methods/large_models/data.py new file mode 100644 index 0000000..87b6581 --- /dev/null +++ b/methods/large_models/data.py @@ -0,0 +1,69 @@ +"""Legacy protocol compatibility and deterministic HF data loading.""" +import math +import numpy as np +import torch +from torch.utils.data import Dataset,Sampler +from datasets import load_from_disk +from experiments_codebase.paths import paths + +def seed_for(seed, stream, step=0): + """由总种子、用途编号和步数隔开数据采样、训练和选基的随机流。""" + return int(np.random.SeedSequence([seed, stream, step]).generate_state(1, dtype=np.uint64)[0] % (2 ** 63 - 1)) + +class HFDataset(Dataset): + def __init__(self,rows):self.data=rows + def __len__(self):return len(self.data) + def __getitem__(self,index):return self.data[index] + +class ProtocolSampler(Sampler): + """Same independent PCG batch-order stream as the previous implementation.""" + def __init__(self,dataset,seed):self.dataset=dataset;self.rng=np.random.default_rng(seed_for(seed,11)) + def __iter__(self):return iter(self.rng.permutation(len(self.dataset)).tolist()) + def __len__(self):return len(self.dataset) + +class LegacyCollator: + def __init__(self,tokenizer):self.tokenizer=tokenizer + def __call__(self,rows): + width=math.ceil(max(len(r['input_ids']) for r in rows)/8)*8 + ids=torch.full((len(rows),width),self.tokenizer.pad_token_id,dtype=torch.long) + mask=torch.zeros_like(ids);targets=torch.full_like(ids,-100) + for i,row in enumerate(rows): + size=len(row['input_ids']);ids[i,-size:]=torch.tensor(row['input_ids']);mask[i,-size:]=1 + if row.get('answer_length',0):targets[i,-row['answer_length']:]=ids[i,-row['answer_length']:] + labels=torch.tensor([r['label'] for r in rows]) if 'label' in rows[0] else targets + return dict(input_ids=ids,attention_mask=mask,labels=labels) + +def legacy_rows(args,tokenizer): + ds=load_from_disk(str(paths()['data']/args.task_name.lower()));rng=np.random.default_rng(args.seed) + n=args.num_train+args.num_dev + if n>len(ds['train']):raise ValueError('Train and development counts exceed available data') + ids=rng.permutation(len(ds['train']))[:n];groups={} + for split,source,indices in [('train','train',ids[:args.num_train]),('development','train',ids[args.num_train:]),('validation','validation',range(min(args.num_eval,len(ds['validation']))))]: + rows=[] + for i in indices: + row=ds[source][int(i)] + if args.task_name=='SST2': + tokens=tokenizer.encode(f"{row['sentence'].strip()} It was",add_special_tokens=True,truncation=True,max_length=args.max_length) + rows.append(dict(input_ids=tokens,label=int(row['label']),source_index=int(i),source_split=source)) + else: + answers=[str(v) for v in row['answers_spans']['spans']] + answer=tokenizer.encode(' '+answers[0],add_special_tokens=False)[:min(32,args.max_length//4)] + prompt=f"Passage: {row['passage']}\nQuestion: {row['question']}\nAnswer:" + tokens=tokenizer.encode(prompt,add_special_tokens=True,truncation=True,max_length=args.max_length-len(answer)) + if not tokens or not answer:raise ValueError('Empty DROP prompt or answer') + rows.append(dict(input_ids=tokens+answer,prompt_ids=tokens,answer_length=len(answer),answers=answers,source_index=int(i),source_split=source)) + groups[split]=rows + return groups + +def convert_samples(task,samples,tokenizer,args): + """MeZO Framework._convert for evaluation; unsupported modes are rejected by CLI.""" + from .utils import encode_prompt + data=[] + for sample in samples: + candidates,lengths=encode_prompt(task,task.get_template(),[],sample,tokenizer,max_length=args.max_length, + generation=task.generation,generation_with_gold=True,max_new_tokens=args.max_new_tokens) + correct=0 if task.generation else sample.candidates.index(sample.correct_candidate[0] if isinstance(sample.correct_candidate,list) else sample.correct_candidate) + if args.train_as_classification: + data.append([{'input_ids':candidates[i],'labels':correct,'option_len':lengths[i],'num_options':len(sample.candidates)} for i in range(len(candidates))]) + else:data.append({'input_ids':candidates[correct],'labels':candidates[correct],'option_len':lengths[correct]}) + return data diff --git a/methods/large_models/logging_utils.py b/methods/large_models/logging_utils.py new file mode 100644 index 0000000..c3a2a24 --- /dev/null +++ b/methods/large_models/logging_utils.py @@ -0,0 +1,34 @@ +"""Shared output helpers; no model loading or optimizer dependencies.""" +from contextlib import contextmanager,redirect_stdout,redirect_stderr +import sys +import torch + +def memory(): + if not torch.cuda.is_available():return {} + torch.cuda.synchronize();free,total=torch.cuda.mem_get_info();g=2**30 + return dict(allocated_GiB=torch.cuda.memory_allocated()/g,reserved_GiB=torch.cuda.memory_reserved()/g, + peak_allocated_GiB=torch.cuda.max_memory_allocated()/g,device_used_GiB=(total-free)/g,device_total_GiB=total/g) + +def figures(out,curve): + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + for key,name in [('loss','loss_curve.png'),('accuracy','acc_curve.png')]: + fig,ax=plt.subplots(figsize=(8,4));found=False + for split in ('train_probe','development'): + points=[p for p in curve if key in p[split]] + if points:ax.plot([p['main_forwards'] for p in points],[p[split][key] for p in points],label=split);found=True + if found: + ax.set(xlabel='Cumulative main forwards (including probes)',ylabel=key);ax.grid(alpha=.2);ax.legend();fig.tight_layout();fig.savefig(out/name,dpi=160) + plt.close(fig) + +class Tee: + def __init__(self,*streams):self.streams=streams + def write(self,text): + for stream in self.streams:stream.write(text);stream.flush() + def flush(self): + for stream in self.streams:stream.flush() + @staticmethod + @contextmanager + def redirect(log): + with redirect_stdout(Tee(sys.stdout,log)),redirect_stderr(Tee(sys.stderr,log)):yield diff --git a/methods/large_models/losses.py b/methods/large_models/losses.py new file mode 100644 index 0000000..cc98c56 --- /dev/null +++ b/methods/large_models/losses.py @@ -0,0 +1,22 @@ +import torch +import torch.nn.functional as F + +class LegacyLoss: + """Keep the previous loss and efficient readout exactly for equivalence testing.""" + def __init__(self,model,tokenizer,task): + from types import SimpleNamespace + self.model=model;self.args=SimpleNamespace(task=task.lower()) + self.label_ids=[tokenizer.encode(w,add_special_tokens=False)[0] for w in (' terrible',' great')] + def __call__(self,inputs): + hidden=self.model.model(input_ids=inputs['input_ids'],attention_mask=inputs['attention_mask'],use_cache=False).last_hidden_state + if self.args.task=='sst2': + logits=self.model.lm_head(hidden[:,-1])[:,self.label_ids] + losses=F.cross_entropy(logits.float(),inputs['labels'],reduction='none') + else: + shifted=inputs['labels'][:,1:];valid=shifted!=-100 + logits=self.model.lm_head(hidden[:,:-1][valid]).float() + token_loss=F.cross_entropy(logits,shifted[valid],reduction='none') + owner=torch.arange(len(hidden),device=hidden.device)[:,None].expand_as(valid)[valid] + losses=torch.zeros(len(hidden),device=hidden.device).scatter_add_(0,owner,token_loss)/valid.sum(1).clamp_min(1) + if not bool(torch.isfinite(losses).all()):raise FloatingPointError('Nonfinite loss') + return losses,logits diff --git a/methods/large_models/metrics.py b/methods/large_models/metrics.py new file mode 100644 index 0000000..0e0a282 --- /dev/null +++ b/methods/large_models/metrics.py @@ -0,0 +1,78 @@ +import numpy as np +import collections +import re +import string +from collections import Counter + +def normalize_answer(s): + """Lower text and remove punctuation, articles and extra whitespace.""" + + def remove_articles(text): + return re.sub(r'\b(a|an|the)\b', ' ', text) + + def white_space_fix(text): + return ' '.join(text.split()) + + def remove_punc(text): + exclude = set(string.punctuation) + return ''.join(ch for ch in text if ch not in exclude) + + def lower(text): + return text.lower() + + return white_space_fix(remove_articles(remove_punc(lower(s)))) + + +def calculate_metric(predictions, metric_name): + if metric_name == "accuracy": + if isinstance(predictions[0].correct_candidate, list): + return np.mean([pred.predicted_candidate in pred.correct_candidate for pred in predictions]) + else: + return np.mean([pred.correct_candidate == pred.predicted_candidate for pred in predictions]) + elif metric_name == "em": + # For question answering + return np.mean([any([normalize_answer(ans) == normalize_answer(pred.predicted_candidate) for ans in pred.correct_candidate]) for pred in predictions]) + elif metric_name == "f1": + # For question answering + f1 = [] + for pred in predictions: + all_f1s = [] + if pred.correct_candidate[0] == "CANNOTANSWER" or pred.correct_candidate[0] == "no answer": + f1.append(int(normalize_answer(pred.correct_candidate[0]) == normalize_answer(pred.predicted_candidate))) + else: + for ans in pred.correct_candidate: + prediction_tokens = normalize_answer(pred.predicted_candidate).split() + ground_truth_tokens = normalize_answer(ans).split() + common = Counter(prediction_tokens) & Counter(ground_truth_tokens) + num_same = sum(common.values()) + if num_same == 0: + all_f1s.append(0) + else: + precision = 1.0 * num_same / len(prediction_tokens) + recall = 1.0 * num_same / len(ground_truth_tokens) + all_f1s.append((2 * precision * recall) / (precision + recall)) + f1.append(max(all_f1s)) + + return np.mean(f1) + + +def f1(pred, gold): + """ + This separate F1 function is used as non-differentiable metric for SQuAD + """ + if gold[0] == "CANNOTANSWER" or gold[0] == "no answer": + return int(normalize_answer(gold[0]) == normalize_answer(pred)) + else: + all_f1s = [] + for ans in gold: + prediction_tokens = normalize_answer(pred).split() + ground_truth_tokens = normalize_answer(ans).split() + common = Counter(prediction_tokens) & Counter(ground_truth_tokens) + num_same = sum(common.values()) + if num_same == 0: + all_f1s.append(0) + else: + precision = 1.0 * num_same / len(prediction_tokens) + recall = 1.0 * num_same / len(ground_truth_tokens) + all_f1s.append((2 * precision * recall) / (precision + recall)) + return np.max(all_f1s) \ No newline at end of file diff --git a/methods/large_models/native_losses.py b/methods/large_models/native_losses.py new file mode 100644 index 0000000..a83500e --- /dev/null +++ b/methods/large_models/native_losses.py @@ -0,0 +1,26 @@ +"""Diagnostics around the unchanged MeZO option-loss wrapper; its scalar loss is authoritative.""" +import torch +import torch.nn.functional as F + +class MeZOLoss: + def __init__(self,model):self.model=model;self.last_weight=None + def __call__(self,inputs): + output=self.model(**inputs,return_dict=True) + labels=inputs['input_ids'][:,1:].clone();labels[labels==self.model.config.pad_token_id]=-100 + for index,length in enumerate(inputs['option_len']): + if int(length)<=0:raise ValueError('Empty MeZO option after encoding/truncation') + labels[index,:-int(length)]=-100 + valid=labels!=-100 + if 'num_options' in inputs: + options=int(inputs['num_options'][0]) + if options!=2 or not bool((inputs['num_options']==2).all()):raise ValueError('Current node/diagnostic integration supports binary SST2 options only') + log_probs=output.logits[:,:-1].log_softmax(-1) + selected=log_probs.gather(-1,labels.masked_fill(~valid,0).unsqueeze(-1)).squeeze(-1) + scores=((selected*valid).sum(-1)/valid.sum(-1)).view(-1,2) + # Repeat per-example scores for the two candidate activation rows. + logits=scores.repeat_interleave(2,dim=0);self.last_weight=len(scores) + else: + logits=output.logits.new_empty((len(labels),0));self.last_weight=int(valid.sum()) + # Preserve the author's scalar/token-weighted objective, rather than + # replacing it with a mean of per-example token losses. + return output.loss.expand(len(inputs['input_ids'])),logits diff --git a/methods/large_models/run.py b/methods/large_models/run.py new file mode 100644 index 0000000..1bffe4b --- /dev/null +++ b/methods/large_models/run.py @@ -0,0 +1,258 @@ +"""MeZO project structure with fix/adjust/node Trainer branches and explicit data protocols.""" +import sys +from pathlib import Path +ROOT=Path(__file__).resolve().parents[2] +sys.path.insert(0,str(ROOT/'src')) +if __package__ in (None,''): + sys.path.insert(0,str(ROOT)) + from methods.large_models.run import main + if __name__=='__main__':main() + raise SystemExit + +from dataclasses import dataclass,field,asdict +from datetime import datetime,timezone +import hashlib +import importlib.metadata +import json +from typing import Optional +import torch +from transformers import HfArgumentParser +from experiments_codebase.paths import paths,model_path,save +from ._upstream_run import Framework as MeZOFramework,OurArguments as MeZOArguments,set_seed +from .tasks import get_task +from .trainer import OurTrainer +from .data import HFDataset,LegacyCollator,legacy_rows,convert_samples +from .utils import DataCollatorWithPaddingAndNesting,forward_wrap_with_option_len +from .logging_utils import Tee + +@dataclass +class OurArguments(MeZOArguments): + trainer: str='fix' + model_name: str='facebook/opt-1.3b' + data_protocol: str='mezo' + main_forward_budget: int=6000 + num_train: int=1000 + num_dev: int=500 + num_eval: int=872 + max_length: int=128 + max_new_tokens: int=32 + seed: int=2026110791 + per_device_train_batch_size: int=16 + per_device_eval_batch_size: int=16 + calibration_samples: int=16 + refresh_every: Optional[int]=None + node_queries: int=2 + node_epsilon: float=1e-3 + node_update: str='original' + basis_lr: float=1e-5 + basis_radius: float=1e-3 + history_beta: float=.9 + zo_schedule: Optional[str]=None + decay_start: int=3000 + lr_min: Optional[float]=None + eval_main_forwards: int=600 + rank: int=1 + q: int=1 + save_final_checkpoint: bool=True + select_best_checkpoint: bool=True + preflight_only: bool=False + action: str='train' + checkpoint: Optional[str]=None + prompt: Optional[str]=None + dtype: str='float32' + resume_from_checkpoint: Optional[str]=None + no_auto_device: bool=True + optim: str='sgd' + weight_decay: float=0. + fp16: bool=False + bf16: Optional[bool]=False + remove_unused_columns: bool=False + dataloader_drop_last: Optional[bool]=None + dataloader_num_workers: int=0 + report_to: list[str]=field(default_factory=list) + disable_tqdm: bool=True + +ALIASES={'--method':'--trainer','--model':'--model_name','--task':'--task_name','--budget':'--main_forward_budget','--lr':'--learning_rate','--mu':'--zo_eps', + '--batch-size':'--per_device_train_batch_size','--eval-batch-size':'--per_device_eval_batch_size','--train-samples':'--num_train','--dev-samples':'--num_dev','--eval-samples':'--num_eval', + '--calibration-samples':'--calibration_samples','--max-length':'--max_length','--eval-every':'--eval_main_forwards','--refresh-every':'--refresh_every', + '--node-queries':'--node_queries','--node-epsilon':'--node_epsilon','--history-beta':'--history_beta','--schedule':'--zo_schedule', + '--decay-start':'--decay_start','--lr-min':'--lr_min','--max-new-tokens':'--max_new_tokens','--out':'--output_dir','--weight-decay':'--weight_decay','--data-protocol':'--data_protocol'} + +def parse_args(argv=None,forced_method=None): + raw=list(sys.argv[1:] if argv is None else argv);normalized=[];i=0 + while i0 for x in (args.basis_lr,args.basis_radius)): + raise ValueError('Basis learning rate and radius must be positive finite') + if not any(v.split('=')[0]=='--learning_rate' for v in normalized):args.learning_rate=1.5e-6 if args.trainer=='node' else 1e-6 + if any(v.split('=')[0]=='--lr_scheduler_type' for v in normalized): + requested=args.lr_scheduler_type.value + if requested not in ('constant','cosine') or args.zo_schedule not in (None,requested):raise ValueError('Use one consistent constant/cosine schedule') + args.zo_schedule=requested + args.zo_schedule=args.zo_schedule or ('cosine' if args.trainer=='node' else 'constant') + from transformers.trainer_utils import SchedulerType + args.lr_scheduler_type=SchedulerType(args.zo_schedule) + args.lr_min=args.lr_min if args.lr_min is not None else args.learning_rate*.1 + args.refresh_every=args.refresh_every or (128 if args.trainer=='node' else 256) + args.train_set_seed=args.seed if args.train_set_seed is None else args.train_set_seed + args.overwrite_output_dir=True + if args.data_protocol not in ('legacy','mezo') or args.task_name not in ('SST2','DROP'):raise ValueError('Unknown protocol or task') + if args.dataloader_drop_last is None:args.dataloader_drop_last=args.data_protocol=='legacy' + if args.action not in ('train','evaluate','generate') or args.zo_schedule not in ('constant','cosine'):raise ValueError('Unknown action or schedule') + counts=[args.num_train,args.num_dev,args.num_eval,args.per_device_train_batch_size,args.per_device_eval_batch_size,args.calibration_samples,args.refresh_every,args.eval_main_forwards,args.node_queries] + if min(counts)<=0 or args.num_train None: + self.subtask = subtask + + def get_task_name(self): + return self.subtask + + def load_dataset(): + raise NotImplementedError + + def get_template(self, template_version=0): + templates = {0: Template} + return templates[template_version] + + def build_sample(self, example): + return + + def sample_train_sets(self, num_train=32, num_dev=None, num_eval=None, num_train_sets=None, seed=None): + if seed is not None: + # one train/demo set using the designated seed + seeds = [seed] + elif num_train_sets is not None: + # num_train_sets train/demo sets + seeds = list(range(num_train_sets)) + else: + # one train/demo set per evaluation sample + assert num_dev is None # not supported + len_valid_samples = len(self.samples["valid"]) if num_eval is None else num_eval + with temp_seed(0): + seeds = np.random.randint(0, 10000, len_valid_samples) + + train_samples = [] + for i, set_seed in enumerate(seeds): + if self.mixed_set: + raise NotImplementedError + train_samples.append(self.sample_subset(data_split="valid", seed=set_seed, num=num_train, exclude=i)) + else: + if num_dev is not None: + train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train+num_dev)) # dev set is included at the end of train set + if num_train + num_dev > len(self.samples["train"]): + logger.warn("num_train + num_dev > available training examples") + else: + train_samples.append(self.sample_subset(data_split="train", seed=set_seed, num=num_train)) + if num_dev is not None: + logger.info(f"Sample train set {len(train_samples[-1])}/{len(self.samples['train'])}") + logger.info(f"... including dev set {num_dev} samples") + return train_samples + + def sample_subset(self, data_split="train", seed=0, num=100, exclude=None): + with temp_seed(seed): + samples = self.samples[data_split] + lens = len(samples) + index = np.random.permutation(lens).tolist()[:num if exclude is None else num+1] + if exclude is not None and exclude in index: + index.remove(exclude) + else: + index = index[:num] + return [samples[i] for i in index] + + @property + def valid_samples(self): + return self.samples["valid"] + + +class SST2Dataset(Dataset): + train_sep = "\n\n" + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset('glue', 'sst2') + train_d = d["train"] + validation_d = d["validation"] + + train_samples = [self.build_sample(example) for example in train_d] + valid_samples = [self.build_sample(example) for example in validation_d] + + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example): + label = int(example["label"]) + return Sample(id=example["idx"], data=example, correct_candidate=label, candidates=[0, 1]) + + def get_template(self, template_version=0): + return {0: SST2Template}[template_version]() + + +class CopaDataset(Dataset): + train_sep = "\n\n" + mixed_set = False + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + train_examples = load_dataset('super_glue', "copa")["train"] + valid_examples = load_dataset('super_glue', "copa")["validation"] + + train_samples = [self.build_sample(example) for example in train_examples] + valid_samples = [self.build_sample(example) for example in valid_examples] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example): + sample = \ + Sample( + id=example["idx"], + data=example, + candidates=[example["choice1"], example["choice2"]], + correct_candidate=example[f"choice{example['label'] + 1}"], + ) + + return sample + + def get_template(self, template_version=0): + return {0: CopaTemplate}[template_version]() + + +class BoolQDataset(Dataset): + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("boolq") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=["Yes", "No"], + correct_candidate="Yes" if example["answer"] else "No", + ) + + return sample + + def get_template(self, template_version=2): + return {0: BoolQTemplate, 1: BoolQTemplateV2, 2: BoolQTemplateV3}[template_version]() + + +class MultiRCDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "multirc") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: MultiRCTemplate}[template_version]() + + +class CBDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "cb") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1, 2], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: CBTemplate}[template_version]() + + +class WICDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "wic") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: WICTemplate}[template_version]() + + +class WSCDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "wsc.fixed") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: WSCTemplate}[template_version]() + + +class ReCoRDDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "record") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=example['entities'], + correct_candidate=example['answers'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: ReCoRDTemplateGPT3}[template_version]() + + +class RTEDataset(Dataset): + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset(subtask, **kwargs) + + def load_dataset(self, path, **kwargs): + d = load_dataset("super_glue", "rte") + train_set = d["train"] + valid_set = d["validation"] + + train_samples = [self.build_sample(example) for example in train_set] + valid_samples = [self.build_sample(example) for example in valid_set] + self.samples = {"train": train_samples, "valid": valid_samples} + + def build_sample(self, example): + sample = \ + Sample( + data=example, + candidates=[0, 1], + correct_candidate=example['label'] + ) + + return sample + + def get_template(self, template_version=0): + return {0: RTETemplate}[template_version]() + + +class SQuADDataset(Dataset): + metric_name = "f1" + generation = True + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset() + + def load_dataset(self): + dataset = load_dataset("squad") + train_examples = dataset["train"] + valid_examples = dataset["validation"] + + train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)] + valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example, idx): + answers = example['answers']['text'] + assert len(answers) > 0 + return Sample( + id=idx, + data={ + "title": example['title'], + "context": example['context'], + "question": example['question'], + "answers": answers + }, + candidates=None, + correct_candidate=answers + ) + + def get_template(self, template_version=0): + return {0: SQuADv2Template}[template_version]() + + +class DROPDataset(Dataset): + metric_name = "f1" + generation = True + + def __init__(self, subtask=None, **kwargs) -> None: + self.load_dataset() + + def load_dataset(self): + dataset = load_dataset("drop") + train_examples = dataset["train"] + valid_examples = dataset["validation"] + + train_samples = [self.build_sample(example, idx) for idx, example in enumerate(train_examples)] + valid_samples = [self.build_sample(example, idx) for idx, example in enumerate(valid_examples)] + self.samples = {"train": train_samples, "valid": valid_samples} + + # for generative tasks, candidates are [] + def build_sample(self, example, idx): + answers = example['answers_spans']['spans'] + assert len(answers) > 0 + return Sample( + id=idx, + data={ + "context": example['passage'], + "question": example['question'], + "answers": answers + }, + candidates=None, + correct_candidate=answers + ) + + def get_template(self, template_version=0): + return {0: DROPTemplate}[template_version]() diff --git a/methods/large_models/templates.py b/methods/large_models/templates.py new file mode 100644 index 0000000..4a07fb2 --- /dev/null +++ b/methods/large_models/templates.py @@ -0,0 +1,379 @@ +class Template: + def encode(self, sample): + """ + Return prompted version of the example (without the answer/candidate) + """ + raise NotImplementedError + + def verbalize(self, sample, candidate): + """ + Return the prompted version of the example (with the answer/candidate) + """ + return candidate + + def encode_sfc(self, sample): + """ + Same as encode, but for SFC (calibration) -- this usually means the input is not included + """ + return "" + + def verbalize_sfc(self, sample, candidate): + """ + Same as verbalize, but for SFC (calibration) -- this usually means the input is not included + """ + return candidate + + +class SST2Template(Template): + verbalizer = {0: "terrible", 1: "great"} + def encode(self, sample): + text = sample.data["sentence"].strip() + return f"{text} It was" + + def verbalize(self, sample, candidate): + text = sample.data["sentence"].strip() + return f"{text} It was {self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f" It was" + + def verbalize_sfc(self, sample, candidate): + return f" It was {self.verbalizer[candidate]}" + + +class CopaTemplate(Template): + capitalization: str = "correct" + effect_conj: str = " so " + cause_conj: str = " because " + + def get_conjucture(self, sample): + if sample.data["question"] == "effect": + conjunction = self.effect_conj + elif sample.data["question"] == "cause": + conjunction = self.cause_conj + else: + raise NotImplementedError + return conjunction + + def get_prompt(self, sample): + premise = sample.data["premise"].rstrip() + if premise.endswith("."): # TODO Add other scripts with different punctuation + premise = premise[:-1] + conjunction = self.get_conjucture(sample) + prompt = premise + conjunction + if self.capitalization == "upper": + prompt = prompt.upper() + elif self.capitalization == "lower": + prompt = prompt.lower() + return prompt + + def encode(self, sample): + prompt = self.get_prompt(sample) + return prompt + + def capitalize(self, c): + if self.capitalization == "correct": + words = c.split(" ") + if words[0] != "I": + words[0] = words[0].lower() + return " ".join(words) + elif self.capitalization == "bug": + return c + elif self.capitalization == "upper": + return c.upper() + elif self.capitalization == "lower": + return c.lower() + else: + raise NotImplementedError + + def verbalize(self, sample, candidate): + prompt = self.get_prompt(sample) + return prompt + self.capitalize(candidate) + + def encode_sfc(self, sample): + conjunction = self.get_conjucture(sample) + return conjunction.strip() + + def verbalize_sfc(self, sample, candidate): + conjunction = self.get_conjucture(sample) + sfc_prompt = conjunction.strip() + " " + self.capitalize(candidate) + return sfc_prompt + + +class BoolQTemplate(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question} {candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class BoolQTemplateV2(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\\n\\n" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\\n\\n{candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class BoolQTemplateV3(Template): + def encode(self, sample): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\n" + + def verbalize(self, sample, candidate): + passage = sample.data["passage"] + question = sample.data["question"] + if not question.endswith("?"): + question = question + "?" + question = question[0].upper() + question[1:] + return f"{passage} {question}\n{candidate}" + + def encode_sfc(self, sample): + return "" + + def verbalize_sfc(self, sample, candidate): + return candidate + + +class MultiRCTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + paragraph = sample.data["paragraph"] + question = sample.data["question"] + answer = sample.data["answer"] + return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n" + + def verbalize(self, sample, candidate): + paragraph = sample.data["paragraph"] + question = sample.data["question"] + answer = sample.data["answer"] + return f"{paragraph}\nQuestion: {question}\nI found this answer \"{answer}\". Is that correct? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class CBTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "Yes", 1: "No", 2: "Maybe"} + + def encode(self, sample): + premise = sample.data["premise"] + hypothesis = sample.data["hypothesis"] + return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n" + + def verbalize(self, sample, candidate): + premise = sample.data["premise"] + hypothesis = sample.data["hypothesis"] + return f"Suppose {premise} Can we infer that \"{hypothesis}\"? Yes, No, or Maybe?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class WICTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + sent1 = sample.data["sentence1"] + sent2 = sample.data["sentence2"] + word = sample.data["word"] + return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n" + + def verbalize(self, sample, candidate): + sent1 = sample.data["sentence1"] + sent2 = sample.data["sentence2"] + word = sample.data["word"] + return f"Does the word \"{word}\" have the same meaning in these two sentences? Yes, No?\n{sent1}\n{sent2}\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class WSCTemplate(Template): + # From PromptSource 1 + verbalizer = {0: "No", 1: "Yes"} + + def encode(self, sample): + text = sample.data['text'] + span1 = sample.data['span1_text'] + span2 = sample.data['span2_text'] + return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n" + + def verbalize(self, sample, candidate): + text = sample.data['text'] + span1 = sample.data['span1_text'] + span2 = sample.data['span2_text'] + return f"{text}\nIn the previous sentence, does the pronoun \"{span2.lower()}\" refer to {span1}? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class ReCoRDTemplate(Template): + # From PromptSource 1 but modified + + def encode(self, sample): + passage = sample.data['passage'] + query = sample.data['query'] + return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer:" + + def verbalize(self, sample, candidate): + passage = sample.data['passage'] + query = sample.data['query'] + return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}" + + def encode_sfc(self, sample): + return f"Answer:" + + def verbalize_sfc(self, sample, candidate): + return f"Answer: {candidate}" + + +class ReCoRDTemplateGPT3(Template): + # From PromptSource 1 but modified + + def encode(self, sample): + passage = sample.data['passage'].replace("@highlight\n", "- ") + return f"{passage}\n-" + + def verbalize(self, sample, candidate): + passage = sample.data['passage'].replace("@highlight\n", "- ") + query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate) + return f"{passage}\n- {query}" + + # passage = sample.data['passage'] + # query = sample.data['query'] + # return f"{passage}\n{query}\nQuestion: what is the \"@placeholder\"\nAnswer: {candidate}" + + def encode_sfc(self, sample): + return f"-" + + def verbalize_sfc(self, sample, candidate): + query = sample.data['query'].replace("@placeholder", candidate[0] if isinstance(candidate, list) else candidate) + return f"- {query}" + + +class RTETemplate(Template): + # From PromptSource 1 + verbalizer={0: "Yes", 1: "No"} + + def encode(self, sample): + premise = sample.data['premise'] + hypothesis = sample.data['hypothesis'] + return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n" + + def verbalize(self, sample, candidate): + premise = sample.data['premise'] + hypothesis = sample.data['hypothesis'] + return f"{premise}\nDoes this mean that \"{hypothesis}\" is true? Yes or No?\n{self.verbalizer[candidate]}" + + def encode_sfc(self, sample): + return f"" + + def verbalize_sfc(self, sample, candidate): + return f"{self.verbalizer[candidate]}" + + +class SQuADv2Template(Template): + + def encode(self, sample): + question = sample.data['question'].strip() + title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer:" + + def verbalize(self, sample, candidate): + question = sample.data['question'].strip() + title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Title: {title}\nContext: {context}\nQuestion: {question}\nAnswer: {answer}\n" + + + def encode_sfc(self, sample): + raise NotImplementedError + + def verbalize_sfc(self, sample, candidate): + raise NotImplementedError + + +class DROPTemplate(Template): + + def encode(self, sample): + question = sample.data['question'].strip() + # title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Passage: {context}\nQuestion: {question}\nAnswer:" + + def verbalize(self, sample, candidate): + question = sample.data['question'].strip() + # title = sample.data['title'] + context = sample.data['context'] + answer = sample.data['answers'][0] # there are multiple answers. for the prompt we only take the first one + + return f"Passage: {context}\nQuestion: {question}\nAnswer: {answer}\n" + + + def encode_sfc(self, sample): + raise NotImplementedError + + def verbalize_sfc(self, sample, candidate): + raise NotImplementedError diff --git a/methods/large_models/trainer.py b/methods/large_models/trainer.py new file mode 100644 index 0000000..d8598b3 --- /dev/null +++ b/methods/large_models/trainer.py @@ -0,0 +1,701 @@ +"""MeZO-style OurTrainer on the supported HF Trainer API, with structured ZO branches.""" +from datetime import datetime,timezone +import math +import os +from pathlib import Path +import time +import numpy as np +import torch +from transformers import Trainer +from transformers.trainer_utils import TrainOutput +from experiments_codebase.paths import save,append +from .data import ProtocolSampler,seed_for +from .losses import LegacyLoss +from .native_losses import MeZOLoss +from .logging_utils import figures,memory + +def top_basis(x, rank=1): + """从[token数, 输入维度]的激活提取主方向,返回[输入维度, rank]。 + + 这里按未中心化激活做SVD,不减去均值;当前训练入口只支持rank=1。 + """ + x = x.float() + if x.shape[0] < x.shape[1]: + values, vectors = torch.linalg.eigh(x @ x.T) + ids = torch.arange(len(values) - 1, len(values) - rank - 1, -1, device=x.device) + if values[ids[-1]] <= values[-1] * 1e-08: + raise ValueError('Insufficient activation rank') + d = x.T @ (vectors[:, ids] / values[ids].sqrt()) + return torch.linalg.qr(d, mode='reduced').Q.contiguous() + return torch.linalg.svd(x, full_matrices=False).Vh[:rank].T.contiguous() + + +def curvature_descent_reference(g, h, p, lr, n=1, quadratic_mu=0.): + """Small-matrix numerical reference, not a model-training estimator. + + Implements Proposition 2.1 with supplied g and effective upper bound h. + Nonzero quadratic_mu is exact only for a quadratic with Hessian equal to h. + Returns the value and its Euclidean derivative with respect to p. + """ + if n < 1 or int(n) != n or lr <= 0 or quadratic_mu < 0: + raise ValueError('Invalid reference parameters') + a = torch.outer(g, g) + pg = p @ g + s = g @ pg + t = torch.trace(p @ h) + alpha, beta = lr * (1 + 1/n) / 2, lr / (2*n) + value = s - alpha * (pg @ h @ pg) - beta * s * t + gradient = a - alpha * (h @ p @ a + a @ p @ h) - beta * (t*a + s*h) + if quadratic_mu: + ph = p @ h + t2 = torch.trace(ph @ ph) + t3 = torch.trace(ph @ ph @ ph) + factor = lr * quadratic_mu**2 / (8*n) + value = value - factor * (t**3 + 6*t*t2 + 8*t3) + gradient = gradient - factor * ((3*t**2 + 6*t2)*h + + 12*t*(h @ p @ h) + 24*(h @ p @ h @ p @ h)) + return value, gradient + + +def curvature_input_gradient_reference(projection_gradient, d, output_size): + """Contract one Linear block of grad_P for P=I_out kron dd.T; small tests only.""" + k = d.numel() + blocks = projection_gradient.reshape(output_size, k, output_size, k) + c = sum(blocks[a, :, a, :] for a in range(output_size)) + gradient = 2 * c @ d + return gradient - d * (d * gradient).sum() + + +class OurTrainer(Trainer): + def __init__(self,*args,tokenizer=None,**kwargs): + if tokenizer is not None:kwargs['processing_class']=tokenizer + super().__init__(*args,**kwargs) + self.tokenizer_for_zo=self.processing_class + self.loss_backend=LegacyLoss(self.model,self.processing_class,self.args.task_name) if self.args.data_protocol=='legacy' else MeZOLoss(self.model) + self.init_zo() + self._last_outputs=None;self._estimate=None;self.current_lr=self.args.learning_rate + self.curve=[];self.latest={};self.started=time.monotonic() + + def _get_train_sampler(self,train_dataset=None): + if self.args.data_protocol=='mezo':return super()._get_train_sampler(train_dataset) + return ProtocolSampler(self.train_dataset if train_dataset is None else train_dataset,self.args.seed) + + def compute_loss(self,model,inputs,return_outputs=False,num_items_in_batch=None): + self._last_outputs=self.loss_backend(inputs) + loss=self._last_outputs[0].mean() + return (loss,{'loss':loss,'logits':self._last_outputs[1]}) if return_outputs else loss + + # This function is copied verbatim from pinned MeZO OurTrainer. See MEZO_REUSE.json. + def zo_forward(self, model, inputs): + """ + Get (no gradient) loss from the model. Dropout is turned off too. + """ + model.eval() + if self.args.non_diff: + # Non-differentiable objective (may require autoregressive generation) + return self.zo_forward_nondiff(model, inputs) + + with torch.inference_mode(): + inputs = self._prepare_inputs(inputs) + with self.compute_loss_context_manager(): + loss = self.compute_loss(model, inputs) + if self.args.n_gpu > 1: + # Warning: this is copied from the original Huggingface Trainer. Untested. + loss = loss.mean() # mean() to average on multi-gpu parallel training + return loss.detach() + + def _forward_outputs(self,inputs): + self.zo_forward(self.model,inputs) + return self._last_outputs + + def init_zo(self): + """只保存模型参数、各层输入基和node历史;不创建B、C或常驻hook。""" + self.named_parameters = list(self.model.named_parameters()) # tied权重只出现一次。 + self.parameter_map = dict(self.named_parameters) + self.parameters = list(self.parameter_map.values()) + self.linear_map = { + name+'.weight': module for name, module in self.model.named_modules() + if isinstance(module, torch.nn.Linear) and name+'.weight' in self.parameter_map + } + self.basis = {} + self.history = {} + self.counts = dict(training=0, calibration=0, evaluation=0, diagnostic=0) + + def call(self, inputs, category='training'): + self.counts[category] += 1 + loss, logits = self._forward_outputs(inputs) + if not bool(torch.isfinite(loss).all()): + raise FloatingPointError('Nonfinite loss') + return loss, logits + + def collect_basis(self, inputs, category='training'): + """一次前向读取各Linear的有效token输入,求未中心化激活的首个右奇异向量。""" + mask = inputs['attention_mask'].bool().reshape(-1) + bases, handles = {}, [] + for name, module in self.linear_map.items(): + def capture(module, args, name=name): + x = args[0].reshape(-1, args[0].shape[-1])[mask] + d = top_basis(x).to(dtype=self.parameter_map[name].dtype) + if name in self.basis and float((d.T @ self.basis[name]).sum()) < 0: + d = -d + bases[name] = d + handles.append(module.register_forward_pre_hook(capture)) + try: + self.call(inputs, category) + finally: + for handle in handles: + handle.remove() + if len(bases) != len(self.linear_map): + raise RuntimeError('Not every linear layer executed') + return bases + + def configure_basis(self, inputs): + self.basis = self.collect_basis(inputs, 'calibration') + self.model.requires_grad_(False) + + def directions(self, seed): + """按种子逐参数重建方向;不保存全模型噪声。Linear方向为z @ D.T。""" + generator = torch.Generator(device=self.args.device).manual_seed(seed) + for name, p in self.named_parameters: + z = torch.randn((p.shape[0], 1) if name in self.basis else p.shape, + device=p.device, dtype=p.dtype, generator=generator) + yield name, p, z + + def shifted(self, inputs, bases, seed, scale, response=None): + """原地加扰动查询,再按同一种子减回;无权重备份,FP32恢复允许舍入误差。""" + applied = 0 + try: + for name, p, z in self.directions(seed): + direction = z if response is None else z * response + if name in bases: + direction = direction @ bases[name].T + p.add_(direction, alpha=scale) + applied += 1 + return self.call(inputs)[0].detach().clone() + finally: + # 前向异常也减回;扰动中途失败时,只恢复已经加过扰动的参数。 + for index, (name, p, z) in enumerate(self.directions(seed)): + if index >= applied: + break + direction = z if response is None else z * response + if name in bases: + direction = direction @ bases[name].T + p.add_(direction, alpha=-scale) + + def zo_step(self, model, inputs, seed): + clean = self.call(inputs)[0] + plus = self.shifted(inputs, self.basis, seed, self.args.zo_eps) + slope = float((plus - clean).double().mean()) / self.args.zo_eps + if not math.isfinite(slope): + raise FloatingPointError('Nonfinite ZO response') + self.projected_grad = slope + self._estimate = dict(seed=seed, clean=clean, slope=slope) + return clean.mean() + + @torch.no_grad() + def coverage_gradient_probe(self, inputs, seed, node_seed, targets): + """Two ordinary ZO queries plus one joint node query. + + At fixed weights/bases, estimate 2 (I-dd.T) G.T G d without history. + See HISTORY_FREE_COVERAGE.md for the linear-response proof and bias. + Clean hooks retain only X.T @ signs; perturbed downstream inputs must + not replace these clean sketches. Only selected output-sized Gaussian + vectors are retained, never full parameter noise or activations. + + This helper does not select/install bases; coverage_step owns the update. + The pending SGD estimate belongs to the OLD bases: consume it with + zo_update before installing any candidate for the next iteration. + """ + if getattr(self, '_estimate', None) is not None: + raise RuntimeError('Consume the pending weight update before probing') + targets = list(targets) + if not targets or len(set(targets)) != len(targets): + raise ValueError('Coverage targets must be nonempty and unique') + if any(n not in self.basis or n not in self.linear_map for n in targets): + raise ValueError('Coverage targets must be initialized Linear weights') + mu, epsilon = self.args.zo_eps, self.args.node_epsilon + if not all(math.isfinite(x) and x > 0 for x in (mu, epsilon)): + raise ValueError('Coverage perturbation scales must be positive and finite') + aliases = list(self.model.named_parameters(remove_duplicate=False)) + for n in targets: + if sum(p is self.parameter_map[n] for _, p in aliases) != 1: + raise ValueError('Coverage probes require untied target weights') + # Reuse exactly the Gaussian coefficients of the ordinary weight query. + noises = {n: z for n, _, z in self.directions(seed) if n in targets} + sketches = {} + shapes = {} + before = self.used() + + def query(inject): + handles, seen = [], set() + def hook_for(n, index): + def hook(module, args, output): + if n in seen: + raise ValueError('Coverage target Linear must execute once per forward') + seen.add(n) + x = args[0] + if inject and tuple(x.shape) != shapes[n]: + raise ValueError('Coverage target shape changed across queries') + gen = torch.Generator(device=x.device).manual_seed(seed_for(node_seed, index)) + signs = (2*torch.randint(0, 2, x.shape[:-1], device=x.device, + generator=gen)-1).to(x.dtype) + if inject: + return output + epsilon*signs[..., None]*noises[n].flatten() + shapes[n] = tuple(x.shape) + # The scalar loss already contains its batch/token reduction. + # Summation here is essential: another mean changes the gradient. + sketches[n] = x.reshape(-1, x.shape[-1]).T @ signs.reshape(-1, 1) + return hook + try: + for index, n in enumerate(targets): + handles.append(self.linear_map[n].register_forward_hook(hook_for(n, index))) + loss = self.call(inputs)[0] + if seen != set(targets): + raise ValueError('Every coverage target must execute in each forward') + return loss + finally: + for handle in handles: + handle.remove() + + clean = query(False) + plus = self.shifted(inputs, self.basis, seed, mu) + slope = float((plus-clean).double().mean())/mu # Same arithmetic as zo_step. + node_loss = query(True) + node_slope = float((node_loss-clean).double().mean())/epsilon + if not all(math.isfinite(x) for x in (slope, node_slope)): + raise FloatingPointError('Nonfinite coverage response') + gradients = {} + for n in targets: + d, v = self.basis[n], sketches[n] + gradients[n] = 2*slope*node_slope*(v-d*(d*v).sum()) + if not bool(torch.isfinite(gradients[n]).all()): + raise FloatingPointError('Nonfinite coverage gradient') + self._estimate = dict(seed=seed, clean=clean, slope=slope) + return dict(variant='history_free_coverage_probe_v1', gradients=gradients, + response=slope, node_response=node_slope, cost=self.used()-before) + + @torch.no_grad() + def coverage_step(self, inputs, seed): + """Current-batch coverage gradient; old-basis SGD, then retract new bases.""" + step, args = self.state.global_step, self.args + if step == 0 or step % args.refresh_every or self.used()+3 > args.main_forward_budget: + return self.fix_step(inputs, seed) + before = self.used() + node_seed = seed_for(args.seed, 1801, step) + probe = self.coverage_gradient_probe(inputs, seed, node_seed, list(self.basis)) + new, layers = {}, {} + for n, gradient in probe['gradients'].items(): + d = self.basis[n] + candidate = d+args.basis_lr*gradient + norm = float(candidate.norm()) + if not math.isfinite(norm) or norm == 0: + raise FloatingPointError('Nonfinite coverage basis retraction') + new[n] = candidate/norm + layers[n] = dict(gradient_norm=float(gradient.norm()), + overlap=float((d*new[n]).sum().square())) + # The saved response belongs to the old direction. Install only after SGD. + result = self.zo_update(self.model) + self.basis.update(new) + event = dict(step=step, variant='history_free_coverage_gradient_v1', + seed=seed, node_seed=node_seed, response=probe['response'], + node_response=probe['node_response'], basis_lr=args.basis_lr, + layers=layers, cost=self.used()-before-2, total_step_cost=self.used()-before, + main_forwards=self.used(), basis_installation='after_old_basis_sgd') + return result, event + + + def zo_update(self, model): + estimate = self._estimate + lr = self.current_lr + self._estimate = None + slope = estimate['slope'] + square = 0 + for n, p, z in self.directions(estimate['seed']): + g = z.mul_(slope) + square += float(g.float().square().sum()) * lr ** 2 + # Linear: g is [dout, 1]; lift it into the full weight matrix. + delta = g @ self.basis[n].T if n in self.basis else g + p.add_(delta, alpha=-lr) + if n in self.history: + self.history[n].mul_(self.args.history_beta).add_(g, alpha=1 - self.args.history_beta) + return dict(batch_loss=float(estimate['clean'].mean()), response=slope, update_norm=math.sqrt(square), learning_rate=lr) + + def fix_step(self, inputs, seed): + """The basis is initialized once; every step is two forwards and SGD.""" + before = self.used() + self.zo_step(self.model, inputs, seed) + result = self.zo_update(self.model) + assert self.used() - before == 2 + return result, None + + + def adjust_step(self, inputs, seed): + """Every r updates, compare one old/new virtual SGD step.""" + args = self.args + step = self.state.global_step + event = None + due = step > 0 and step % args.refresh_every == 0 + if due and self.used() + 6 + 2 <= args.main_forward_budget: + before = self.used() + new = self.collect_basis(self.probe_batch()) + trial = self.adjust_probe(self.probe_batch(), self.probe_batch(), new, + seed_for(args.seed, 91, step), self.current_lr) + accept = trial['gain'] > 0 + if accept: + self.basis.update(new) + event = dict(step=step, variant='adjust_single_probe_v1', trial=trial, + accepted=bool(accept), main_forwards=self.used(), cost=self.used()-before) + result, _ = self.fix_step(inputs, seed) + return result, event + + def node_step(self, inputs, seed): + """Control: refresh every r updates, without comparing old/new bases.""" + args = self.args + step = self.state.global_step + cost = 1 + len(self.history) * args.node_queries + due = step > 0 and step % args.refresh_every == 0 + if not due or self.used() + cost + 2 > args.main_forward_budget: + return self.fix_step(inputs, seed) + before = self.used() + new, metrics = self.node_proposal(self.probe_batch(), seed_for(args.seed, 705, step)) + self.basis.update(new) + for name in new: + self.history[name].zero_() + event = dict(step=step, variant='node_unconditional_refresh_control_v1', layers=metrics, + learning_rate=self.current_lr, accepted=bool(new), + main_forwards=self.used(), cost=self.used()-before) + return self.fix_step(inputs, seed)[0], event + + def adjust_probe(self, inputs, reference, new, seed, lr): + clean = self.call(inputs)[0] + a0 = float((self.shifted(inputs, self.basis, seed, self.args.zo_eps) - clean).double().mean()) / self.args.zo_eps + a1 = float((self.shifted(inputs, new, seed, self.args.zo_eps) - clean).double().mean()) / self.args.zo_eps + l0 = self.shifted(reference, self.basis, seed, -lr, response=a0) + l1 = self.shifted(reference, new, seed, -lr, response=a1) + return dict(gain=float((l0 - l1).double().mean()), old_loss=float(l0.mean()), new_loss=float(l1.mean())) + + @torch.no_grad() + def curvature_refresh(self, batches, seed, tangent_seed, *, certified_smoothness=None, + basis_lr, basis_radius): + """Plan section 6: full n=1 anisotropic objective, 13 main forwards. + + Caller supplies independent A/B/C batches and a proven global L for F. + Numeric positivity below does not certify L. This conditional API is not + With certified_smoothness=None, explicitly use the user-authorized local + Hessian engineering variant; no upper-bound guarantee is claimed. + """ + mu, lr = self.args.zo_eps, self.current_lr + values = (basis_lr, basis_radius, mu, lr) + if certified_smoothness is not None: + values += (certified_smoothness,) + if not all(math.isfinite(x) and x > 0 for x in values): + raise ValueError('Curvature selection requires positive finite L, rho, delta, mu and eta') + if len(batches) != 3 or not self.basis: + raise ValueError('Curvature selection requires three independent batches and initialized bases') + before = self.used() + generator = torch.Generator(device=self.args.device).manual_seed(tangent_seed) + tangents, plus, minus = {}, {}, {} + for name, d in self.basis.items(): + v = torch.randn(d.shape, device=d.device, dtype=d.dtype, generator=generator) + v -= d * (d * v).sum() # Tangent Gaussian; do not normalize v. + tangents[name] = v + plus[name] = torch.nn.functional.normalize(d + basis_radius*v, dim=0) + minus[name] = torch.nn.functional.normalize(d - basis_radius*v, dim=0) + # Stream the shared latent noise. Unit bases imply ||U z||^2=||z||^2. + norm_square = sum(float(z.double().square().sum()) for _, _, z in self.directions(seed)) + clean_c = self.call(batches[2])[0].detach().clone().double().mean() + scores, observations = [], [] + for bases in (plus, minus): + responses = [] + for batch in batches[:2]: + fp = self.shifted(batch, bases, seed, mu).double().mean() + fm = self.shifted(batch, bases, seed, -mu).double().mean() + responses.append(float(fp-fm)/(2*mu)) + fp = self.shifted(batches[2], bases, seed, mu).double().mean() + fm = self.shifted(batches[2], bases, seed, -mu).double().mean() + curvature = float(fp-2*clean_c+fm)/mu**2 + upper_curvature = curvature + (0. if certified_smoothness is None else 2*certified_smoothness*norm_square) + score = responses[0]*responses[1]*(1-lr*upper_curvature/2) + scores.append(score) + observations.append(dict(responses=responses, curvature=curvature, + upper_curvature=upper_curvature, score=score)) + q = (scores[0]-scores[1])/(2*basis_radius) + if not all(math.isfinite(x) for x in (*scores, q)): + raise FloatingPointError('Nonfinite curvature basis score/gradient') + updated, overlaps = {}, {} + gradient_square = 0. + for name, d in self.basis.items(): + gradient = q*tangents[name] # Keep magnitude; no sign or clipping. + candidate = d + basis_lr*gradient + norm = float(candidate.double().norm()) + if not math.isfinite(norm) or norm == 0: + raise FloatingPointError('Nonfinite curvature basis update') + updated[name] = candidate/norm + gradient_square += float(gradient.double().square().sum()) + overlaps[name] = float((d.double()*updated[name].double()).sum().square()) + assert self.used()-before == 13 + self.basis.update(updated) + return dict(variant='local_curvature_gradient_v1' if certified_smoothness is None else 'curvature_descent_cross_batch_v1', cost=self.used()-before, + curvature_quantity='local_hessian' if certified_smoothness is None else 'certified_quadratic_upper_bound', + main_forwards=self.used(), seed=seed, tangent_seed=tangent_seed, + certified_smoothness=certified_smoothness, basis_lr=basis_lr, + basis_radius=basis_radius, weight_radius=mu, learning_rate=lr, + probes=observations, score_difference=scores[0]-scores[1], + difference_quotient=q, gradient_norm=math.sqrt(gradient_square), + direction_norm_square=norm_square, overlaps=overlaps) + + @torch.no_grad() + def curvature_step(self, inputs, seed, *, selection_batches, certified_smoothness=None, + basis_lr, basis_radius): + """Conditional full step; inputs/seed must be fresh versus selection. + + selection_batches is a callable drawing independent A/B/C on refresh only. + Existing HF RandomSampler training is not asserted to be an iid oracle. + """ + step = self.state.global_step + event = None + if step > 0 and step % self.args.refresh_every == 0 and self.used()+15 <= self.args.main_forward_budget: + selection_seed = seed_for(self.args.seed, 1701, step) + tangent_seed = seed_for(self.args.seed, 1702, step) + if seed == selection_seed: + raise ValueError('Training and selection directions must have independent seeds') + event = self.curvature_refresh(selection_batches(), selection_seed, tangent_seed, + certified_smoothness=certified_smoothness, basis_lr=basis_lr, + basis_radius=basis_radius) + event['step'] = step + return self.fix_step(inputs, seed)[0], event + + def configure_history(self): + names = [n for n in self.basis if n.endswith('self_attn.v_proj.weight')] + if len(names) < 3: + raise ValueError('Node proposal needs three v_proj layers') + ids = sorted(set((min(len(names) - 1, int(len(names) * v / 24)) for v in (15, 17, 19)))) + if len(ids) < 3: + ids = list(range(len(names) - 3, len(names))) + self.history = {names[i]: self.parameter_map[names[i]].new_zeros(self.parameter_map[names[i]].shape[0], 1) for i in ids} + + def node_proposal(self, inputs, seed): + """Estimate G.T @ p using node probes, then normalize it into a basis. + + p is the normalized EMA of projected coefficient gradients G @ d. + The sketch estimates a vector, not the scalar coverage s = ||G @ d||^2. + """ + clean, logits = self.call(inputs) + mask = inputs['attention_mask'].bool() + new = {} + metrics = {} + if self.args.task_name.lower() == 'sst2': + residual = logits.softmax(1)[:, 1] - inputs['labels'] + margin = logits[:, 1] - logits[:, 0] + for ni, (n, hist) in enumerate(self.history.items()): + norm = float(hist.norm()) + if norm <= 1e-20: + metrics[n] = {'skipped': 'zero history'} + continue + p = hist.flatten() / norm + est = [] + for k in range(self.args.node_queries): + gen = torch.Generator(device=self.args.device).manual_seed(seed_for(seed, ni, k)) + eta = (torch.randint(0, 2, mask.shape, generator=gen, device=self.args.device) * 2 - 1) * mask + features = {} + + def hook(mod, args, output): + x = args[0].reshape(*mask.shape, -1) + features['x'] = (x * eta[:, :, None]).sum(1) + return output + (self.args.node_epsilon * eta[:, :, None] * p).reshape_as(output) + handle = self.linear_map[n].register_forward_hook(hook) + try: + pert_loss, pert_logits = self.call(inputs) + finally: + handle.remove() + if self.args.task_name.lower() == 'sst2': + d = residual * (pert_logits[:, 1] - pert_logits[:, 0] - margin) / self.args.node_epsilon + else: + d = (pert_loss - clean) / self.args.node_epsilon + est.append((features['x'] * d[:, None]).mean(0)) + sketch = torch.stack(est).mean(0) + sn = float(sketch.norm()) + if sn <= 1e-20: + metrics[n] = {'skipped': 'zero sketch'} + continue + d = sketch[:, None] / sn + old = self.basis[n] + if float((d.T @ old).sum()) < 0: + d = -d + new[n] = d + metrics[n] = dict(history_norm=norm, sketch_norm=sn, overlap=float((d.T @ old).square().sum())) + return (new, metrics) + + def descent_probe(self, inputs, candidates, seed, lr): + """Predict the actual one-sided SGD step from three same-batch loss values. + + Exact for a quadratic objective; no virtual update or diagnostic gradient. + All candidates share the clean forward and coefficient-space Gaussian z. + """ + mu = self.args.zo_eps + clean = self.call(inputs)[0].detach().clone() + trials = [] + for bases in candidates: + plus = self.shifted(inputs, bases, seed, mu) + minus = self.shifted(inputs, bases, seed, -mu) + slope = float((plus.double() - minus.double()).mean()) / (2 * mu) + curvature = float((plus.double() - 2 * clean.double() + minus.double()).mean()) / mu ** 2 + response = float((plus - clean).double().mean()) / mu + first_order = lr * slope * response + second_order = 0.5 * lr ** 2 * response ** 2 * curvature + predicted = first_order - second_order + if not all((math.isfinite(v) for v in (slope, curvature, response, predicted))): + raise FloatingPointError('Nonfinite node descent prediction') + trials.append(dict(clean_loss=float(clean.double().mean()), plus_loss=float(plus.double().mean()), minus_loss=float(minus.double().mean()), slope=slope, curvature=curvature, response=response, first_order=first_order, second_order=second_order, predicted_descent=predicted)) + return trials + + def used(self):return self.counts['training']+self.counts['calibration'] + + def learning_rate_at(self,q): + a=self.args + if a.zo_schedule=='constant':return a.learning_rate + f=min(1,max(0,(q-a.decay_start)/max(1,a.main_forward_budget-a.decay_start))) + return a.lr_min+(a.learning_rate-a.lr_min)*.5*(1+math.cos(math.pi*f)) + + def progress(self,stage): + out=Path(self.args.output_dir);point=self.curve[-1] if self.curve else None + best=min(self.curve,key=lambda p:p['development']['loss']) if self.curve else None + value=dict(stage=stage,completed=self.used(),total=self.args.main_forward_budget,current_unit=self.args.trainer,pid=os.getpid(),output_directory=str(out), + elapsed_seconds=time.monotonic()-self.started,last_update=datetime.now(timezone.utc).isoformat(),step=self.state.global_step,latest_training_batch=self.latest,evaluation=point,query_counts=self.counts.copy(), + best_development=None if best is None else {'loss':best['development']['loss'],'main_forwards':best['main_forwards']},current_lr=self.current_lr,memory=memory(),data_protocol=self.args.data_protocol) + save(out/'progress.json',value) + text=f"# {self.args.trainer}: {stage}\n\nMain forwards: {self.used()}/{self.args.main_forward_budget}; updates: {self.state.global_step}; PID: {os.getpid()}\n\nLatest batch: {self.latest}\n\nLast evaluation (actual query count): {point}\n\nBest development: {value['best_development']}\n\nLR: {self.current_lr}; elapsed: {value['elapsed_seconds']:.1f}s\n\nUpdated UTC: {value['last_update']}\n" + tmp=out/'progress.md.tmp';tmp.write_text(text);tmp.replace(out/'progress.md') + print(value,flush=True) + + def collate(self,indices,dataset=None): + dataset=self.train_dataset if dataset is None else dataset + return self._prepare_inputs(self.data_collator([dataset[int(i)] for i in indices])) + + @torch.no_grad() + def evaluate_dataset(self,dataset,indices=None): + indices=list(range(len(dataset))) if indices is None else list(indices) + total=weight_sum=correct=label_count=0 + size=self.args.per_device_eval_batch_size + for start in range(0,len(indices),size): + chosen=indices[start:start+size];inputs=self.collate(chosen,dataset) + losses,logits=self.call(inputs,'evaluation') + weight=self.loss_backend.last_weight if self.args.data_protocol=='mezo' else len(chosen) + total+=float(losses.double().mean())*weight;weight_sum+=weight + if self.args.task_name=='SST2': + correct+=int((logits.argmax(1)==inputs['labels']).sum());label_count+=len(inputs['labels']) + result=dict(loss=total/weight_sum,examples=len(indices)) + if label_count:result['accuracy']=correct/label_count + return result + + def measure(self): + point=dict(step=self.state.global_step,main_forwards=self.used(),elapsed_seconds=time.monotonic()-self.started, + train_probe=self.evaluate_dataset(self.train_dataset,range(min(128,len(self.train_dataset)))),development=self.evaluate_dataset(self.eval_dataset)) + if getattr(self.args, 'select_best_checkpoint', False) and self.state.global_step > 0: + if not hasattr(self, 'best_checkpoint') or point['development']['loss'] < self.best_checkpoint['development']['loss']: + self.save_model(str(Path(self.args.output_dir)/'best_model')) + self.best_checkpoint = dict(step=point['step'], main_forwards=point['main_forwards'], + development=point['development'], criterion='minimum development loss', + evaluation_forwards=self.counts['evaluation']) + save(Path(self.args.output_dir)/'best_checkpoint.json', self.best_checkpoint) + self.curve.append(point);out=Path(self.args.output_dir);save(out/'curve.json',self.curve);figures(out,self.curve);self.progress('evaluation') + + @torch.no_grad() + def restore_best_model(self): + """Stream saved tensors into the existing model, preserving tied weights.""" + import json + from safetensors import safe_open + folder = Path(self.args.output_dir)/'best_model' + index = folder/'model.safetensors.index.json' + files = sorted(set(json.loads(index.read_text())['weight_map'].values())) if index.exists() else ['model.safetensors'] + state = self.model.state_dict() # References, not a weight snapshot. + key = lambda t: (t.data_ptr(), t.storage_offset(), tuple(t.shape)) + missing = {key(t) for t in state.values()} + for filename in files: + with safe_open(str(folder/filename), framework='pt', device='cpu') as handle: + for name in handle.keys(): + state[name].copy_(handle.get_tensor(name)) + missing.discard(key(state[name])) + if missing: + raise RuntimeError('Best checkpoint does not cover all model tensors') + + @torch.no_grad() + def _inner_training_loop(self,batch_size=None,args=None,resume_from_checkpoint=None,trial=None,ignore_keys_for_eval=None): + args=args or self.args + if resume_from_checkpoint:raise ValueError('Resume is not implemented; use a fresh run or load a merged HF model for inference') + self._train_batch_size=batch_size or args.per_device_train_batch_size + out=Path(args.output_dir);self.progress('calibration') + try: + self.configure_basis(self.collate(range(min(args.calibration_samples,len(self.train_dataset))))) + local_curvature = args.trainer=='node' and getattr(args,'node_update','original')=='local_curvature' + history_free = args.trainer=='node' and getattr(args,'node_update','original')=='history_free' + if args.trainer=='node' and not (local_curvature or history_free):self.configure_history() + save(out/'parameter_inventory.json',dict(unique_tensors=len(self.parameters),unique_parameters=sum(p.numel() for p in self.parameters), + structured_weights=len(self.basis),node_targets=list(self.basis) if history_free else list(self.history),coverage='direct_weights_inplace_v2: Linear low-rank SGD on W; dense embedding/norm/bias SGD; tied head once')) + if args.preflight_only: + inputs=self.collate(range(min(2,len(self.train_dataset))));before=self.call(inputs,'diagnostic')[0].clone() + self.shifted(inputs,self.basis,71,args.zo_eps) + torch.testing.assert_close(before,self.call(inputs,'diagnostic')[0],rtol=1e-5,atol=1e-6) + self.basis.update({n:-d for n,d in self.basis.items()}) + torch.testing.assert_close(before,self.call(inputs,'diagnostic')[0],rtol=1e-5,atol=1e-6) + save(out/'preflight.json',dict(passed=True,counts=self.counts));self.progress('complete') + return TrainOutput(0,0.,{'main_forwards':self.used()}) + dataloader=self.get_train_dataloader();iterator=iter(dataloader) + rng_probe=np.random.default_rng(seed_for(args.seed,12)) + def probe_batch(): + ids=rng_probe.choice(len(self.train_dataset),min(args.per_device_train_batch_size,len(self.train_dataset)),replace=False) + return self.collate(ids) + self.probe_batch = probe_batch + # Independent selection draws; preserve the author's HF training sampler. + rng_selection = np.random.default_rng(seed_for(args.seed,1710)) + def selection_batches(): + return [self.collate(rng_selection.choice(len(self.train_dataset), + args.per_device_train_batch_size,replace=False)) for _ in range(3)] + self.measure();next_eval=args.eval_main_forwards;sum_loss=0. + while self.used()+2<=args.main_forward_budget and (args.max_steps<=0 or self.state.global_step=next_eval:self.measure();next_eval=(self.used()//args.eval_main_forwards+1)*args.eval_main_forwards + if self.curve[-1]['main_forwards']!=self.used():self.measure() + save(out/'query_ledger.json',dict(main_forwards=self.used(),counts=self.counts,all_detection_charged=True,evaluations_separate=True)) + if getattr(args, 'select_best_checkpoint', False):self.restore_best_model() + save(out/'summary.json',dict(status='complete',steps=self.state.global_step,main_forwards=self.used(),counts=self.counts,memory=memory(),elapsed_seconds=time.monotonic()-self.started,data_protocol=args.data_protocol, + evaluated_weights='development_best' if getattr(args,'select_best_checkpoint',False) else 'final_iterate', + best_checkpoint=getattr(self,'best_checkpoint',None))) + if args.save_final_checkpoint:self.save_model(str(out/'model')) + self.progress('complete') + return TrainOutput(self.state.global_step,sum_loss/max(1,self.state.global_step),{'main_forwards':self.used()}) + except BaseException: + import traceback + save(out/'failure.json',{'traceback':traceback.format_exc()});self.progress('failed');raise + + @torch.no_grad() + def save_model(self, output_dir=None, _internal_call=False): + """W already contains all learned updates; export an ordinary HF model.""" + out = Path(output_dir or self.args.output_dir) + out.mkdir(parents=True, exist_ok=True) + self.model.save_pretrained(out) + self.processing_class.save_pretrained(out) + save(out/'weights_export.json', dict(format='Standard HF weights', + parameterization='direct_weights_inplace_v2', resume_supported=False, + source_protocol=self.args.data_protocol)) diff --git a/methods/large_models/utils.py b/methods/large_models/utils.py new file mode 100644 index 0000000..c39cd10 --- /dev/null +++ b/methods/large_models/utils.py @@ -0,0 +1,355 @@ +import json +import os +import contextlib +from typing import Optional, Union +import numpy as np +from dataclasses import dataclass, is_dataclass, asdict +import logging +import time +from torch.nn import CrossEntropyLoss +import torch.nn.functional as F +from transformers.modeling_outputs import CausalLMOutputWithPast +import torch +from transformers.utils import PaddingStrategy +from transformers import PreTrainedTokenizerBase +from transformers.data.data_collator import DataCollatorMixin +import transformers +from typing import Optional, Union, List, Dict, Any +import signal +from subprocess import call +from collections.abc import Mapping +from typing import Any, Callable, Dict, List, NewType, Optional, Tuple, Union +InputDataClass = NewType("InputDataClass", Any) +from dataclasses import dataclass +from transformers.tokenization_utils_base import PreTrainedTokenizerBase + + + +logger = logging.getLogger(__name__) + + +def forward_wrap_with_option_len(self, input_ids=None, labels=None, option_len=None, num_options=None, return_dict=None, **kwargs): + """ + This is to replace the original forward function of Transformer models to enable: + (1) Partial target sequence: loss will only be calculated on part of the sequence + (2) Classification-style training: a classification loss (CE) will be calculated over several options + Input: + - input_ids, labels: same as the original forward function + - option_len: a list of int indicating the option lengths, and loss will be calculated only on the + last option_len tokens + - num_options: a list of int indicating the number of options for each example (this will be #label + words for classification tasks and #choices for multiple choice tasks), and a classification loss + will be calculated. + """ + outputs = self.original_forward(input_ids=input_ids, **kwargs) + if labels is None: + return outputs + logits = outputs.logits + + loss = None + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + # Here we use input_ids (which should always = labels) bc sometimes labels are correct candidate IDs + shift_labels = torch.clone(input_ids)[..., 1:].contiguous() + shift_labels[shift_labels == self.config.pad_token_id] = -100 + + # Apply option len (do not calculate loss on the non-option part) + for _i, _len in enumerate(option_len): + shift_labels[_i, :-_len] = -100 + + # Calculate the loss + loss_fct = CrossEntropyLoss(ignore_index=-100) + if num_options is not None: + # Train as a classification tasks + log_probs = F.log_softmax(shift_logits, dim=-1) + mask = shift_labels != -100 # Option part + shift_labels[~mask] = 0 # So that it doesn't mess up with indexing + + selected_log_probs = torch.gather(log_probs, dim=-1, index=shift_labels.unsqueeze(-1)).squeeze(-1) # (bsz x num_options, len) + selected_log_probs = (selected_log_probs * mask).sum(-1) / mask.sum(-1) # (bsz x num_options) + + if any([x != num_options[0] for x in num_options]): + # Multi choice tasks with different number of options + loss = 0 + start_id = 0 + count = 0 + while start_id < len(num_options): + end_id = start_id + num_options[start_id] + _logits = selected_log_probs[start_id:end_id].unsqueeze(0) # (1, num_options) + _labels = labels[start_id:end_id][0].unsqueeze(0) # (1) + loss = loss_fct(_logits, _labels) + loss + count += 1 + start_id = end_id + loss = loss / count + else: + num_options = num_options[0] + selected_log_probs = selected_log_probs.view(-1, num_options) # (bsz, num_options) + labels = labels.view(-1, num_options)[:, 0] # Labels repeat so we only take the first one + loss = loss_fct(selected_log_probs, labels) + else: + loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[1:] + return (loss,) + output if loss is not None else output + + return CausalLMOutputWithPast( + loss=loss, + logits=logits, + past_key_values=outputs.past_key_values, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +def encode_prompt(task, template, train_samples, eval_sample, tokenizer, max_length, sfc=False, icl_sfc=False, generation=False, generation_with_gold=False, max_new_tokens=None): + """ + Encode prompts for eval_sample + Input: + - task, template: task and template class + - train_samples, eval_sample: demonstrations and the actual sample + - tokenizer, max_length: tokenizer and max length + - sfc: generate prompts for calibration (surface form competition; https://arxiv.org/abs/2104.08315) + - icl_sfc: generate prompts for ICL version calibration + - generation: whether it is an generation task + - generation_with_gold: whether to include the generation-task gold answers (for training) + - max_new_tokens: max number of new tokens to generate so that we can save enough space + (only for generation tasks) + Output: + - encodings: a list of N lists of tokens. N is the number of options for classification/multiple-choice. + - option_lens: a list of N integers indicating the number of option tokens. + """ + + # Demonstrations for ICL + train_prompts = [template.verbalize(sample, sample.correct_candidate).strip() for sample in train_samples] + train_prompts = task.train_sep.join(train_prompts).strip() + + # sfc or icl_sfc indicates that this example is used for calibration + if sfc or icl_sfc: + encode_fn = template.encode_sfc; verbalize_fn = template.verbalize_sfc + else: + encode_fn = template.encode; verbalize_fn = template.verbalize + + unverbalized_eval_prompt = encode_fn(eval_sample).strip(' ') + if not generation: + # We generate one prompt for each candidate (different classes in classification) + # or different choices in multiple-choice tasks + verbalized_eval_prompts = [verbalize_fn(eval_sample, cand).strip(' ') for cand in eval_sample.candidates] + unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt)) + option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts] + + if sfc: + # Without demonstrations + final_prompts = verbalized_eval_prompts + else: + # With demonstrations + final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts] + else: + assert not sfc and not icl_sfc, "Generation tasks do not support SFC" + if generation_with_gold: + verbalized_eval_prompts = [verbalize_fn(eval_sample, eval_sample.correct_candidate)] + unverbalized_eval_prompt_length = len(tokenizer.encode(unverbalized_eval_prompt)) + option_lens = [(len(tokenizer.encode(verbalized_eval_prompt)) - unverbalized_eval_prompt_length) for verbalized_eval_prompt in verbalized_eval_prompts] + final_prompts = [(train_prompts + task.train_sep + eval_prompt).lstrip().strip(' ') for eval_prompt in verbalized_eval_prompts] + else: + option_lens = [0] + final_prompts = [(train_prompts + task.train_sep + unverbalized_eval_prompt).lstrip().strip(' ')] + + # Tokenize + encodings = [tokenizer.encode(final_prompt) for final_prompt in final_prompts] + + # Truncate (left truncate as demonstrations are less important) + if generation and max_new_tokens is not None: + max_length = max_length - max_new_tokens + + if any([len(encoding) > max_length for encoding in encodings]): + logger.warn("Exceed max length") + if getattr(tokenizer, "add_bos_token", False): + encodings = [encoding[0:1] + encoding[1:][-(max_length-1):] for encoding in encodings] + else: + encodings = [encoding[-max_length:] for encoding in encodings] + + return encodings, option_lens + + + +@dataclass +class ICLCollator: + """ + Collator for ICL + """ + tokenizer: PreTrainedTokenizerBase + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + if not isinstance(features[0], Mapping): + features = [vars(f) for f in features] + first = features[0] + batch = {} + + pad_id = self.tokenizer.pad_token_id + + pad_ids = {"input_ids": pad_id, "attention_mask": 0, "sfc_input_ids": pad_id, "sfc_attention_mask": 0, "labels": pad_id} + for key in first: + pp = pad_ids[key] + lens = [len(f[key]) for f in features] + max_len = max(lens) + feature = np.stack([np.pad(f[key], (0, max_len - lens[i]), "constant", constant_values=(0, pp)) for i, f in enumerate(features)]) + padded_feature = torch.from_numpy(feature).long() + batch[key] = padded_feature + + return batch + + +@dataclass +class DataCollatorWithPaddingAndNesting: + """ + Collator for training + """ + + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str, PaddingStrategy] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + return_tensors: str = "pt" + + def __call__(self, features: List[Dict[str, Any]]) -> Dict[str, Any]: + features = [ff for f in features for ff in f] + batch = self.tokenizer.pad( + features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors=self.return_tensors, + ) + if "label" in batch: + batch["labels"] = batch["label"] + del batch["label"] + if "label_ids" in batch: + batch["labels"] = batch["label_ids"] + del batch["label_ids"] + return batch + + +@dataclass +class NondiffCollator(DataCollatorMixin): + """ + Collator for non-differentiable objectives + """ + tokenizer: PreTrainedTokenizerBase + padding: Union[bool, str, PaddingStrategy] = True + max_length: Optional[int] = None + pad_to_multiple_of: Optional[int] = None + label_pad_token_id: int = -100 + return_tensors: str = "pt" + + def torch_call(self, features): + import torch + + label_name = "label" if "label" in features[0].keys() else "labels" + labels = [feature[label_name] for feature in features] if label_name in features[0].keys() else None + + no_labels_features = [{k: v for k, v in feature.items() if k != label_name and k != "gold"} for feature in features] + + batch = self.tokenizer.pad( + no_labels_features, + padding=self.padding, + max_length=self.max_length, + pad_to_multiple_of=self.pad_to_multiple_of, + return_tensors="pt", + ) + + if labels is None: + return batch + + sequence_length = batch["input_ids"].shape[1] + padding_side = self.tokenizer.padding_side + + def to_list(tensor_or_iterable): + if isinstance(tensor_or_iterable, torch.Tensor): + return tensor_or_iterable.tolist() + return list(tensor_or_iterable) + + if padding_side == "right": + batch[label_name] = [ + to_list(label) + [self.label_pad_token_id] * (sequence_length - len(label)) for label in labels + ] + else: + batch[label_name] = [ + [self.label_pad_token_id] * (sequence_length - len(label)) + to_list(label) for label in labels + ] + + batch[label_name] = torch.tensor(batch[label_name], dtype=torch.int64) + if "gold" in features[0]: + batch["gold"] = [feature["gold"] for feature in features] + + return batch + + +class SIGUSR1Callback(transformers.TrainerCallback): + """ + This callback is used to save the model when a SIGUSR1 signal is received + (SLURM stop signal or a keyboard interruption signal). + """ + + def __init__(self) -> None: + super().__init__() + self.signal_received = False + signal.signal(signal.SIGUSR1, self.handle_signal) + signal.signal(signal.SIGINT, self.handle_signal) + logger.warn("Handler registered") + + def handle_signal(self, signum, frame): + self.signal_received = True + logger.warn("Signal received") + + def on_step_end(self, args, state, control, **kwargs): + if self.signal_received: + control.should_save = True + control.should_training_stop = True + + def on_train_end(self, args, state, control, **kwargs): + if self.signal_received: + exit(0) + + +@dataclass +class Prediction: + correct_candidate: Union[int, str] + predicted_candidate: Union[int, str] + + +@contextlib.contextmanager +def count_time(name): + logger.info("%s..." % name) + start_time = time.time() + try: + yield + finally: + logger.info("Done with %.2fs" % (time.time() - start_time)) + + +@contextlib.contextmanager +def temp_seed(seed): + state = np.random.get_state() + np.random.seed(seed) + try: + yield + finally: + np.random.set_state(state) + + +class EnhancedJSONEncoder(json.JSONEncoder): + def default(self, o): + if is_dataclass(o): + return asdict(o) + return super().default(o) + + +def write_predictions_to_file(final_preds, output): + with open(output, "w") as f: + for pred in final_preds: + f.write(json.dumps(pred, cls=EnhancedJSONEncoder) + "\n") + + +def write_metrics_to_file(metrics, output): + json.dump(metrics, open(output, "w"), cls=EnhancedJSONEncoder, indent=4) \ No newline at end of file diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..5f276f6 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,9 @@ +[project] +name = "experiments-codebase" +version = "0.1.0" +requires-python = ">=3.13,<3.14" +dependencies = ["torch==2.13.0", "transformers==4.57.1", "huggingface-hub==0.36.0", "datasets==3.6.0", "numpy==2.2.6", "matplotlib==3.10.7", "accelerate==1.12.0", "psutil==7.1.3", "sentencepiece==0.2.1", "scikit-learn==1.7.2", "pytest==8.4.2"] +[tool.uv] +package = false +[tool.pytest.ini_options] +pythonpath = ["src"] diff --git a/reports/agzo_environment.json b/reports/agzo_environment.json new file mode 100644 index 0000000..75af8ed --- /dev/null +++ b/reports/agzo_environment.json @@ -0,0 +1,30 @@ +{ + "python": "3.11.15 (main, Jun 23 2026, 15:19:43) [Clang 22.1.3 ]", + "executable": "/home/gloamxun/experiments_codebase/baselines/agzo/.venv/bin/python", + "paths": { + "models": "/mnt/e/Experiments/Assets/models", + "data": "/mnt/e/Experiments/Assets/data", + "results": "/mnt/e/Experiments/Assets/results" + }, + "versions": { + "torch": "2.13.0", + "transformers": "4.53.2", + "datasets": "2.21.0", + "huggingface-hub": "0.36.0" + }, + "cuda_available": true, + "gpu": "NVIDIA GeForce RTX 5070 Ti", + "capability": [ + 12, + 0 + ], + "cuda_smoke": 2.0, + "sst2": { + "train": 67349, + "validation": 872 + }, + "drop": { + "train": 77400, + "validation": 9535 + } +} diff --git a/reports/checkpoint_restore.json b/reports/checkpoint_restore.json new file mode 100644 index 0000000..c107923 --- /dev/null +++ b/reports/checkpoint_restore.json @@ -0,0 +1,20 @@ +{ + "passed": true, + "model": "Qwen/Qwen3-0.6B", + "task": "sst2", + "before": { + "loss": 0.13995715975761414, + "examples": 2, + "accuracy": 1.0 + }, + "after": { + "loss": 0.13995715975761414, + "examples": 2, + "accuracy": 1.0 + }, + "output": "/mnt/e/Experiments/Assets/results/checkpoint_check_20261110T165316543980Z", + "generation": { + "text": "A wonderful movie It was a great movie." + }, + "scope": "Small real-model training checkpoint, structured hook restoration, evaluation and generation; not performance evidence" +} \ No newline at end of file diff --git a/reports/final_audit.json b/reports/final_audit.json new file mode 100644 index 0000000..205e430 --- /dev/null +++ b/reports/final_audit.json @@ -0,0 +1,185 @@ +{ + "passed": true, + "checked_at": "2026-11-10T16:56:53.304163+00:00", + "validation_checks": 45, + "mechanism_tests": 5, + "checkpoint_roundtrip": { + "passed": true, + "model": "Qwen/Qwen3-0.6B", + "task": "sst2", + "before": { + "loss": 0.13995715975761414, + "examples": 2, + "accuracy": 1.0 + }, + "after": { + "loss": 0.13995715975761414, + "examples": 2, + "accuracy": 1.0 + }, + "output": "/mnt/e/Experiments/Assets/results/checkpoint_check_20261110T165316543980Z", + "generation": { + "text": "A wonderful movie It was a great movie." + }, + "scope": "Small real-model training checkpoint, structured hook restoration, evaluation and generation; not performance evidence" + }, + "environments": { + "ours": { + "python": "3.13.14 (main, Jun 23 2026, 15:18:27) [Clang 22.1.3 ]", + "executable": "/home/gloamxun/experiments_codebase/.venv/bin/python", + "paths": { + "models": "/mnt/e/Experiments/Assets/models", + "data": "/mnt/e/Experiments/Assets/data", + "results": "/mnt/e/Experiments/Assets/results" + }, + "versions": { + "torch": "2.13.0", + "transformers": "4.57.1", + "datasets": "3.6.0", + "huggingface-hub": "0.36.0" + }, + "cuda_available": true, + "gpu": "NVIDIA GeForce RTX 5070 Ti", + "capability": [ + 12, + 0 + ], + "cuda_smoke": 2.0, + "sst2": { + "train": 67349, + "validation": 872 + }, + "drop": { + "train": 77400, + "validation": 9535 + } + }, + "mezo": { + "python": "3.11.15 (main, Jun 23 2026, 15:19:43) [Clang 22.1.3 ]", + "executable": "/home/gloamxun/experiments_codebase/baselines/mezo/.venv/bin/python", + "paths": { + "models": "/mnt/e/Experiments/Assets/models", + "data": "/mnt/e/Experiments/Assets/data", + "results": "/mnt/e/Experiments/Assets/results" + }, + "versions": { + "torch": "2.13.0", + "transformers": "4.28.1", + "datasets": "2.14.7", + "huggingface-hub": "0.36.0" + }, + "cuda_available": true, + "gpu": "NVIDIA GeForce RTX 5070 Ti", + "capability": [ + 12, + 0 + ], + "cuda_smoke": 2.0, + "sst2": { + "train": 67349, + "validation": 872 + }, + "drop": { + "train": 77400, + "validation": 9535 + } + }, + "agzo": { + "python": "3.11.15 (main, Jun 23 2026, 15:19:43) [Clang 22.1.3 ]", + "executable": "/home/gloamxun/experiments_codebase/baselines/agzo/.venv/bin/python", + "paths": { + "models": "/mnt/e/Experiments/Assets/models", + "data": "/mnt/e/Experiments/Assets/data", + "results": "/mnt/e/Experiments/Assets/results" + }, + "versions": { + "torch": "2.13.0", + "transformers": "4.53.2", + "datasets": "2.21.0", + "huggingface-hub": "0.36.0" + }, + "cuda_available": true, + "gpu": "NVIDIA GeForce RTX 5070 Ti", + "capability": [ + 12, + 0 + ], + "cuda_smoke": 2.0, + "sst2": { + "train": 67349, + "validation": 872 + }, + "drop": { + "train": 77400, + "validation": 9535 + } + }, + "lozo": { + "python": "3.11.15 (main, Jun 23 2026, 15:19:43) [Clang 22.1.3 ]", + "executable": "/home/gloamxun/experiments_codebase/baselines/lozo/.venv/bin/python", + "paths": { + "models": "/mnt/e/Experiments/Assets/models", + "data": "/mnt/e/Experiments/Assets/data", + "results": "/mnt/e/Experiments/Assets/results" + }, + "versions": { + "torch": "2.13.0", + "transformers": "4.28.1", + "datasets": "2.14.7", + "huggingface-hub": "0.36.0" + }, + "cuda_available": true, + "gpu": "NVIDIA GeForce RTX 5070 Ti", + "capability": [ + 12, + 0 + ], + "cuda_smoke": 2.0, + "sst2": { + "train": 67349, + "validation": 872 + }, + "drop": { + "train": 77400, + "validation": 9535 + } + }, + "loren": { + "python": "3.11.15 (main, Jun 23 2026, 15:19:43) [Clang 22.1.3 ]", + "executable": "/home/gloamxun/experiments_codebase/baselines/loren/.venv/bin/python", + "paths": { + "models": "/mnt/e/Experiments/Assets/models", + "data": "/mnt/e/Experiments/Assets/data", + "results": "/mnt/e/Experiments/Assets/results" + }, + "versions": { + "torch": "2.13.0", + "transformers": "4.44.2", + "datasets": "2.21.0", + "huggingface-hub": "0.36.0" + }, + "cuda_available": true, + "gpu": "NVIDIA GeForce RTX 5070 Ti", + "capability": [ + 12, + 0 + ], + "cuda_smoke": 2.0, + "sst2": { + "train": 67349, + "validation": 872 + }, + "drop": { + "train": 77400, + "validation": 9535 + } + } + }, + "git": { + "commits": 0, + "staged_files": 0, + "official_source_changes": 0 + }, + "scope": "Small real-model independent execution, dependency and inference checks; no full benchmark or paper accuracy reproduction", + "final_environment_change": "HF defaults initialized before library imports; final modern model/task matrix, doctor in all five environments, mechanism tests and checkpoint roundtrip validate this routing change." +} \ No newline at end of file diff --git a/reports/loren_environment.json b/reports/loren_environment.json new file mode 100644 index 0000000..bbf6d09 --- /dev/null +++ b/reports/loren_environment.json @@ -0,0 +1,30 @@ +{ + "python": "3.11.15 (main, Jun 23 2026, 15:19:43) [Clang 22.1.3 ]", + "executable": "/home/gloamxun/experiments_codebase/baselines/loren/.venv/bin/python", + "paths": { + "models": "/mnt/e/Experiments/Assets/models", + "data": "/mnt/e/Experiments/Assets/data", + "results": "/mnt/e/Experiments/Assets/results" + }, + "versions": { + "torch": "2.13.0", + "transformers": "4.44.2", + "datasets": "2.21.0", + "huggingface-hub": "0.36.0" + }, + "cuda_available": true, + "gpu": "NVIDIA GeForce RTX 5070 Ti", + "capability": [ + 12, + 0 + ], + "cuda_smoke": 2.0, + "sst2": { + "train": 67349, + "validation": 872 + }, + "drop": { + "train": 77400, + "validation": 9535 + } +} diff --git a/reports/lozo_environment.json b/reports/lozo_environment.json new file mode 100644 index 0000000..a2400d9 --- /dev/null +++ b/reports/lozo_environment.json @@ -0,0 +1,30 @@ +{ + "python": "3.11.15 (main, Jun 23 2026, 15:19:43) [Clang 22.1.3 ]", + "executable": "/home/gloamxun/experiments_codebase/baselines/lozo/.venv/bin/python", + "paths": { + "models": "/mnt/e/Experiments/Assets/models", + "data": "/mnt/e/Experiments/Assets/data", + "results": "/mnt/e/Experiments/Assets/results" + }, + "versions": { + "torch": "2.13.0", + "transformers": "4.28.1", + "datasets": "2.14.7", + "huggingface-hub": "0.36.0" + }, + "cuda_available": true, + "gpu": "NVIDIA GeForce RTX 5070 Ti", + "capability": [ + 12, + 0 + ], + "cuda_smoke": 2.0, + "sst2": { + "train": 67349, + "validation": 872 + }, + "drop": { + "train": 77400, + "validation": 9535 + } +} diff --git a/reports/mezo_environment.json b/reports/mezo_environment.json new file mode 100644 index 0000000..1bb27f5 --- /dev/null +++ b/reports/mezo_environment.json @@ -0,0 +1,30 @@ +{ + "python": "3.11.15 (main, Jun 23 2026, 15:19:43) [Clang 22.1.3 ]", + "executable": "/home/gloamxun/experiments_codebase/baselines/mezo/.venv/bin/python", + "paths": { + "models": "/mnt/e/Experiments/Assets/models", + "data": "/mnt/e/Experiments/Assets/data", + "results": "/mnt/e/Experiments/Assets/results" + }, + "versions": { + "torch": "2.13.0", + "transformers": "4.28.1", + "datasets": "2.14.7", + "huggingface-hub": "0.36.0" + }, + "cuda_available": true, + "gpu": "NVIDIA GeForce RTX 5070 Ti", + "capability": [ + 12, + 0 + ], + "cuda_smoke": 2.0, + "sst2": { + "train": 67349, + "validation": 872 + }, + "drop": { + "train": 77400, + "validation": 9535 + } +} diff --git a/reports/mezo_refactor/checkpoint_roundtrip.json b/reports/mezo_refactor/checkpoint_roundtrip.json new file mode 100644 index 0000000..411b1a3 --- /dev/null +++ b/reports/mezo_refactor/checkpoint_roundtrip.json @@ -0,0 +1,50 @@ +{ + "passed": true, + "before": { + "loss": 0.4010155154392123, + "examples": 2, + "accuracy": 0.5 + }, + "after": { + "loss": 0.40101617109030485, + "examples": 2, + "accuracy": 0.5 + }, + "absolute_loss_error": 6.556510925292969e-07, + "reason_for_tolerance": "Merging W+B@D.T changes FP32 operation order; training trajectories are checked exactly before export", + "model": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031900885659Z/model", + "generation": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/merged_checkpoint_generate.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--action", + "generate", + "--checkpoint", + "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031900885659Z/model", + "--prompt", + "A wonderful movie It was", + "--max-new-tokens", + "4", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031920077168Z" + } +} \ No newline at end of file diff --git a/reports/mezo_refactor/extended_validation.json b/reports/mezo_refactor/extended_validation.json new file mode 100644 index 0000000..e729d62 --- /dev/null +++ b/reports/mezo_refactor/extended_validation.json @@ -0,0 +1,415 @@ +{ + "passed": true, + "checks": { + "legacy_fix_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_fix_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "5", + "--refresh-every", + "1", + "--data-protocol", + "legacy", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031733746234Z" + }, + "legacy_adjust_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_adjust_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "17", + "--refresh-every", + "1", + "--data-protocol", + "legacy", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031743161248Z" + }, + "legacy_node_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_node_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--method", + "node", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "13", + "--refresh-every", + "1", + "--data-protocol", + "legacy", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031751567289Z" + }, + "mezo_fix_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_fix_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "5", + "--refresh-every", + "1", + "--data-protocol", + "mezo", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031759302310Z" + }, + "mezo_adjust_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_adjust_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "17", + "--refresh-every", + "1", + "--data-protocol", + "mezo", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031807119167Z" + }, + "mezo_node_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_node_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--method", + "node", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "13", + "--refresh-every", + "1", + "--data-protocol", + "mezo", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031815242198Z" + }, + "mezo_node_qwen_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_node_qwen_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "sst2", + "--budget", + "13", + "--refresh-every", + "1", + "--data-protocol", + "mezo", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031825554100Z" + }, + "mezo_node_qwen_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_node_qwen_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "drop", + "--budget", + "13", + "--refresh-every", + "1", + "--data-protocol", + "mezo", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031849531522Z" + }, + "merged_checkpoint_train": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/merged_checkpoint_train.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "5", + "--data-protocol", + "legacy", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031900885659Z" + }, + "merged_checkpoint_evaluate": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/merged_checkpoint_evaluate.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--action", + "evaluate", + "--checkpoint", + "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031900885659Z/model", + "--task", + "sst2", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031912764789Z" + }, + "merged_checkpoint_generate": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/merged_checkpoint_generate.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--action", + "generate", + "--checkpoint", + "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031900885659Z/model", + "--prompt", + "A wonderful movie It was", + "--max-new-tokens", + "4", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031920077168Z" + } + } +} \ No newline at end of file diff --git a/reports/mezo_refactor/initial_validation_report.json b/reports/mezo_refactor/initial_validation_report.json new file mode 100644 index 0000000..b2cf1bc --- /dev/null +++ b/reports/mezo_refactor/initial_validation_report.json @@ -0,0 +1,255 @@ +{ + "passed": false, + "checks": { + "unit_tests": { + "passed": false, + "returncode": 1, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/unit_tests.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "-m", + "pytest", + "-q", + "tests" + ] + }, + "entry_help": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/entry_help.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--help" + ] + }, + "legacy_fix_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_fix_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "25", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "legacy" + ] + }, + "legacy_adjust_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_adjust_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "45", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "legacy" + ] + }, + "legacy_node_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_node_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--method", + "node", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "45", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "legacy" + ] + }, + "mezo_fix_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_fix_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "25", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "mezo" + ] + }, + "mezo_adjust_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_adjust_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "45", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "mezo" + ] + }, + "mezo_node_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_node_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--method", + "node", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "45", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "mezo" + ] + } + } +} \ No newline at end of file diff --git a/reports/mezo_refactor/paired_equivalence.json b/reports/mezo_refactor/paired_equivalence.json new file mode 100644 index 0000000..11aec87 --- /dev/null +++ b/reports/mezo_refactor/paired_equivalence.json @@ -0,0 +1,272 @@ +{ + "passed": true, + "methods": { + "fix": { + "passed": true, + "updates": 12, + "max_absolute_errors": { + "batch_loss": 0.0, + "response": 0.0, + "update_norm": 0.0 + }, + "same_query_trajectory": true, + "folders": { + "old": "/mnt/e/Experiments/Assets/results/fix_sst2_20261111T031418885033Z", + "new": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031424990588Z" + }, + "old_refresh_events": [], + "new_refresh_events": [], + "same_refresh_events": true + }, + "adjust": { + "passed": true, + "updates": 11, + "max_absolute_errors": { + "batch_loss": 0.0, + "response": 0.0, + "update_norm": 0.0 + }, + "same_query_trajectory": true, + "folders": { + "old": "/mnt/e/Experiments/Assets/results/adjust_sst2_20261111T031431322232Z", + "new": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031438563297Z" + }, + "old_refresh_events": [ + { + "step": 2, + "trials": [ + { + "gain": 8.369113008181253e-05, + "old_loss": 0.896460771560669, + "new_loss": 0.8963770866394043 + }, + { + "gain": 0.00025764728585879004, + "old_loss": 1.894831657409668, + "new_loss": 1.8945739269256592 + } + ], + "mean_gain": 0.00017066920797030127, + "sem": 8.697807788848876e-05, + "accepted": true, + "main_forwards": 16, + "cost": 11 + }, + { + "step": 4, + "trials": [ + { + "gain": 0.004473025600115458, + "old_loss": 0.8813985586166382, + "new_loss": 0.8769254684448242 + }, + { + "gain": 2.588704228401184e-05, + "old_loss": 0.8185362219810486, + "new_loss": 0.8185102939605713 + } + ], + "mean_gain": 0.0022494563211997347, + "sem": 0.002223569278915723, + "accepted": true, + "main_forwards": 31, + "cost": 11 + } + ], + "new_refresh_events": [ + { + "step": 2, + "trials": [ + { + "gain": 8.369113008181253e-05, + "old_loss": 0.896460771560669, + "new_loss": 0.8963770866394043 + }, + { + "gain": 0.00025764728585879004, + "old_loss": 1.894831657409668, + "new_loss": 1.8945739269256592 + } + ], + "mean_gain": 0.00017066920797030127, + "sem": 8.697807788848876e-05, + "accepted": true, + "main_forwards": 16, + "cost": 11 + }, + { + "step": 4, + "trials": [ + { + "gain": 0.004473025600115458, + "old_loss": 0.8813985586166382, + "new_loss": 0.8769254684448242 + }, + { + "gain": 2.588704228401184e-05, + "old_loss": 0.8185362219810486, + "new_loss": 0.8185102939605713 + } + ], + "mean_gain": 0.0022494563211997347, + "sem": 0.002223569278915723, + "accepted": true, + "main_forwards": 31, + "cost": 11 + } + ], + "same_refresh_events": true + }, + "node": { + "passed": true, + "updates": 11, + "max_absolute_errors": { + "batch_loss": 0.0, + "response": 0.0, + "update_norm": 0.0 + }, + "same_query_trajectory": true, + "folders": { + "old": "/mnt/e/Experiments/Assets/results/node_sst2_20261111T031446305709Z", + "new": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031453279675Z" + }, + "old_refresh_events": [ + { + "step": 2, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 26.104965209960938, + "sketch_norm": 3.668133497238159, + "overlap": 0.6362813115119934 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 27.68947982788086, + "sketch_norm": 0.5021779537200928, + "overlap": 0.0945340245962143 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 25.401365280151367, + "sketch_norm": 0.31518134474754333, + "overlap": 0.16355261206626892 + } + }, + "main_forwards": 12, + "cost": 7 + }, + { + "step": 4, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 353.03338623046875, + "sketch_norm": 1.3937129974365234, + "overlap": 0.0828152596950531 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 368.1776428222656, + "sketch_norm": 1.3050999641418457, + "overlap": 0.10932166129350662 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 388.01849365234375, + "sketch_norm": 0.1866365224123001, + "overlap": 0.05388975143432617 + } + }, + "main_forwards": 23, + "cost": 7 + }, + { + "step": 6, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 187.65158081054688, + "sketch_norm": 9.435571670532227, + "overlap": 0.10554195940494537 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 181.28565979003906, + "sketch_norm": 6.177098274230957, + "overlap": 0.008472532033920288 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 182.54153442382812, + "sketch_norm": 1.02308189868927, + "overlap": 5.3368166845757514e-05 + } + }, + "main_forwards": 34, + "cost": 7 + } + ], + "new_refresh_events": [ + { + "step": 2, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 26.104965209960938, + "sketch_norm": 3.668133497238159, + "overlap": 0.6362813115119934 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 27.68947982788086, + "sketch_norm": 0.5021779537200928, + "overlap": 0.0945340245962143 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 25.401365280151367, + "sketch_norm": 0.31518134474754333, + "overlap": 0.16355261206626892 + } + }, + "main_forwards": 12, + "cost": 7 + }, + { + "step": 4, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 353.03338623046875, + "sketch_norm": 1.3937129974365234, + "overlap": 0.0828152596950531 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 368.1776428222656, + "sketch_norm": 1.3050999641418457, + "overlap": 0.10932166129350662 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 388.01849365234375, + "sketch_norm": 0.1866365224123001, + "overlap": 0.05388975143432617 + } + }, + "main_forwards": 23, + "cost": 7 + }, + { + "step": 6, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 187.65158081054688, + "sketch_norm": 9.435571670532227, + "overlap": 0.10554195940494537 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 181.28565979003906, + "sketch_norm": 6.177098274230957, + "overlap": 0.008472532033920288 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 182.54153442382812, + "sketch_norm": 1.02308189868927, + "overlap": 5.3368166845757514e-05 + } + }, + "main_forwards": 34, + "cost": 7 + } + ], + "same_refresh_events": true + } + } +} \ No newline at end of file diff --git a/reports/mezo_refactor/progress.json b/reports/mezo_refactor/progress.json new file mode 100644 index 0000000..f0aa89a --- /dev/null +++ b/reports/mezo_refactor/progress.json @@ -0,0 +1,9 @@ +{ + "stage": "complete", + "completed": 27, + "total": 27, + "current_unit": "MeZO refactor complete", + "pid": 12998, + "output_directory": "/home/gloamxun/experiments_codebase/reports/mezo_refactor", + "last_update": "2026-11-11T03:25:31.803411+00:00" +} \ No newline at end of file diff --git a/reports/mezo_refactor/progress.md b/reports/mezo_refactor/progress.md new file mode 100644 index 0000000..0f05646 --- /dev/null +++ b/reports/mezo_refactor/progress.md @@ -0,0 +1,11 @@ +# MeZO structure refactor complete + +11 numerical/interface tests passed. All three OPT125M paired trajectories match the previous implementation exactly in loss, response, update norm, refresh events and main-forward count. + +Both data protocols passed SST2/DROP short checks; native Qwen/node integration passed. Standard merged HF checkpoint evaluation and generation passed; observed loss difference 6.56e-07 from FP32 merge order. + +Official source hashes unchanged (521 files). Root Git has no commits or staged files. No formal benchmark launched. + +Default data_protocol=legacy; MeZO author sampling/template/objective requires explicit --data_protocol mezo. + +Updated UTC: 2026-11-11T03:25:31.803411+00:00 diff --git a/reports/mezo_refactor/validation_report.json b/reports/mezo_refactor/validation_report.json new file mode 100644 index 0000000..cc94281 --- /dev/null +++ b/reports/mezo_refactor/validation_report.json @@ -0,0 +1,1141 @@ +{ + "passed": true, + "checked_at": "2026-11-11T03:25:31.803411+00:00", + "checks": { + "unit_tests": { + "passed": true, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/unit_final.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "-m", + "pytest", + "-q", + "tests" + ], + "count": 11 + }, + "official_sources_unchanged": { + "passed": true, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/official_sources_final.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "scripts/verify_sources.py" + ] + }, + "entry_help": { + "passed": true, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/entry_help_final.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--help" + ] + }, + "module_help": { + "passed": true, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/module_help_final.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "-m", + "methods.shared_mezo.large_models.run", + "--help" + ] + }, + "public_regression_help": { + "passed": true, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/regression_help_final.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "scripts/validate_mezo_refactor.py", + "--help" + ] + }, + "checkpoint_helper_help": { + "passed": true, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/checkpoint_help_final.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "scripts/validate_checkpoint.py", + "--help" + ] + }, + "paired_fix": { + "passed": true, + "updates": 12, + "max_absolute_errors": { + "batch_loss": 0.0, + "response": 0.0, + "update_norm": 0.0 + }, + "same_query_trajectory": true, + "folders": { + "old": "/mnt/e/Experiments/Assets/results/fix_sst2_20261111T031418885033Z", + "new": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031424990588Z" + }, + "old_refresh_events": [], + "new_refresh_events": [], + "same_refresh_events": true + }, + "paired_adjust": { + "passed": true, + "updates": 11, + "max_absolute_errors": { + "batch_loss": 0.0, + "response": 0.0, + "update_norm": 0.0 + }, + "same_query_trajectory": true, + "folders": { + "old": "/mnt/e/Experiments/Assets/results/adjust_sst2_20261111T031431322232Z", + "new": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031438563297Z" + }, + "old_refresh_events": [ + { + "step": 2, + "trials": [ + { + "gain": 8.369113008181253e-05, + "old_loss": 0.896460771560669, + "new_loss": 0.8963770866394043 + }, + { + "gain": 0.00025764728585879004, + "old_loss": 1.894831657409668, + "new_loss": 1.8945739269256592 + } + ], + "mean_gain": 0.00017066920797030127, + "sem": 8.697807788848876e-05, + "accepted": true, + "main_forwards": 16, + "cost": 11 + }, + { + "step": 4, + "trials": [ + { + "gain": 0.004473025600115458, + "old_loss": 0.8813985586166382, + "new_loss": 0.8769254684448242 + }, + { + "gain": 2.588704228401184e-05, + "old_loss": 0.8185362219810486, + "new_loss": 0.8185102939605713 + } + ], + "mean_gain": 0.0022494563211997347, + "sem": 0.002223569278915723, + "accepted": true, + "main_forwards": 31, + "cost": 11 + } + ], + "new_refresh_events": [ + { + "step": 2, + "trials": [ + { + "gain": 8.369113008181253e-05, + "old_loss": 0.896460771560669, + "new_loss": 0.8963770866394043 + }, + { + "gain": 0.00025764728585879004, + "old_loss": 1.894831657409668, + "new_loss": 1.8945739269256592 + } + ], + "mean_gain": 0.00017066920797030127, + "sem": 8.697807788848876e-05, + "accepted": true, + "main_forwards": 16, + "cost": 11 + }, + { + "step": 4, + "trials": [ + { + "gain": 0.004473025600115458, + "old_loss": 0.8813985586166382, + "new_loss": 0.8769254684448242 + }, + { + "gain": 2.588704228401184e-05, + "old_loss": 0.8185362219810486, + "new_loss": 0.8185102939605713 + } + ], + "mean_gain": 0.0022494563211997347, + "sem": 0.002223569278915723, + "accepted": true, + "main_forwards": 31, + "cost": 11 + } + ], + "same_refresh_events": true + }, + "paired_node": { + "passed": true, + "updates": 11, + "max_absolute_errors": { + "batch_loss": 0.0, + "response": 0.0, + "update_norm": 0.0 + }, + "same_query_trajectory": true, + "folders": { + "old": "/mnt/e/Experiments/Assets/results/node_sst2_20261111T031446305709Z", + "new": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031453279675Z" + }, + "old_refresh_events": [ + { + "step": 2, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 26.104965209960938, + "sketch_norm": 3.668133497238159, + "overlap": 0.6362813115119934 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 27.68947982788086, + "sketch_norm": 0.5021779537200928, + "overlap": 0.0945340245962143 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 25.401365280151367, + "sketch_norm": 0.31518134474754333, + "overlap": 0.16355261206626892 + } + }, + "main_forwards": 12, + "cost": 7 + }, + { + "step": 4, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 353.03338623046875, + "sketch_norm": 1.3937129974365234, + "overlap": 0.0828152596950531 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 368.1776428222656, + "sketch_norm": 1.3050999641418457, + "overlap": 0.10932166129350662 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 388.01849365234375, + "sketch_norm": 0.1866365224123001, + "overlap": 0.05388975143432617 + } + }, + "main_forwards": 23, + "cost": 7 + }, + { + "step": 6, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 187.65158081054688, + "sketch_norm": 9.435571670532227, + "overlap": 0.10554195940494537 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 181.28565979003906, + "sketch_norm": 6.177098274230957, + "overlap": 0.008472532033920288 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 182.54153442382812, + "sketch_norm": 1.02308189868927, + "overlap": 5.3368166845757514e-05 + } + }, + "main_forwards": 34, + "cost": 7 + } + ], + "new_refresh_events": [ + { + "step": 2, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 26.104965209960938, + "sketch_norm": 3.668133497238159, + "overlap": 0.6362813115119934 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 27.68947982788086, + "sketch_norm": 0.5021779537200928, + "overlap": 0.0945340245962143 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 25.401365280151367, + "sketch_norm": 0.31518134474754333, + "overlap": 0.16355261206626892 + } + }, + "main_forwards": 12, + "cost": 7 + }, + { + "step": 4, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 353.03338623046875, + "sketch_norm": 1.3937129974365234, + "overlap": 0.0828152596950531 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 368.1776428222656, + "sketch_norm": 1.3050999641418457, + "overlap": 0.10932166129350662 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 388.01849365234375, + "sketch_norm": 0.1866365224123001, + "overlap": 0.05388975143432617 + } + }, + "main_forwards": 23, + "cost": 7 + }, + { + "step": 6, + "layers": { + "model.decoder.layers.7.self_attn.v_proj.weight": { + "history_norm": 187.65158081054688, + "sketch_norm": 9.435571670532227, + "overlap": 0.10554195940494537 + }, + "model.decoder.layers.8.self_attn.v_proj.weight": { + "history_norm": 181.28565979003906, + "sketch_norm": 6.177098274230957, + "overlap": 0.008472532033920288 + }, + "model.decoder.layers.9.self_attn.v_proj.weight": { + "history_norm": 182.54153442382812, + "sketch_norm": 1.02308189868927, + "overlap": 5.3368166845757514e-05 + } + }, + "main_forwards": 34, + "cost": 7 + } + ], + "same_refresh_events": true + }, + "legacy_fix_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_fix_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "5", + "--refresh-every", + "1", + "--data-protocol", + "legacy", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031733746234Z" + }, + "legacy_adjust_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_adjust_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "17", + "--refresh-every", + "1", + "--data-protocol", + "legacy", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031743161248Z" + }, + "legacy_node_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_node_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--method", + "node", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "13", + "--refresh-every", + "1", + "--data-protocol", + "legacy", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031751567289Z" + }, + "mezo_fix_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_fix_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "5", + "--refresh-every", + "1", + "--data-protocol", + "mezo", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031759302310Z" + }, + "mezo_adjust_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_adjust_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "17", + "--refresh-every", + "1", + "--data-protocol", + "mezo", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031807119167Z" + }, + "mezo_node_opt125_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_node_opt125_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--method", + "node", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "drop", + "--budget", + "13", + "--refresh-every", + "1", + "--data-protocol", + "mezo", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031815242198Z" + }, + "mezo_node_qwen_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_node_qwen_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "sst2", + "--budget", + "13", + "--refresh-every", + "1", + "--data-protocol", + "mezo", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031825554100Z" + }, + "mezo_node_qwen_drop": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_node_qwen_drop.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "drop", + "--budget", + "13", + "--refresh-every", + "1", + "--data-protocol", + "mezo", + "--no-save-checkpoint", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031849531522Z" + }, + "merged_checkpoint_train": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/merged_checkpoint_train.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "5", + "--data-protocol", + "legacy", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031900885659Z" + }, + "merged_checkpoint_evaluate": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/merged_checkpoint_evaluate.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--action", + "evaluate", + "--checkpoint", + "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031900885659Z/model", + "--task", + "sst2", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031912764789Z" + }, + "merged_checkpoint_generate": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/merged_checkpoint_generate.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--action", + "generate", + "--checkpoint", + "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031900885659Z/model", + "--prompt", + "A wonderful movie It was", + "--max-new-tokens", + "4", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031920077168Z" + }, + "merged_checkpoint_numerics": { + "passed": true, + "before": { + "loss": 0.4010155154392123, + "examples": 2, + "accuracy": 0.5 + }, + "after": { + "loss": 0.40101617109030485, + "examples": 2, + "accuracy": 0.5 + }, + "absolute_loss_error": 6.556510925292969e-07, + "reason_for_tolerance": "Merging W+B@D.T changes FP32 operation order; training trajectories are checked exactly before export", + "model": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031900885659Z/model", + "generation": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/merged_checkpoint_generate.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--action", + "generate", + "--checkpoint", + "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031900885659Z/model", + "--prompt", + "A wonderful movie It was", + "--max-new-tokens", + "4", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100" + ], + "output": "/mnt/e/Experiments/Assets/results/mezo_style_20261111T031920077168Z" + } + }, + "initial_legacy_fix_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_fix_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "25", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "legacy" + ] + }, + "initial_legacy_adjust_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_adjust_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "45", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "legacy" + ] + }, + "initial_legacy_node_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/legacy_node_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--method", + "node", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "45", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "legacy" + ] + }, + "initial_mezo_fix_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_fix_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "25", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "mezo" + ] + }, + "initial_mezo_adjust_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_adjust_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "45", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "mezo" + ] + }, + "initial_mezo_node_opt125_sst2": { + "passed": true, + "returncode": 0, + "log": "/home/gloamxun/experiments_codebase/reports/mezo_refactor/mezo_node_opt125_sst2.log", + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "methods/node/run.py", + "--method", + "node", + "--model", + "/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots/27dcfa74d334bc871f3234de431e71c6eeba5dd6", + "--task", + "sst2", + "--budget", + "45", + "--train-samples", + "10", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "3", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--refresh-every", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint", + "--data-protocol", + "mezo" + ] + } + }, + "source_sha256": { + "methods/shared_mezo/__init__.py": "9879f7275808db88394b34d906a0e9ad85ee1dcb09ef388ba9421cb5dc4480f7", + "methods/shared_mezo/large_models/losses.py": "36b4f646a7f68913ac6832c137575565cb6b31d9e38c6cd2480288c59d3f949d", + "methods/shared_mezo/large_models/templates.py": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6", + "methods/shared_mezo/large_models/logging_utils.py": "02272e983509910742bc7d7b1b8abdcc41a809d36d8204b806016c8f26c685ed", + "methods/shared_mezo/large_models/tasks.py": "11f2904364f63f462aebb64adc191dc59fb0e0ad632c474f80c1d8617af45376", + "methods/shared_mezo/large_models/native_losses.py": "b3220209623fd3051c092bbfff9ce7a952b381731a60361276680d92bc3ab4a8", + "methods/shared_mezo/large_models/data.py": "483b21a8f0841e87514229e06f6c2ba9c46ab4fbb93e13bb2c75db8e9e64cfe6", + "methods/shared_mezo/large_models/utils.py": "2b4df62167638e61f63ab7d90857d0d7114bb656f84b61f8e4f4ff68d0495570", + "methods/shared_mezo/large_models/metrics.py": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c", + "methods/shared_mezo/large_models/trainer.py": "0a41fe3ea69224229b5548fbfa87b5ce05525c7af2ae5d49f05647a5cfe1fd4e", + "methods/shared_mezo/large_models/_upstream_run.py": "32d6dc17ab9da185912c813b80487ce2db28fd213ac31b03cab6c801e9d742ec", + "methods/shared_mezo/large_models/__init__.py": "9879f7275808db88394b34d906a0e9ad85ee1dcb09ef388ba9421cb5dc4480f7", + "methods/shared_mezo/large_models/run.py": "9e72b748ba09a6c739649b43c73ac4f25fa5d2d1a61afbfec52d05019dd5d373", + "methods/shared_mezo/large_models/assets.py": "9eceaf6c421c4f933d7f32ca1ab753d22a7ea53c1a4957ad911a2d8b982b340f", + "methods/shared_mezo/large_models/subspace.py": "36613581663626b9538de4c989610f39b0534c5e51326a150df91bdfb85c0473", + "methods/fix_adjust/run_legacy.py": "3bc2bc9582be1176db38b129c4fcea34e660764f25e8c84da0a85634f079875f", + "methods/fix_adjust/run.py": "3bea8227e71eaf4dad3335f7c0d82abebbfeb0af94ef212b7f2461bb5aa64713", + "methods/node/run_legacy.py": "13feb0914e519218fe03cec3b8020b17db1ffea7db688d65d3d097d052eb21be", + "methods/node/run.py": "4951e18c781cceedaebdee56c77b7878392e7d8f7086bfe09f83a30910b937a0" + }, + "default_protocol": "legacy", + "mezo_protocol": "explicit --data_protocol mezo", + "scope": "MeZO-style code refactor: tiny algebra, paired pretrained OPT125M regression, two-protocol SST2/DROP smoke checks, Qwen native integration, merged HF inference", + "no_formal_training": true, + "no_commit_or_push": true, + "official_mezo_reuse": { + "commit": "552cb1b710767f9a6e1dc8f9645d7640376f9941", + "files": { + "templates.py": { + "upstream": "baselines/mezo/large_models/templates.py", + "upstream_sha256": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6", + "reused_sha256": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6", + "changes": [] + }, + "metrics.py": { + "upstream": "baselines/mezo/large_models/metrics.py", + "upstream_sha256": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c", + "reused_sha256": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c", + "changes": [] + }, + "tasks.py": { + "upstream": "baselines/mezo/large_models/tasks.py", + "upstream_sha256": "693c28ccc7e02997a7dced601f15a89d67a514581f98d1bc642768ef3271ed58", + "reused_sha256": "11f2904364f63f462aebb64adc191dc59fb0e0ad632c474f80c1d8617af45376", + "changes": [ + { + "old": "from templates import *", + "new": "from .templates import *" + }, + { + "old": "from utils import temp_seed", + "new": "from .utils import temp_seed" + }, + { + "old": "from datasets import load_dataset", + "new": "from .assets import load_dataset" + } + ] + }, + "utils.py": { + "upstream": "baselines/mezo/large_models/utils.py", + "upstream_sha256": "04686e63041fcc9efce7284ead16c8b5a5aa6f6e648ede447b587cad9531b0aa", + "reused_sha256": "2b4df62167638e61f63ab7d90857d0d7114bb656f84b61f8e4f4ff68d0495570", + "changes": [ + { + "old": "if tokenizer.add_bos_token:", + "new": "if getattr(tokenizer, \"add_bos_token\", False):" + } + ] + }, + "_upstream_run.py": { + "upstream": "baselines/mezo/large_models/run.py", + "upstream_sha256": "00b864c0e53c28f02572a510e6d612bfcca38682be843054bc1806354815bd81", + "reused_sha256": "32d6dc17ab9da185912c813b80487ce2db28fd213ac31b03cab6c801e9d742ec", + "changes": [ + { + "old": "import tasks", + "new": "from . import tasks" + }, + { + "old": "from tasks import get_task", + "new": "from .tasks import get_task" + }, + { + "old": "from metrics import calculate_metric", + "new": "from .metrics import calculate_metric" + }, + { + "old": "from utils import *", + "new": "from .utils import *" + }, + { + "old": "from trainer import OurTrainer", + "new": "from .trainer import OurTrainer" + }, + { + "old": "free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3)", + "new": "free_in_GB = int(torch.cuda.mem_get_info()[0]/1024**3) if torch.cuda.is_available() else 0" + }, + { + "old": "config=config,\n )", + "new": "config=config,\n torch_dtype=torch.float32, attn_implementation=\"eager\", local_files_only=True,\n )" + }, + { + "old": "tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast=False)", + "new": "tokenizer = AutoTokenizer.from_pretrained(self.args.model_name, use_fast=\"qwen\" in self.args.model_name.lower(), local_files_only=True)\n if tokenizer.pad_token_id is None:\n tokenizer.pad_token = tokenizer.eos_token" + }, + { + "old": "if self.args.save_on_interrupt:\n trainer.add_callback", + "new": "self.trainer = trainer\n if self.args.save_on_interrupt:\n trainer.add_callback" + } + ] + } + }, + "trainer_reuse": { + "upstream": "baselines/mezo/large_models/trainer.py:OurTrainer.zo_forward", + "ast_identical": true, + "base": "transformers.Trainer (modern supported API)", + "reason": "MeZO 2023 copied Trainer imports removed private APIs; retain original zo_forward and Framework, replace only inner loop with structured branches" + } + }, + "note": "Initial failed test was a docstring dedent comparison, fixed without algorithm changes; initial record preserved. Final post-smoke edits are argument guards, metadata and evaluation progress/counter reporting." +} \ No newline at end of file diff --git a/reports/ours_environment.json b/reports/ours_environment.json new file mode 100644 index 0000000..a277252 --- /dev/null +++ b/reports/ours_environment.json @@ -0,0 +1,30 @@ +{ + "python": "3.13.14 (main, Jun 23 2026, 15:18:27) [Clang 22.1.3 ]", + "executable": "/home/gloamxun/experiments_codebase/.venv/bin/python", + "paths": { + "models": "/mnt/e/Experiments/Assets/models", + "data": "/mnt/e/Experiments/Assets/data", + "results": "/mnt/e/Experiments/Assets/results" + }, + "versions": { + "torch": "2.13.0", + "transformers": "4.57.1", + "datasets": "3.6.0", + "huggingface-hub": "0.36.0" + }, + "cuda_available": true, + "gpu": "NVIDIA GeForce RTX 5070 Ti", + "capability": [ + 12, + 0 + ], + "cuda_smoke": 2.0, + "sst2": { + "train": 67349, + "validation": 872 + }, + "drop": { + "train": 77400, + "validation": 9535 + } +} diff --git a/reports/progress.json b/reports/progress.json new file mode 100644 index 0000000..ee20ad2 --- /dev/null +++ b/reports/progress.json @@ -0,0 +1,9 @@ +{ + "stage": "complete", + "completed": 45, + "total": 45, + "current_unit": "Packaging, independent environments and smoke validation complete", + "last_update": "2026-11-10T16:56:53.304163+00:00", + "output_directory": "/home/gloamxun/experiments_codebase", + "no_commit_or_push": true +} \ No newline at end of file diff --git a/reports/progress.md b/reports/progress.md new file mode 100644 index 0000000..3bb1e78 --- /dev/null +++ b/reports/progress.md @@ -0,0 +1,7 @@ +# Preparation complete + +45 independent checks passed; 5 numerical mechanism tests passed. Checkpoint reload, evaluation and generation passed. Five independent uv environments pass dependency checks and read both datasets. + +No commit or push; no full benchmark launched. + +See final_audit.json and validation_report.json for scope and exact logs. diff --git a/reports/source_audit.json b/reports/source_audit.json new file mode 100644 index 0000000..1078606 --- /dev/null +++ b/reports/source_audit.json @@ -0,0 +1,25 @@ +{ + "created": "2026-11-10T16:56:45.695731+00:00", + "official_sources": { + "mezo": { + "commit": "552cb1b710767f9a6e1dc8f9645d7640376f9941", + "tracked_upstream_changes": [] + }, + "lozo": { + "commit": "5d1ade5bf41846471d33ba526f877829b9a19856", + "tracked_upstream_changes": [] + }, + "agzo": { + "commit": "623e09a5a7dfdee697a603ec1e7aa01e3f5e6290", + "tracked_upstream_changes": [] + }, + "loren": { + "commit": "b80a32bc394332d1a1f115f41dfb5dcf7b326d37", + "tracked_upstream_changes": [] + } + }, + "root_commits": 0, + "credentials_stored": false, + "old_experiment_sources_modified": false, + "asset_manifest": "/mnt/e/Experiments/Assets/asset_manifest.json" +} \ No newline at end of file diff --git a/reports/validation_report.json b/reports/validation_report.json new file mode 100644 index 0000000..5dab207 --- /dev/null +++ b/reports/validation_report.json @@ -0,0 +1,1319 @@ +{ + "passed": true, + "checks": { + "mezo_native_help": { + "passed": true, + "returncode": 0, + "seconds": 3.0248180119961035, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/mezo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/mezo/native.py", + "--help" + ], + "log": "/home/gloamxun/experiments_codebase/reports/mezo_native_help.log", + "source_sha256": "c30fe99d07261e9280d7726bc5afa0cda366e65f8cba8ac1dbd56009689cb70e" + }, + "mezo_native_opt_sst2": { + "passed": true, + "returncode": 0, + "seconds": 24.676955856994027, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/mezo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/mezo/native.py", + "--asset-model", + "facebook/opt-1.3b", + "--asset-task", + "sst2", + "--max_steps", + "2", + "--num_train", + "16", + "--num_dev", + "4", + "--num_eval", + "4", + "--per_device_train_batch_size", + "2", + "--learning_rate", + "1e-6", + "--zo_eps", + "1e-3", + "--max_length", + "64", + "--save_strategy", + "no", + "--logging_steps", + "1", + "--evaluation_strategy", + "no" + ], + "log": "/home/gloamxun/experiments_codebase/reports/mezo_native_opt_sst2.log", + "source_sha256": "c30fe99d07261e9280d7726bc5afa0cda366e65f8cba8ac1dbd56009689cb70e" + }, + "lozo_native_help": { + "passed": true, + "returncode": 0, + "seconds": 2.9264584890042897, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/lozo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/lozo/native.py", + "--help" + ], + "log": "/home/gloamxun/experiments_codebase/reports/lozo_native_help.log", + "source_sha256": "c8d2e5148aec21cfec44330720421cd5b1e22d8daacefbfec6cf8283d970dbef" + }, + "lozo_native_opt_sst2": { + "passed": true, + "returncode": 0, + "seconds": 24.576297747000353, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/lozo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/lozo/native.py", + "--asset-model", + "facebook/opt-1.3b", + "--asset-task", + "sst2", + "--max_steps", + "2", + "--num_train", + "16", + "--num_dev", + "4", + "--num_eval", + "4", + "--per_device_train_batch_size", + "2", + "--learning_rate", + "1e-6", + "--zo_eps", + "1e-3", + "--max_length", + "64", + "--save_strategy", + "no", + "--logging_steps", + "1", + "--evaluation_strategy", + "no", + "--rank_r", + "1", + "--step_interval", + "100" + ], + "log": "/home/gloamxun/experiments_codebase/reports/lozo_native_opt_sst2.log", + "source_sha256": "c8d2e5148aec21cfec44330720421cd5b1e22d8daacefbfec6cf8283d970dbef" + }, + "agzo_native_help": { + "passed": true, + "returncode": 0, + "seconds": 3.6785890010069124, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/agzo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/agzo/native.py", + "--help" + ], + "log": "/home/gloamxun/experiments_codebase/reports/agzo_native_help.log", + "source_sha256": "4d45c83455bfdc956551dd93532a9eabfc98f77b983549e42c8aa0ce843ff98a" + }, + "agzo_native_opt_sst2": { + "passed": true, + "returncode": 0, + "seconds": 11.193064459017478, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/agzo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/agzo/native.py", + "--asset-model", + "facebook/opt-1.3b", + "--asset-task", + "sst2", + "--max_steps", + "2", + "--num_train", + "16", + "--num_dev", + "4", + "--num_eval", + "4", + "--per_device_train_batch_size", + "2", + "--learning_rate", + "1e-6", + "--zo_eps", + "1e-3", + "--max_length", + "64", + "--save_strategy", + "no", + "--logging_steps", + "1", + "--eval_strategy", + "no" + ], + "log": "/home/gloamxun/experiments_codebase/reports/agzo_native_opt_sst2.log", + "source_sha256": "4d45c83455bfdc956551dd93532a9eabfc98f77b983549e42c8aa0ce843ff98a" + }, + "loren_native_help": { + "passed": true, + "returncode": 0, + "seconds": 3.274749111995334, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/loren/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/loren/native.py", + "--help" + ], + "log": "/home/gloamxun/experiments_codebase/reports/loren_native_help.log", + "source_sha256": "fe19b6eb4449cf5f6e5a5d94f3f0849a22fc3c2cecb6912c55d88469b0ddcce4" + }, + "loren_native_opt_sst2": { + "passed": true, + "returncode": 0, + "seconds": 11.800456627999665, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/loren/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/loren/native.py", + "--asset-model", + "facebook/opt-1.3b", + "--asset-task", + "sst2", + "--epochs", + "1", + "--samplesize", + "4", + "--samplesize_validation", + "4", + "--batchsize", + "2", + "--batchsize_limit", + "2", + "--lr", + "1e-6", + "--num_queries", + "2", + "--perturbation_scale", + "1e-3", + "--damping", + "0.1", + "--lr_cov", + "1e-3", + "--weight_decay", + "0", + "--max_seq_length", + "64", + "--logging", + "csv", + "--init_seed", + "42" + ], + "log": "/home/gloamxun/experiments_codebase/reports/loren_native_opt_sst2.log", + "source_sha256": "fe19b6eb4449cf5f6e5a5d94f3f0849a22fc3c2cecb6912c55d88469b0ddcce4" + }, + "mechanism_tests": { + "passed": true, + "returncode": 0, + "seconds": 5.135638131003361, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "-m", + "pytest", + "-q", + "tests" + ], + "log": "/home/gloamxun/experiments_codebase/reports/mechanism_tests.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "fix_opt-1.3b_sst2": { + "passed": true, + "returncode": 0, + "seconds": 11.050553789973492, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "facebook/opt-1.3b", + "--task", + "sst2", + "--budget", + "5", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/fix_opt-1.3b_sst2.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "fix_opt-1.3b_drop": { + "passed": true, + "returncode": 0, + "seconds": 11.199363332998473, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "facebook/opt-1.3b", + "--task", + "drop", + "--budget", + "5", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/fix_opt-1.3b_drop.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "fix_Qwen3-0.6B_sst2": { + "passed": true, + "returncode": 0, + "seconds": 22.57671752301394, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "sst2", + "--budget", + "5", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/fix_Qwen3-0.6B_sst2.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "fix_Qwen3-0.6B_drop": { + "passed": true, + "returncode": 0, + "seconds": 9.04249995999271, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/fix_adjust/run.py", + "--method", + "fix", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "drop", + "--budget", + "5", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/fix_Qwen3-0.6B_drop.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "adjust_opt-1.3b_sst2": { + "passed": true, + "returncode": 0, + "seconds": 11.24724150900147, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "facebook/opt-1.3b", + "--task", + "sst2", + "--budget", + "17", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/adjust_opt-1.3b_sst2.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "adjust_opt-1.3b_drop": { + "passed": true, + "returncode": 0, + "seconds": 11.096854245988652, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "facebook/opt-1.3b", + "--task", + "drop", + "--budget", + "17", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/adjust_opt-1.3b_drop.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "adjust_Qwen3-0.6B_sst2": { + "passed": true, + "returncode": 0, + "seconds": 20.32401170299272, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "sst2", + "--budget", + "17", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/adjust_Qwen3-0.6B_sst2.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "adjust_Qwen3-0.6B_drop": { + "passed": true, + "returncode": 0, + "seconds": 9.445584093016805, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/fix_adjust/run.py", + "--method", + "adjust", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "drop", + "--budget", + "17", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/adjust_Qwen3-0.6B_drop.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "node_opt-1.3b_sst2": { + "passed": true, + "returncode": 0, + "seconds": 14.212221766996663, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/node/run.py", + "--method", + "node", + "--model", + "facebook/opt-1.3b", + "--task", + "sst2", + "--budget", + "13", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/node_opt-1.3b_sst2.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "node_opt-1.3b_drop": { + "passed": true, + "returncode": 0, + "seconds": 11.450210035982309, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/node/run.py", + "--method", + "node", + "--model", + "facebook/opt-1.3b", + "--task", + "drop", + "--budget", + "13", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/node_opt-1.3b_drop.log", + "source_sha256": "89738d6c30fab5634a8aa53e23c52c9ad96100e2585d7c246231974d3ef4b7d8" + }, + "node_Qwen3-0.6B_sst2": { + "passed": true, + "returncode": 0, + "seconds": 24.17712394701084, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/node/run.py", + "--method", + "node", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "sst2", + "--budget", + "13", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/node_Qwen3-0.6B_sst2.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "node_Qwen3-0.6B_drop": { + "passed": true, + "returncode": 0, + "seconds": 8.944291715015424, + "command": [ + "/home/gloamxun/experiments_codebase/.venv/bin/python", + "/home/gloamxun/experiments_codebase/methods/node/run.py", + "--method", + "node", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "drop", + "--budget", + "13", + "--refresh-every", + "1", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--calibration-samples", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/node_Qwen3-0.6B_drop.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "mezo_modern_sync": { + "passed": true, + "returncode": 0, + "seconds": 14.249761213985039, + "command": [ + "/home/gloamxun/.local/bin/uv", + "sync", + "--locked", + "--project", + "/home/gloamxun/experiments_codebase/baselines/mezo", + "--no-default-groups", + "--group", + "modern" + ], + "log": "/home/gloamxun/experiments_codebase/reports/mezo_modern_sync.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "mezo_compatible_opt-1.3b_sst2": { + "passed": true, + "returncode": 0, + "seconds": 14.45389104197966, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/mezo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/mezo/run_compatible.py", + "--model", + "facebook/opt-1.3b", + "--task", + "sst2", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/mezo_compatible_opt-1.3b_sst2.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "mezo_compatible_opt-1.3b_drop": { + "passed": true, + "returncode": 0, + "seconds": 11.29535807200591, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/mezo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/mezo/run_compatible.py", + "--model", + "facebook/opt-1.3b", + "--task", + "drop", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/mezo_compatible_opt-1.3b_drop.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "mezo_compatible_Qwen3-0.6B_sst2": { + "passed": true, + "returncode": 0, + "seconds": 23.126173030002974, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/mezo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/mezo/run_compatible.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "sst2", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/mezo_compatible_Qwen3-0.6B_sst2.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "mezo_compatible_Qwen3-0.6B_drop": { + "passed": true, + "returncode": 0, + "seconds": 8.29504331201315, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/mezo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/mezo/run_compatible.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "drop", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/mezo_compatible_Qwen3-0.6B_drop.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "mezo_restore_native": { + "passed": true, + "returncode": 0, + "seconds": 0.21470897301333025, + "command": [ + "/home/gloamxun/.local/bin/uv", + "sync", + "--locked", + "--project", + "/home/gloamxun/experiments_codebase/baselines/mezo" + ], + "log": "/home/gloamxun/experiments_codebase/reports/mezo_restore_native.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "lozo_modern_sync": { + "passed": true, + "returncode": 0, + "seconds": 0.2143980250111781, + "command": [ + "/home/gloamxun/.local/bin/uv", + "sync", + "--locked", + "--project", + "/home/gloamxun/experiments_codebase/baselines/lozo", + "--no-default-groups", + "--group", + "modern" + ], + "log": "/home/gloamxun/experiments_codebase/reports/lozo_modern_sync.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "lozo_compatible_opt-1.3b_sst2": { + "passed": true, + "returncode": 0, + "seconds": 14.609566135972273, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/lozo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/lozo/run_compatible.py", + "--model", + "facebook/opt-1.3b", + "--task", + "sst2", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/lozo_compatible_opt-1.3b_sst2.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "lozo_compatible_opt-1.3b_drop": { + "passed": true, + "returncode": 0, + "seconds": 10.795322000980377, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/lozo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/lozo/run_compatible.py", + "--model", + "facebook/opt-1.3b", + "--task", + "drop", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/lozo_compatible_opt-1.3b_drop.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "lozo_compatible_Qwen3-0.6B_sst2": { + "passed": true, + "returncode": 0, + "seconds": 19.86798537199502, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/lozo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/lozo/run_compatible.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "sst2", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/lozo_compatible_Qwen3-0.6B_sst2.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "lozo_compatible_Qwen3-0.6B_drop": { + "passed": true, + "returncode": 0, + "seconds": 9.192512602021452, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/lozo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/lozo/run_compatible.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "drop", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/lozo_compatible_Qwen3-0.6B_drop.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "lozo_restore_native": { + "passed": true, + "returncode": 0, + "seconds": 0.11431754799559712, + "command": [ + "/home/gloamxun/.local/bin/uv", + "sync", + "--locked", + "--project", + "/home/gloamxun/experiments_codebase/baselines/lozo" + ], + "log": "/home/gloamxun/experiments_codebase/reports/lozo_restore_native.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "agzo_modern_sync": { + "passed": true, + "returncode": 0, + "seconds": 0.21460815699538216, + "command": [ + "/home/gloamxun/.local/bin/uv", + "sync", + "--locked", + "--project", + "/home/gloamxun/experiments_codebase/baselines/agzo", + "--no-default-groups", + "--group", + "modern" + ], + "log": "/home/gloamxun/experiments_codebase/reports/agzo_modern_sync.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "agzo_compatible_opt-1.3b_sst2": { + "passed": true, + "returncode": 0, + "seconds": 16.1555079940008, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/agzo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/agzo/run_compatible.py", + "--model", + "facebook/opt-1.3b", + "--task", + "sst2", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/agzo_compatible_opt-1.3b_sst2.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "agzo_compatible_opt-1.3b_drop": { + "passed": true, + "returncode": 0, + "seconds": 11.251995261991397, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/agzo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/agzo/run_compatible.py", + "--model", + "facebook/opt-1.3b", + "--task", + "drop", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/agzo_compatible_opt-1.3b_drop.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "agzo_compatible_Qwen3-0.6B_sst2": { + "passed": true, + "returncode": 0, + "seconds": 23.47625998398871, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/agzo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/agzo/run_compatible.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "sst2", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/agzo_compatible_Qwen3-0.6B_sst2.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "agzo_compatible_Qwen3-0.6B_drop": { + "passed": true, + "returncode": 0, + "seconds": 11.394127793988446, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/agzo/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/agzo/run_compatible.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "drop", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/agzo_compatible_Qwen3-0.6B_drop.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "agzo_restore_native": { + "passed": true, + "returncode": 0, + "seconds": 0.26490445199306123, + "command": [ + "/home/gloamxun/.local/bin/uv", + "sync", + "--locked", + "--project", + "/home/gloamxun/experiments_codebase/baselines/agzo" + ], + "log": "/home/gloamxun/experiments_codebase/reports/agzo_restore_native.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "loren_modern_sync": { + "passed": true, + "returncode": 0, + "seconds": 0.16437157199834473, + "command": [ + "/home/gloamxun/.local/bin/uv", + "sync", + "--locked", + "--project", + "/home/gloamxun/experiments_codebase/baselines/loren", + "--no-default-groups", + "--group", + "modern" + ], + "log": "/home/gloamxun/experiments_codebase/reports/loren_modern_sync.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "loren_compatible_opt-1.3b_sst2": { + "passed": true, + "returncode": 0, + "seconds": 18.259858131990768, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/loren/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/loren/run_compatible.py", + "--model", + "facebook/opt-1.3b", + "--task", + "sst2", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/loren_compatible_opt-1.3b_sst2.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "loren_compatible_opt-1.3b_drop": { + "passed": true, + "returncode": 0, + "seconds": 14.502735324989771, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/loren/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/loren/run_compatible.py", + "--model", + "facebook/opt-1.3b", + "--task", + "drop", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/loren_compatible_opt-1.3b_drop.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "loren_compatible_Qwen3-0.6B_sst2": { + "passed": true, + "returncode": 0, + "seconds": 23.526868151995586, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/loren/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/loren/run_compatible.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "sst2", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/loren_compatible_Qwen3-0.6B_sst2.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "loren_compatible_Qwen3-0.6B_drop": { + "passed": true, + "returncode": 0, + "seconds": 11.393709043011768, + "command": [ + "/home/gloamxun/experiments_codebase/baselines/loren/.venv/bin/python", + "/home/gloamxun/experiments_codebase/baselines/loren/run_compatible.py", + "--model", + "Qwen/Qwen3-0.6B", + "--task", + "drop", + "--budget", + "6", + "--train-samples", + "8", + "--dev-samples", + "2", + "--eval-samples", + "2", + "--batch-size", + "2", + "--eval-batch-size", + "2", + "--max-length", + "64", + "--eval-every", + "100", + "--no-save-checkpoint" + ], + "log": "/home/gloamxun/experiments_codebase/reports/loren_compatible_Qwen3-0.6B_drop.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + }, + "loren_restore_native": { + "passed": true, + "returncode": 0, + "seconds": 0.21446642000228167, + "command": [ + "/home/gloamxun/.local/bin/uv", + "sync", + "--locked", + "--project", + "/home/gloamxun/experiments_codebase/baselines/loren" + ], + "log": "/home/gloamxun/experiments_codebase/reports/loren_restore_native.log", + "source_sha256": "6cdb0b92ccf09399b64fdfa6a6f4fe484c211a81f70f123e6837e74206a221ad" + } + }, + "scope": "Import/help and small real-model runs; not paper-performance validation", + "updated": "2026-11-10T16:52:47.521168+00:00" +} \ No newline at end of file diff --git a/scripts/assets.lock.json b/scripts/assets.lock.json new file mode 100644 index 0000000..8d44f1a --- /dev/null +++ b/scripts/assets.lock.json @@ -0,0 +1,105 @@ +{ + "models": { + "facebook/opt-1.3b": { + "path": "/mnt/e/Experiments/Assets/models/opt-1.3b", + "revision": "3f5c25d0bc631cb57ac65913f76e22c2dfb61d62", + "files": { + "config.json": { + "bytes": 653, + "sha256": "f1aaceefb7d34d346e9b0400d95fdb4970567bcbe1d4aba1068c5402099b644f" + }, + "generation_config.json": { + "bytes": 137, + "sha256": "d37de99f9835d7a4d0916257f724504d12c4a668f36a50b2d42e09ba4ebd05d5" + }, + "merges.txt": { + "bytes": 456318, + "sha256": "1ce1664773c50f3e0cc8842619a93edc4624525b728b188a9e0be33b7726adc5" + }, + "pytorch_model.bin": { + "bytes": 2631639353, + "sha256": "cf7d5c970d6ddbd3b03009b397c0422e147edd5c8020d47a8d2fac0b11a3b08d" + }, + "special_tokens_map.json": { + "bytes": 441, + "sha256": "0f3cd5f307a2735cfee31ddf33be88655e8be165ee2cdc26ced966f04258adf0" + }, + "tokenizer_config.json": { + "bytes": 685, + "sha256": "d1e4185b43a0a06421ab7218d5c1a775350bd13024507b34fbed25dcf6c14c6b" + }, + "vocab.json": { + "bytes": 898822, + "sha256": "06b4d46c8e752d410213d9548eb27a54db70fda0319b6271fb8d59dead5e1cab" + } + } + }, + "Qwen/Qwen3-0.6B": { + "path": "/mnt/e/Experiments/Assets/models/qwen3-0.6b", + "revision": "c1899de289a04d12100db370d81485cdf75e47ca", + "files": { + "LICENSE": { + "bytes": 11343, + "sha256": "832dd9e00a68dd83b3c3fb9f5588dad7dcf337a0db50f7d9483f310cd292e92e" + }, + "README.md": { + "bytes": 13965, + "sha256": "1ab64a26fcb3b461423b89a433a8c858f1bf8d4086f979cbb3ff878d47cf20e9" + }, + "config.json": { + "bytes": 726, + "sha256": "660db3b73d788119c04535e48cf9be5f55bc3100841a718637ae695b442f27dd" + }, + "generation_config.json": { + "bytes": 239, + "sha256": "2325da0f15bb848e018c5ae071b7943332e9f871d6b60e2ed22ca97d4cb993d2" + }, + "merges.txt": { + "bytes": 1671853, + "sha256": "8831e4f1a044471340f7c0a83d7bd71306a5b867e95fd870f74d0c5308a904d5" + }, + "model.safetensors": { + "bytes": 1503300328, + "sha256": "f47f71177f32bcd101b7573ec9171e6a57f4f4d31148d38e382306f42996874b" + }, + "tokenizer.json": { + "bytes": 11422654, + "sha256": "aeb13307a71acd8fe81861d94ad54ab689df773318809eed3cbe794b4492dae4" + }, + "tokenizer_config.json": { + "bytes": 9732, + "sha256": "d5d09f07b48c3086c508b30d1c9114bd1189145b74e982a265350c923acd8101" + }, + "vocab.json": { + "bytes": 2776833, + "sha256": "ca10d7e9fb3ed18575dd1e277a2579c16d108e32f27439684afa0e10b1440910" + } + } + } + }, + "datasets": { + "sst2": { + "path": "/mnt/e/Experiments/Assets/data/sst2", + "rows": { + "train": 67349, + "validation": 872 + }, + "fingerprints": { + "train": "31164fe5d5d3c937", + "validation": "85a5492b887544af" + } + }, + "drop": { + "path": "/mnt/e/Experiments/Assets/data/drop", + "rows": { + "train": 77400, + "validation": 9535 + }, + "fingerprints": { + "train": "758c6e093d1e3b41", + "validation": "77842021869200ba" + } + } + }, + "note": "File hashes pin staged models; datasets fingerprints are serialization-specific, run data hashes are authoritative." +} \ No newline at end of file diff --git a/scripts/doctor.py b/scripts/doctor.py new file mode 100644 index 0000000..e5114d0 --- /dev/null +++ b/scripts/doctor.py @@ -0,0 +1,17 @@ +"""Inspect the active uv environment and shared assets without loading model weights.""" +import importlib.metadata as meta +import json +import os +from pathlib import Path +import sys +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'src')) +from experiments_codebase.paths import paths +import torch +from datasets import load_from_disk +result={'python':sys.version,'executable':sys.executable,'paths':{k:str(v) for k,v in paths().items()},'versions':{p:meta.version(p) for p in ('torch','transformers','datasets','huggingface-hub')},'cuda_available':torch.cuda.is_available()} +if torch.cuda.is_available(): + x=torch.ones(1,device='cuda');result.update(gpu=torch.cuda.get_device_name(),capability=torch.cuda.get_device_capability(),cuda_smoke=float((x+x).cpu())) +for task in ('sst2','drop'): + ds=load_from_disk(str(paths()['data']/task));result[task]={s:len(d) for s,d in ds.items()} +print(json.dumps(result,indent=2)) diff --git a/scripts/env.sh b/scripts/env.sh new file mode 100755 index 0000000..0aaccb9 --- /dev/null +++ b/scripts/env.sh @@ -0,0 +1,20 @@ +# Source from any directory; no activation of another project's environment. +_experiments_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +if [ -f "$_experiments_root/.env" ]; then + set -a; source "$_experiments_root/.env"; set +a +fi +export EXPERIMENT_ASSETS="${EXPERIMENT_ASSETS:-/mnt/e/Experiments/Assets}" +export EXPERIMENT_MODELS="${EXPERIMENT_MODELS:-$EXPERIMENT_ASSETS/models}" +export EXPERIMENT_DATA="${EXPERIMENT_DATA:-$EXPERIMENT_ASSETS/data}" +export EXPERIMENT_RESULTS="${EXPERIMENT_RESULTS:-$EXPERIMENT_ASSETS/results}" +# Override legacy HF_HOME inherited from older experiments within this shell. +export HF_HOME="$EXPERIMENT_MODELS/.huggingface" +export HF_HUB_CACHE="$HF_HOME/hub" +export HF_DATASETS_CACHE="$EXPERIMENT_DATA/.huggingface/datasets" +export HF_XET_CACHE="$HF_HOME/xet" +export XDG_CACHE_HOME="${XDG_CACHE_HOME:-$HOME/.cache}" +export WANDB_DIR="$EXPERIMENT_RESULTS/wandb" +export WANDB_MODE="${WANDB_MODE:-disabled}" +export TOKENIZERS_PARALLELISM=false +export PYTHONPATH="$_experiments_root/src${PYTHONPATH:+:$PYTHONPATH}" +unset _experiments_root diff --git a/scripts/final_audit.py b/scripts/final_audit.py new file mode 100644 index 0000000..64a476e --- /dev/null +++ b/scripts/final_audit.py @@ -0,0 +1,40 @@ +"""Final checks of environments, assets, provenance and the uncommitted tree.""" +import json +from pathlib import Path +import subprocess +from datetime import datetime,timezone +ROOT=Path(__file__).resolve().parents[1];UV=str(Path.home()/'.local/bin/uv') +reports=ROOT/'reports' +results={} +with (reports/'dependency_check.log').open('w') as log: + for name,folder in [('ours',ROOT),*[(m,ROOT/'baselines'/m) for m in ('mezo','agzo','lozo','loren')]]: + log.write(f'\n=== {name} ===\n');log.flush() + process=subprocess.run([UV,'pip','check','--python',str(folder/'.venv/bin/python')],stdout=log,stderr=subprocess.STDOUT) + assert process.returncode==0,name + path=reports/f'{name}_environment.json' + data=subprocess.check_output([str(folder/'.venv/bin/python'),str(ROOT/'scripts/doctor.py')],text=True) + path.write_text(data);results[name]=json.loads(data) + assert results[name]['sst2']['train']==67349 and results[name]['drop']['train']==77400 +for m in ('mezo','agzo','lozo','loren'): + for required in ('pyproject.toml','uv.lock','.python-version','TROUBLESHOOTING.md','native.py','run_compatible.py'): + assert (ROOT/'baselines'/m/required).is_file() +validation=json.loads((reports/'validation_report.json').read_text()) +assert validation['passed'] and len(validation['checks'])==45 +checkpoint=json.loads((reports/'checkpoint_restore.json').read_text()) +assert checkpoint['passed'] +source=json.loads((reports/'source_audit.json').read_text()) +assert all(not v['tracked_upstream_changes'] for v in source['official_sources'].values()) +assert subprocess.check_output(['git','-C',str(ROOT),'rev-list','--all','--count'],text=True).strip()=='0' +assert not subprocess.check_output(['git','-C',str(ROOT),'diff','--cached','--name-only'],text=True).strip() +ignored=['.env','.venv/bin/python','baselines/mezo/.venv/bin/python','baselines/mezo/.upstream-git/config','models/test.bin','data/test.parquet','results/test.json'] +check=subprocess.run(['git','-C',str(ROOT),'check-ignore','--stdin'],input='\n'.join(ignored)+'\n',capture_output=True,text=True,check=True) +assert check.stdout.splitlines()==ignored +result=dict(passed=True,checked_at=datetime.now(timezone.utc).isoformat(),validation_checks=45,mechanism_tests=5,checkpoint_roundtrip=checkpoint, + environments=results,git=dict(commits=0,staged_files=0,official_source_changes=0), + scope='Small real-model independent execution, dependency and inference checks; no full benchmark or paper accuracy reproduction', + final_environment_change='HF defaults initialized before library imports; final modern model/task matrix, doctor in all five environments, mechanism tests and checkpoint roundtrip validate this routing change.') +(reports/'final_audit.json').write_text(json.dumps(result,indent=2)) +progress=dict(stage='complete',completed=45,total=45,current_unit='Packaging, independent environments and smoke validation complete',last_update=result['checked_at'],output_directory=str(ROOT),no_commit_or_push=True) +tmp=reports/'progress.json.tmp';tmp.write_text(json.dumps(progress,indent=2));tmp.replace(reports/'progress.json') +tmp=reports/'progress.md.tmp';tmp.write_text('# Preparation complete\n\n45 independent checks passed; 5 numerical mechanism tests passed. Checkpoint reload, evaluation and generation passed. Five independent uv environments pass dependency checks and read both datasets.\n\nNo commit or push; no full benchmark launched.\n\nSee final_audit.json and validation_report.json for scope and exact logs.\n');tmp.replace(reports/'progress.md') +print(json.dumps({'passed':True,'validation_checks':45,'environments':list(results),'root':str(ROOT)})) diff --git a/scripts/plot_compare.py b/scripts/plot_compare.py new file mode 100644 index 0000000..0d0e8ea --- /dev/null +++ b/scripts/plot_compare.py @@ -0,0 +1,28 @@ +"""Compare selected compatible run curves without seed-range shading.""" +import argparse +import json +from pathlib import Path +import sys +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'src')) +from experiments_codebase.paths import paths +import matplotlib +matplotlib.use('Agg') +import matplotlib.pyplot as plt + +def main(): + p=argparse.ArgumentParser(description=__doc__);p.add_argument('--config',type=Path,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args() + if not a.out.resolve().is_relative_to(paths()['results'].resolve()):raise ValueError('Plots belong under shared results') + a.out.mkdir(parents=True,exist_ok=True);cfg=json.loads(a.config.read_text()) + for metric in ('loss','accuracy'): + fig,ax=plt.subplots(figsize=(9,4));any_curve=False + for item in cfg['runs']: + if not item.get('enabled',True):continue + folder=Path(item['directory']);curve=json.loads((folder/'curve.json').read_text());split=cfg.get('split','development') + points=[v for v in curve if metric in v[split]] + if points:ax.plot([v['main_forwards'] for v in points],[v[split][metric] for v in points],label=item['label']);any_curve=True + if any_curve: + ax.set(xlabel='Cumulative main forwards',ylabel=metric,title=cfg.get('title',''));ax.legend();ax.grid(alpha=.2);fig.tight_layout();fig.savefig(a.out/f'{metric}_curve.png',dpi=180) + plt.close(fig) + (a.out/'plot_config.json').write_text(json.dumps(cfg,indent=2)) +if __name__=='__main__':main() diff --git a/scripts/plot_config.example.json b/scripts/plot_config.example.json new file mode 100644 index 0000000..629f65c --- /dev/null +++ b/scripts/plot_config.example.json @@ -0,0 +1,21 @@ +{ + "title": "OPT-1.3B / SST-2", + "split": "development", + "runs": [ + { + "label": "MeZO", + "directory": "/mnt/e/Experiments/Assets/results/REPLACE_MEZO_RUN", + "enabled": true + }, + { + "label": "Adjust", + "directory": "/mnt/e/Experiments/Assets/results/REPLACE_ADJUST_RUN", + "enabled": true + }, + { + "label": "Node", + "directory": "/mnt/e/Experiments/Assets/results/REPLACE_NODE_RUN", + "enabled": true + } + ] +} \ No newline at end of file diff --git a/scripts/prepare_assets.py b/scripts/prepare_assets.py new file mode 100644 index 0000000..8cb4b37 --- /dev/null +++ b/scripts/prepare_assets.py @@ -0,0 +1,85 @@ +"""Copy verified existing assets, or explicitly download absent public assets. No moves.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import shutil +import subprocess +import time + +def main(): + p=argparse.ArgumentParser();p.add_argument('--download-missing',action='store_true');p.add_argument('--datasets-only',action='store_true');a=p.parse_args() + subprocess.run(['mountpoint','-q','/mnt/e'],check=True) + root=Path(os.environ.get('EXPERIMENT_ASSETS','/mnt/e/Experiments/Assets')) + old=Path('/mnt/e/Experiments/optimizer_research') + root.mkdir(parents=True,exist_ok=True) + for d in ('models','data','results'):(root/d).mkdir(exist_ok=True) + os.environ['HF_HOME']=str(root/'models/.huggingface') + os.environ['HF_HUB_CACHE']=str(root/'models/.huggingface/hub') + os.environ['HF_DATASETS_CACHE']=str(root/'data/.huggingface/datasets') + os.environ['HF_XET_CACHE']=str(root/'models/.huggingface/xet') + manifest=json.loads((root/'asset_manifest.json').read_text()) if (root/'asset_manifest.json').exists() else {'root':str(root),'models':{},'datasets':{}} + lockpath=Path(__file__).with_name('assets.lock.json') + lock=json.loads(lockpath.read_text()) if lockpath.exists() else {} + for ident,alias in ([] if a.datasets_only else [('facebook/opt-1.3b','opt-1.3b'),('Qwen/Qwen3-0.6B','qwen3-0.6b')]): + dest=root/'models'/alias;dest.mkdir(exist_ok=True) + cache=old/'huggingface/hub'/('models--'+ident.replace('/','--'))/'snapshots' + candidates=sorted(cache.glob('*')) if cache.exists() else [] + expected=lock.get('models',{}).get(ident,{}) + snapshots=[v for v in candidates if (v/'config.json').exists() and (not expected or v.name==expected['revision'])] + if snapshots: + source=snapshots[-1];revision=source.name + for f in source.rglob('*'): + if not f.is_file():continue + target=dest/f.relative_to(source);target.parent.mkdir(parents=True,exist_ok=True) + if not target.exists():shutil.copy2(f,target,follow_symlinks=True) + if target.stat().st_size!=f.stat().st_size:raise RuntimeError(f'Partial asset {target}') + elif a.download_missing: + from huggingface_hub import snapshot_download + snapshot_download(ident,revision=expected.get('revision','main'),local_dir=dest);revision=expected.get('revision','downloaded: see local HF metadata') + else:raise RuntimeError(f'No cached model {ident}; retry with --download-missing') + files={} + for f in sorted(dest.rglob('*')): + if not f.is_file() or '.cache' in f.parts:continue + h=hashlib.sha256() + with f.open('rb') as stream: + for block in iter(lambda:stream.read(8*1024*1024),b''):h.update(block) + files[str(f.relative_to(dest))]={'bytes':f.stat().st_size,'sha256':h.hexdigest()} + pinned=expected.get('files',{}).get(str(f.relative_to(dest))) + if pinned and files[str(f.relative_to(dest))]!=pinned:raise RuntimeError(f'Model hash mismatch: {f}') + manifest['models'][ident]={'path':str(dest),'revision':revision,'files':files} + print(f'Model ready: {ident} ({len(files)} files)',flush=True) + # Preserve raw full datasets separately from frozen historical benchmark samples. + from datasets import load_dataset, DatasetDict + for ident,config,alias in [('glue','sst2','sst2'),('ucinlp/drop',None,'drop')]: + dest=root/'data'/alias + from datasets import load_from_disk + try: + ds=load_from_disk(str(dest)) if (dest/'dataset_dict.json').exists() else None + except ValueError: + # Rebuild from immutable raw parquet when a newer datasets serialized List + # features that legacy author environments cannot read. + ds=None + if ds is None: + if alias=='sst2' and (old/'datasets/sst2/train.parquet').exists(): + ds=load_dataset('parquet',data_files={s:str(old/f'datasets/sst2/{s}.parquet') for s in ('train','validation')}) + else: + hub=old/'huggingface/hub'/('datasets--'+ident.replace('/','--'))/'snapshots' + parquet={s:sorted(str(f) for v in hub.glob('*') for f in v.rglob(f'*{s}*.parquet')) for s in ('train','validation')} + if all(parquet.values()):ds=load_dataset('parquet',data_files=parquet) + elif a.download_missing:ds=load_dataset(ident,config) if config else load_dataset(ident) + else:raise RuntimeError(f'No cached raw {alias}; retry with --download-missing') + ds.save_to_disk(str(dest)) + from datasets import load_from_disk + ds=load_from_disk(str(dest)) + manifest['datasets'][alias]={'path':str(dest),'rows':{s:len(d) for s,d in ds.items()}, + 'fingerprints':{s:d._fingerprint for s,d in ds.items()}} + print(f'Dataset ready: {alias} {manifest["datasets"][alias]["rows"]}',flush=True) + frozen=old/'results/final_results/data' + if frozen.exists(): + shutil.copytree(frozen,root/'data/historical_opt13_sst2',dirs_exist_ok=True) + target=root/'asset_manifest.json';tmp=target.with_suffix('.tmp');tmp.write_text(json.dumps(manifest,indent=2));tmp.replace(target) + print(f'Manifest: {target}') + +if __name__=='__main__':main() diff --git a/scripts/sync_all.sh b/scripts/sync_all.sh new file mode 100755 index 0000000..6fde0d0 --- /dev/null +++ b/scripts/sync_all.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +set -euo pipefail +cd "$(dirname "$0")/.." +uv sync --locked +for method in mezo agzo lozo loren; do + uv sync --locked --project "baselines/$method" +done diff --git a/scripts/validate.py b/scripts/validate.py new file mode 100644 index 0000000..e829189 --- /dev/null +++ b/scripts/validate.py @@ -0,0 +1,73 @@ +"""Independent environment and real-model smoke checks, no long training.""" +import argparse +import hashlib +from datetime import datetime,timezone +import json +import os +from pathlib import Path +import subprocess +import time + +ROOT=Path(__file__).resolve().parents[1] +UV='/home/gloamxun/.local/bin/uv' +ENV=dict(os.environ,UV_SYSTEM_CERTS='true',PYTHONPATH=str(ROOT/'src'),WANDB_MODE='disabled',TOKENIZERS_PARALLELISM='false') +REPORT=ROOT/'reports/validation_report.json' +def save(path,value): + tmp=path.with_suffix('.tmp');tmp.write_text(json.dumps(value,indent=2));tmp.replace(path) +def main(): + p=argparse.ArgumentParser();p.add_argument('--stage',choices=['native','ours','modern','all'],default='all');p.add_argument('--retry',action='store_true');a=p.parse_args() + results=json.loads(REPORT.read_text())['checks'] if REPORT.exists() else {} + start=time.monotonic() + def run(name,cmd): + files=list((ROOT/'src').rglob('*.py'))+list((ROOT/'methods').rglob('*.py'))+list((ROOT/'tests').rglob('*.py')) + if '_native_' in name: + method=name.split('_')[0];files=[ROOT/'baselines'/method/'native.py',ROOT/'baselines'/method/'uv.lock',ROOT/'src/experiments_codebase/paths.py'] + h=hashlib.sha256() + for f in sorted(files):h.update(str(f.relative_to(ROOT)).encode());h.update(f.read_bytes()) + fingerprint=h.hexdigest() + if name in results and results[name]['passed'] and results[name].get('source_sha256')==fingerprint and not a.retry:return + print('START',name,flush=True) + log=ROOT/'reports'/f'{name}.log';begin=time.monotonic() + progress=dict(stage='validating',current_unit=name,completed=sum(v['passed'] for v in results.values()),total=None,pid=os.getpid(),output_directory=str(ROOT),last_update=datetime.now(timezone.utc).isoformat(),elapsed_seconds=time.monotonic()-start,log=str(log)) + save(ROOT/'reports/progress.json',progress) + tmp=ROOT/'reports/progress.md.tmp';tmp.write_text(f'# Codebase validation\n\nCurrent: {name}\n\nPassed checks: {progress["completed"]}\n\nPID: {os.getpid()}\n\nLog: {log}\n\nUpdated UTC: {progress["last_update"]}\n');tmp.replace(ROOT/'reports/progress.md') + with log.open('w') as stream: + try:rc=subprocess.run(cmd,env=ENV,cwd=ROOT,stdout=stream,stderr=subprocess.STDOUT,timeout=600).returncode + except subprocess.TimeoutExpired:rc=124 + results[name]=dict(passed=rc==0,returncode=rc,seconds=time.monotonic()-begin,command=cmd,log=str(log),source_sha256=fingerprint) + save(REPORT,dict(passed=all(v['passed'] for v in results.values()),checks=results,scope='Import/help and small real-model runs; not paper-performance validation',updated=datetime.now(timezone.utc).isoformat())) + print('END',name,rc,flush=True) + if rc:print('\n'.join(log.read_text().splitlines()[-15:]),flush=True) + if a.stage in ('native','all'): + for method in ('mezo','lozo','agzo','loren'): + project=ROOT/'baselines'/method + run(method+'_native_help',[str(project/'.venv/bin/python'),str(project/'native.py'),'--help']) + if method=='loren': + flags='--epochs 1 --samplesize 4 --samplesize_validation 4 --batchsize 2 --batchsize_limit 2 --lr 1e-6 --num_queries 2 --perturbation_scale 1e-3 --damping 0.1 --lr_cov 1e-3 --weight_decay 0 --max_seq_length 64 --logging csv --init_seed 42'.split() + else: + flags='--max_steps 2 --num_train 16 --num_dev 4 --num_eval 4 --per_device_train_batch_size 2 --learning_rate 1e-6 --zo_eps 1e-3 --max_length 64 --save_strategy no --logging_steps 1'.split() + flags+=['--eval_strategy' if method=='agzo' else '--evaluation_strategy','no'] + if method=='lozo':flags+=['--rank_r','1','--step_interval','100'] + run(method+'_native_opt_sst2',[str(project/'.venv/bin/python'),str(project/'native.py'),'--asset-model','facebook/opt-1.3b','--asset-task','sst2',*flags]) + if a.stage in ('ours','all'): + run('mechanism_tests',[str(ROOT/'.venv/bin/python'),'-m','pytest','-q','tests']) + for method in ('fix','adjust','node'): + for model in ('facebook/opt-1.3b','Qwen/Qwen3-0.6B'): + for task in ('sst2','drop'): + entry=ROOT/'methods/large_models/run.py' + flags=['--method',method,'--model',model,'--task',task,'--budget',str({'fix':5,'adjust':17,'node':17}[method]),'--refresh-every','1','--train-samples','8','--dev-samples','2','--eval-samples','2','--batch-size','2','--eval-batch-size','2','--calibration-samples','2','--max-length','64','--eval-every','100','--no-save-checkpoint'] + run(f'{method}_{model.split("/")[-1]}_{task}',[str(ROOT/'.venv/bin/python'),str(entry),*flags]) + if a.stage in ('modern','all'): + for method in ('mezo','lozo','agzo','loren'): + project=ROOT/'baselines'/method + run(method+'_modern_sync',[UV,'sync','--locked','--project',str(project),'--no-default-groups','--group','modern']) + for model in ('facebook/opt-1.3b','Qwen/Qwen3-0.6B'): + for task in ('sst2','drop'): + flags=['--model',model,'--task',task,'--budget','6','--train-samples','8','--dev-samples','2','--eval-samples','2','--batch-size','2','--eval-batch-size','2','--max-length','64','--eval-every','100','--no-save-checkpoint'] + run(f'{method}_compatible_{model.split("/")[-1]}_{task}',[str(project/'.venv/bin/python'),str(project/'run_compatible.py'),*flags]) + run(method+'_restore_native',[UV,'sync','--locked','--project',str(project)]) + report=json.loads(REPORT.read_text()) + progress=dict(stage='complete' if report['passed'] else 'needs_fixes',completed=sum(v['passed'] for v in results.values()),total=len(results),pid=os.getpid(),last_update=datetime.now(timezone.utc).isoformat(),output_directory=str(ROOT),elapsed_seconds=time.monotonic()-start) + save(ROOT/'reports/progress.json',progress) + (ROOT/'reports/progress.md').write_text('# Codebase validation\n\n'+json.dumps(progress,indent=2)+'\n\nSee validation_report.json for exact scope and per-check logs. No commits/pushes.\n') +if __name__=='__main__':main() diff --git a/scripts/validate_checkpoint.py b/scripts/validate_checkpoint.py new file mode 100644 index 0000000..14b42e2 --- /dev/null +++ b/scripts/validate_checkpoint.py @@ -0,0 +1,28 @@ +"""Small real-model save/reload/inference check; outputs remain in shared Assets.""" +import json +from pathlib import Path +import subprocess +import sys +from datetime import datetime,timezone +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'src')) +from experiments_codebase.paths import paths,save + +def main(): + stamp=datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ') + output=paths()['results']/f'checkpoint_check_{stamp}' + import argparse + cached=list(Path('/mnt/e/Experiments/optimizer_research/huggingface/hub/models--facebook--opt-125m/snapshots').glob('*/config.json')) + parser=argparse.ArgumentParser();parser.add_argument('--model',default=str(cached[0].parent) if cached else 'Qwen/Qwen3-0.6B') + model=parser.parse_args().model + args=['--model',model,'--task','sst2','--budget','5','--train-samples','8','--dev-samples','2','--eval-samples','2','--batch-size','2','--eval-batch-size','2','--calibration-samples','2','--max-length','64'] + entry=ROOT/'methods/large_models/run.py';train=output/'training';evaluation=output/'evaluation';generation=output/'generation' + output.mkdir() + commands=[['--out',str(train),*args],['--action','evaluate','--checkpoint',str(train/'model'),'--out',str(evaluation),*args],['--action','generate','--checkpoint',str(train/'model'),'--out',str(generation),'--prompt','A wonderful movie It was','--max-new-tokens','4',*args]] + for index,flags in enumerate(commands): + with (output/f'{index}.log').open('w') as stream:subprocess.run([sys.executable,str(entry),*flags],cwd=ROOT,stdout=stream,stderr=subprocess.STDOUT,check=True,timeout=300) + before=json.loads((train/'summary.json').read_text())['validation'];after=json.loads((evaluation/'evaluation.json').read_text()) + assert before['accuracy']==after['accuracy'] and abs(before['loss']-after['loss'])<5e-5 + save(ROOT/'reports/mezo_refactor/checkpoint_restore.json',dict(passed=True,model=model,task='sst2',before=before,after=after,output=str(output),generation=json.loads((generation/'generation.json').read_text()),scope='Small real-model training checkpoint, merged HF weight restoration (FP32 rounding tolerance), evaluation and generation; not performance evidence')) + print(json.dumps({'passed':True,'output':str(output)})) +if __name__=='__main__':main() diff --git a/scripts/validate_history_free_coverage.py b/scripts/validate_history_free_coverage.py new file mode 100644 index 0000000..38a2bbe --- /dev/null +++ b/scripts/validate_history_free_coverage.py @@ -0,0 +1,56 @@ +"""CPU FP64 quadrature audit of actual forward queries; never launches training.""" +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path +import sys + +ROOT = Path(__file__).resolve().parents[1] +sys.path[:0] = [str(ROOT), str(ROOT/'src'), str(ROOT/'tests')] +from test_history_free_coverage import quadrature + + +def main(): + if not os.path.ismount('/mnt/e'): + raise RuntimeError('Shared E mount is unavailable') + out = Path('/mnt/e/Experiments/Assets/results')/( + 'history_free_coverage_audit_'+datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')) + out.mkdir(parents=True, exist_ok=False) + results = dict(protocol='analytic small-model validation; no LLM training', + dtype='float64', quadrature_order=4, gaussian_dimensions=2, + sign_patterns=16, draws_per_case=256, forwards_per_draw=3, + training_queries=0, evaluation_queries=0, cases={}, bias={}) + diagnostic = 0 + for power in (1, 2): + r = quadrature(power) + diagnostic += r['forwards'] + results['cases'][str(power)] = dict(max_error=r['max_error'], + tangent_error=r['max_tangent'], + mean={n: v.flatten().tolist() for n, v in r['mean'].items()}, + truth={n: v.flatten().tolist() for n, v in r['truth'].items()}) + assert r['max_error'] < 1e-11 + for varying in ('mu', 'eps'): + errors = [] + for radius in (.08, .04, .02): + kwargs = dict(mu=1e-5, eps=1e-5) + kwargs[varying] = radius + r = quadrature(4, **kwargs) + diagnostic += r['forwards'] + errors.append(r['max_error']) + ratios = [errors[i]/errors[i+1] for i in range(2)] + assert all(3.8 < ratio < 4.2 for ratio in ratios) + results['bias'][varying] = dict(radii=[.08, .04, .02], errors=errors, ratios=ratios) + results['diagnostic_forward_queries'] = diagnostic + files = ['methods/large_models/trainer.py', 'methods/HISTORY_FREE_COVERAGE.md', + 'tests/test_history_free_coverage.py', 'scripts/validate_history_free_coverage.py'] + results['sources'] = {n: hashlib.sha256((ROOT/n).read_bytes()).hexdigest() for n in files} + results['command'] = '.venv/bin/python scripts/validate_history_free_coverage.py' + results['status'] = 'passed' + (out/'validation.json').write_text(json.dumps(results, indent=2)+'\n') + print(json.dumps(dict(output=str(out), cases=results['cases'], bias=results['bias'], + diagnostic_forward_queries=diagnostic), indent=2)) + + +if __name__ == '__main__': + main() diff --git a/scripts/verify_sources.py b/scripts/verify_sources.py new file mode 100644 index 0000000..183fdcd --- /dev/null +++ b/scripts/verify_sources.py @@ -0,0 +1,14 @@ +"""Verify vendored author files even after cloning the outer project without upstream Git objects.""" +import hashlib +import json +from pathlib import Path +ROOT=Path(__file__).resolve().parents[1] +manifest=json.loads((ROOT/'upstream_files.sha256.json').read_text()) +checked=0 +for method,entry in manifest.items(): + for name,expected in entry['files'].items(): + path=ROOT/'baselines'/method/name + assert path.is_file(),f'Missing official file: {path}' + assert hashlib.sha256(path.read_bytes()).hexdigest()==expected,f'Modified official file: {path}' + checked+=1 +print(json.dumps({'passed':True,'official_files_checked':checked})) diff --git a/src/experiments_codebase/__init__.py b/src/experiments_codebase/__init__.py new file mode 100644 index 0000000..9f6dc66 --- /dev/null +++ b/src/experiments_codebase/__init__.py @@ -0,0 +1 @@ +"""Standalone forward-only experiment runtime.""" diff --git a/src/experiments_codebase/official.py b/src/experiments_codebase/official.py new file mode 100644 index 0000000..d3ed620 --- /dev/null +++ b/src/experiments_codebase/official.py @@ -0,0 +1,81 @@ +"""Call pinned official numerical methods without legacy Trainer imports. + +This is a task/Trainer adapter, not a claim of reproducing an author's full protocol. +Upstream numerical function bodies are compiled intact. LOZO's optional replay fix +is an explicitly named variant and never changes the vendored source. +""" +import ast +import inspect +import logging +import math +import time +from pathlib import Path +from types import SimpleNamespace +from typing import Optional +import numpy as np +import torch +from .paths import REPO + +FILES={'mezo':'large_models/trainer.py','lozo':'large_models/LOZOtrainer.py','agzo':'zo-bench/trainer.py','loren':'model/glue_transformer_loren.py'} + +def methods(path,names,fix=False): + code=path.read_text() + if fix: + start=code.index(' def lowrank_zo_update(self):') + old=' v = self.v[name]\n u = self.random_gaussian_matrix' + new=' v = self.v[name]\n if self.step % args.step_interval == 0:\n torch.randn(param.data.size(1), args.rank_r, device=param.data.device, dtype=param.data.dtype)\n u = self.random_gaussian_matrix' + assert code[start:].count(old)==1 + code=code[:start]+code[start:].replace(old,new) + tree=ast.parse(code);cls=next(n for n in tree.body if isinstance(n,ast.ClassDef) and any(isinstance(x,ast.FunctionDef) and x.name in names for x in n.body)) + body=[n for n in cls.body if isinstance(n,ast.FunctionDef) and n.name in names] + if set(n.name for n in body)!=set(names):raise RuntimeError('Upstream optimizer API changed') + ns=dict(torch=torch,np=np,math=math,nn=torch.nn,Optional=Optional,logger=logging.getLogger(__name__),time=time) + unit=ast.Module(body=[ast.ClassDef(name='Upstream',bases=[],keywords=[],body=body,decorator_list=[])],type_ignores=[]) + exec(compile(ast.fix_missing_locations(unit),str(path),'exec'),ns) + return ns['Upstream'] + +def sgd_with_wdecay(param,grad,lr,weight_decay): + param.mul_(1-lr*weight_decay);param.add_(grad,alpha=-lr) + +def build(task,args): + method=args.method;path=REPO/'baselines'/method/FILES[method] + if method=='mezo':cls=methods(path,['zo_perturb_parameters','zo_step','zo_update']) + elif method=='lozo':cls=methods(path,['lowrank_zo_perturb_parameters','random_gaussian_matrix','lowrank_zo_step','lowrank_zo_update'],args.lozo_rng_fix) + elif method=='agzo':cls=methods(path,['_ensure_agzo_hooks','_register_agzo_hooks','_make_agzo_hook','_agzo_compute_direction','_agzo_power_iteration','agzo_collect_basis','_agzo_sample_z','_get_agzo_rank','_safe_normal','agzo_perturb_parameters','agzo_step']) + else: + original=methods(path,['configure_params','perturb_parameters','lnes_zo_update','training_step']) + class Scope: + def configure_params(self):pass + cls=type('ScopedOfficialLOREN',(original,Scope),{}) + for name in ('perturb_parameters','lnes_zo_update','training_step'): + inspect.unwrap(getattr(original,name)).__globals__.update(sgd_with_wdecay=sgd_with_wdecay) + state=cls();state.model=task.model + state.args=SimpleNamespace(zo_eps=args.mu,weight_decay=args.weight_decay,gradient_accumulation_steps=1, + step_interval=args.lozo_interval,rank_r=args.rank,q=1,perturbation_mode='two_side',agzo_power_iter_steps=args.power_iterations,agzo_rank=args.rank,agzo_debug_memory=False) + state.zo_forward=lambda model,inputs:task.loss(inputs) + state.zo_forward_memory_eff=state.zo_forward + state.current_lr=args.lr;state._get_learning_rate=lambda:state.current_lr + state.lr_scheduler=SimpleNamespace(step=lambda:None) + if method=='agzo': + state.agzo_enabled=True;state._agzo_hooks_registered=False;state.agzo_hooks=[];state.agzo_layer_inputs={};state.agzo_u={};state.agzo_collecting=False;state._agzo_missing_activation_warned=False + state.get_grad_sparsity_by_name=lambda name:None;state.sparse_grad_rng=torch.Generator(device=task.device);state.sparse_grad_random_seed=123 + state.optimizer=torch.optim.SGD(task.parameters,lr=args.lr,weight_decay=args.weight_decay) + if method=='loren': + if task.device.type!='cuda':raise ValueError('Official LOREN hardcodes cuda') + state.params=task.named_parameters;state.damping=args.damping;state.d_sqrt=math.sqrt(args.damping) + state.lr_cov=args.lr_cov;state.beta1=args.beta1;state.num_queries=args.loren_queries;state.zero_order_eps=args.mu;state.weight_decay=args.weight_decay + state.evec_a={};state.momentum={};state.param_info={} + state.state=SimpleNamespace(learning_rate=args.lr,global_training_steps=0,time=[],query=[]) + state.configure_params() + return state + +def update(state,task,args,inputs,lr): + state.current_lr=lr + if args.method=='mezo':value=state.zo_step(task.model,inputs);state.zo_update(task.model) + elif args.method=='lozo':value=state.lowrank_zo_step(task.model,inputs);state.lowrank_zo_update() + elif args.method=='agzo': + for g in state.optimizer.param_groups:g['lr']=lr + value=state.agzo_step(task.model,inputs) + else: + state.state.learning_rate=lr;log={};state.training_step(task.model,inputs,log=log);value=log['train_loss'] + return dict(batch_loss=float(value),learning_rate=lr,response=float(state.projected_grad) if hasattr(state,'projected_grad') else None) diff --git a/src/experiments_codebase/paths.py b/src/experiments_codebase/paths.py new file mode 100644 index 0000000..ef24eed --- /dev/null +++ b/src/experiments_codebase/paths.py @@ -0,0 +1,40 @@ +"""Shared assets, independent of cwd and the legacy workspace.""" +import json +import os +from pathlib import Path +import subprocess + +REPO=Path(__file__).resolve().parents[2] + +def configure_environment(): + root=Path(os.environ.get('EXPERIMENT_ASSETS','/mnt/e/Experiments/Assets')) + value={k:Path(os.environ.get('EXPERIMENT_'+k.upper(),str(root/k))) for k in ('models','data','results')} + os.environ['HF_HOME']=str(value['models']/'.huggingface') + os.environ['HF_HUB_CACHE']=str(value['models']/'.huggingface/hub') + os.environ['HF_DATASETS_CACHE']=str(value['data']/'.huggingface/datasets') + os.environ['HF_XET_CACHE']=str(value['models']/'.huggingface/xet') + return value + +def paths(): + value=configure_environment() + if any(str(p).startswith('/mnt/e/') for p in value.values()):subprocess.run(['mountpoint','-q','/mnt/e'],check=True) + for p in value.values():p.mkdir(parents=True,exist_ok=True) + return value + +# HF constants read environment at import time, before model/dataset code loads. +# Setting defaults here has no filesystem side effects, so --help stays usable. +configure_environment() + +def model_path(name): + alias={'facebook/opt-1.3b':'opt-1.3b','Qwen/Qwen3-0.6B':'qwen3-0.6b'}.get(name,name) + direct=Path(name).expanduser() + candidate=direct if direct.is_dir() else paths()['models']/alias + if not (candidate/'config.json').exists():raise FileNotFoundError(f'Model not staged: {candidate}') + return candidate + +def save(path,value): + p=Path(path);p.parent.mkdir(parents=True,exist_ok=True) + tmp=p.with_suffix(p.suffix+'.tmp');tmp.write_text(json.dumps(value,ensure_ascii=False,indent=2,allow_nan=False),encoding='utf-8');tmp.replace(p) + +def append(path,value): + with Path(path).open('a',encoding='utf-8') as stream:stream.write(json.dumps(value,ensure_ascii=False,allow_nan=False)+'\n') diff --git a/src/experiments_codebase/runner.py b/src/experiments_codebase/runner.py new file mode 100644 index 0000000..e39d55a --- /dev/null +++ b/src/experiments_codebase/runner.py @@ -0,0 +1,213 @@ +"""Common training, inference and audit entry point; all outputs live in Assets.""" +import argparse +from contextlib import redirect_stdout,redirect_stderr +from datetime import datetime,timezone +import hashlib +import importlib.metadata +import json +import math +import os +from pathlib import Path +import sys +import time +import traceback +import numpy as np +import torch +from .paths import paths,save,append,REPO +from .task import Task,batch,load_rows,seed_for +from . import official + +def parser(): + p=argparse.ArgumentParser(description=__doc__) + p.add_argument('--method',choices=['fix','adjust','node','mezo','agzo','lozo','loren'],default='fix') + p.add_argument('--model',default='facebook/opt-1.3b');p.add_argument('--task',choices=['sst2','drop'],default='sst2') + p.add_argument('--action',choices=['train','evaluate','generate'],default='train') + p.add_argument('--checkpoint',type=Path);p.add_argument('--prompt');p.add_argument('--max-new-tokens',type=int,default=32) + p.add_argument('--budget',type=int,default=6000,help='All main forwards: calibration, proposals, probes and updates') + p.add_argument('--lr',type=float,default=None);p.add_argument('--mu',type=float,default=1e-3) + p.add_argument('--weight-decay',type=float,default=0);p.add_argument('--seed',type=int,default=2026110791) + p.add_argument('--batch-size',type=int,default=16);p.add_argument('--eval-batch-size',type=int,default=16) + p.add_argument('--train-samples',type=int,default=1000);p.add_argument('--dev-samples',type=int,default=500) + p.add_argument('--eval-samples',type=int,default=872);p.add_argument('--calibration-samples',type=int,default=16) + p.add_argument('--max-length',type=int,default=128);p.add_argument('--eval-every',type=int,default=600) + p.add_argument('--refresh-every',type=int,default=None);p.add_argument('--probe-pairs',type=int,default=2) + p.add_argument('--gate-k',type=float,default=1);p.add_argument('--gate-margin',type=float,default=0) + p.add_argument('--node-queries',type=int,default=2);p.add_argument('--node-epsilon',type=float,default=1e-3) + p.add_argument('--history-beta',type=float,default=.9) + p.add_argument('--schedule',choices=['constant','cosine'],default=None) + p.add_argument('--decay-start',type=int,default=3000);p.add_argument('--lr-min',type=float,default=None) + p.add_argument('--rank',type=int,default=1);p.add_argument('--power-iterations',type=int,default=5) + p.add_argument('--lozo-interval',type=int,default=100);p.add_argument('--lozo-rng-fix',action='store_true') + p.add_argument('--loren-queries',type=int,default=6);p.add_argument('--damping',type=float,default=.1) + p.add_argument('--lr-cov',type=float,default=1e-3);p.add_argument('--beta1',type=float,default=.9) + p.add_argument('--dtype',choices=['float32','float16','bfloat16'],default='float32') + p.add_argument('--device',default='cuda');p.add_argument('--out',type=Path) + p.add_argument('--no-save-checkpoint',action='store_true');p.add_argument('--preflight-only',action='store_true') + return p + +def rate(args,q): + if args.schedule=='constant':return args.lr + fraction=min(1,max(0,(q-args.decay_start)/max(1,args.budget-args.decay_start))) + return args.lr_min+(args.lr-args.lr_min)*.5*(1+math.cos(math.pi*fraction)) + +def memory(): + if not torch.cuda.is_available():return {} + torch.cuda.synchronize();free,total=torch.cuda.mem_get_info();g=2**30 + return dict(allocated_GiB=torch.cuda.memory_allocated()/g,reserved_GiB=torch.cuda.memory_reserved()/g,peak_allocated_GiB=torch.cuda.max_memory_allocated()/g,device_used_GiB=(total-free)/g,device_total_GiB=total/g) + +def figures(out,curve): + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + for key,name in [('loss','loss_curve.png'),('accuracy','acc_curve.png')]: + fig,ax=plt.subplots(figsize=(8,4)) + found=False + for split in ('train_probe','development'): + points=[p for p in curve if key in p[split]] + if points:ax.plot([p['main_forwards'] for p in points],[p[split][key] for p in points],label=split);found=True + if not found:plt.close(fig);continue + ax.set(xlabel='Cumulative main forwards (including probes)',ylabel=key);ax.grid(alpha=.2);ax.legend();fig.tight_layout();fig.savefig(out/name,dpi=160);plt.close(fig) + +def restore(task,path): + state=torch.load(path,map_location=task.device,weights_only=False) + task.model.load_state_dict(state['model']) + if state['structured']: + # Install hooks without a calibration query; the saved basis is authoritative. + first={n:s['basis'] for n,s in state['structured'].items()} + task.collect_basis=lambda *a,**k:first + task.configure(None);task.structured=state['structured'];task.history=state.get('history',{}) + return state + +@torch.no_grad() +def execute(args,out): + begin=time.monotonic();curve=[];step=0;latest={};used=lambda:task.counts['training']+task.counts['calibration'] + def progress(stage,**kw): + point=curve[-1] if curve else None + best=min(curve,key=lambda p:p['development']['loss']) if curve else None + value=dict(stage=stage,completed=used() if 'task' in locals_outer else 0,total=args.budget,current_unit=args.method, + pid=os.getpid(),output_directory=str(out),elapsed_seconds=time.monotonic()-begin,last_update=datetime.now(timezone.utc).isoformat(), + step=step,latest_training_batch=latest,evaluation=point,best_development=None if best is None else dict(loss=best['development']['loss'],main_forwards=best['main_forwards']), + current_lr=rate(args,used()) if 'task' in locals_outer else args.lr,memory=memory(),**kw) + save(out/'progress.json',value) + text=f"# {args.method}: {stage}\n\nMain forwards: {value['completed']}/{args.budget}; updates: {step}; PID: {os.getpid()}\n\n" + text+=f"Latest batch: {json.dumps(latest)}\n\nLast evaluation (with actual query count): {json.dumps(point)}\n\nBest development: {json.dumps(value['best_development'])}\n\nLR: {value['current_lr']}; elapsed seconds: {value['elapsed_seconds']:.1f}\n\nUpdated UTC: {value['last_update']}\n" + tmp=out/'progress.md.tmp';tmp.write_text(text);tmp.replace(out/'progress.md') + print(json.dumps(value),flush=True) + locals_outer={};progress('loading') + task=Task(args);locals_outer['task']=task + try: + if args.checkpoint:restore(task,args.checkpoint) + if args.action=='generate': + if not args.prompt:raise ValueError('--prompt is required') + inputs=task.tokenizer(args.prompt,return_tensors='pt').to(task.device) + tokens=task.model.generate(**inputs,max_new_tokens=args.max_new_tokens,do_sample=False,pad_token_id=task.tokenizer.pad_token_id) + save(out/'generation.json',{'text':task.tokenizer.decode(tokens[0],skip_special_tokens=True)});progress('complete');return + rows=load_rows(args,task.tokenizer) + for split,data in rows.items():save(out/'data'/f'{split}.json',data) + hashes={s:hashlib.sha256((out/'data'/f'{s}.json').read_bytes()).hexdigest() for s in rows} + save(out/'data_manifest.json',dict(sha256=hashes,counts={s:len(r) for s,r in rows.items()},selection='independent train/development subsets of train split; validation held out')) + if args.action=='evaluate': + save(out/'evaluation.json',task.evaluate(rows['validation']));progress('complete');return + ours=args.method in ('fix','adjust','node') + if ours and not args.checkpoint: + calibration=batch(rows['train'][:args.calibration_samples],task.tokenizer,task.device);task.configure(calibration) + if args.method=='node':task.configure_history() + save(out/'parameter_inventory.json',dict(unique_parameters=sum(p.numel() for p in task.parameters),unique_tensors=len(task.parameters),linear_weights=len(task.linear_map),structured_weights=len(task.structured), + coverage='All unique original parameters: structured Linear SGD; embedding/norm/bias Gaussian SGD; tied head once' if ours else 'Official numerical methods applied to all unique original parameters',node_targets=list(task.history))) + state=None if ours else official.build(task,args) + if args.preflight_only: + if ours: + inp=batch(rows['train'][:2],task.tokenizer,task.device);old=task.dense_snapshot();clean=task.call(inp,'diagnostic')[0].clone() + task.shifted(inp,task.bases(),task.directions(71),args.mu,old) + assert all(torch.equal(task.parameter_map[n],v) for n,v in old.items()) + torch.testing.assert_close(clean,task.call(inp,'diagnostic')[0],rtol=0,atol=0) + before=task.call(inp,'diagnostic')[0].clone();task.switch({n:-d for n,d in task.bases().items()}) + torch.testing.assert_close(before,task.call(inp,'diagnostic')[0],rtol=0,atol=0) + save(out/'preflight.json',dict(passed=True,memory=memory(),counts=task.counts));progress('complete');return + rng=np.random.default_rng(seed_for(args.seed,11));probe_rng=np.random.default_rng(seed_for(args.seed,12));order=rng.permutation(len(rows['train']));cursor=0 + def sample_next(): + nonlocal cursor,order + if cursor+args.batch_size>len(order):order=rng.permutation(len(rows['train']));cursor=0 + indices=order[cursor:cursor+args.batch_size];cursor+=args.batch_size + return batch([rows['train'][i] for i in indices],task.tokenizer,task.device) + def probe_batch(): + ids=probe_rng.choice(len(rows['train']),min(args.batch_size,len(rows['train'])),replace=False) + return batch([rows['train'][i] for i in ids],task.tokenizer,task.device) + def measure(): + point=dict(main_forwards=used(),step=step,elapsed_seconds=time.monotonic()-begin, + train_probe=task.evaluate(rows['train'][:min(128,len(rows['train']))]),development=task.evaluate(rows['development'])) + curve.append(point);save(out/'curve.json',curve);figures(out,curve);progress('evaluation') + measure();next_eval=args.eval_every + cost={'mezo':2,'lozo':2,'agzo':3,'loren':args.loren_queries}.get(args.method,2) + while used()+cost<=args.budget: + lr=rate(args,used()) + if ours and step and step%args.refresh_every==0 and args.method!='fix': + need=(1+5*args.probe_pairs) if args.method=='adjust' else 1+len(task.history)*args.node_queries + if used()+need+2<=args.budget: + before=used();event=dict(step=step) + if args.method=='adjust': + new=task.collect_basis(probe_batch());trials=[task.probe(probe_batch(),probe_batch(),new,seed_for(args.seed,91,step*args.probe_pairs+j),lr) for j in range(args.probe_pairs)] + gains=np.array([r['gain'] for r in trials]);mean=float(gains.mean());sem=float(gains.std(ddof=1)/math.sqrt(len(gains))) + accept=mean-args.gate_k*sem>args.gate_margin + if accept:task.switch(new) + event.update(trials=trials,mean_gain=mean,sem=sem,accepted=bool(accept)) + else:event['layers']=task.node_refresh(probe_batch(),seed_for(args.seed,705,step)) + event.update(main_forwards=used(),cost=used()-before);append(out/'refresh.jsonl',event) + if used()+cost>args.budget:break + step+=1;inputs=sample_next();before=used() + np.random.seed(seed_for(args.seed,33,step)%2**32);torch.manual_seed(seed_for(args.seed,22,step)) + latest=task.update(inputs,seed_for(args.seed,33,step),lr) if ours else official.update(state,task,args,inputs,lr) + if used()-before!=cost:raise AssertionError(f'Actual query count {used()-before} != expected {cost}') + append(out/'records.jsonl',dict(step=step,main_forwards=used(),**latest)) + if step%10==0:progress('training') + if used()>=next_eval:measure();next_eval=(used()//args.eval_every+1)*args.eval_every + if curve[-1]['main_forwards']!=used():measure() + validation=task.evaluate(rows['validation']) + save(out/'summary.json',dict(status='complete',steps=step,main_forwards=used(),counts=task.counts,validation=validation,memory=memory(),elapsed_seconds=time.monotonic()-begin)) + save(out/'query_ledger.json',dict(main_forwards=used(),counts=task.counts,all_detection_charged=True,evaluations_separate=True)) + if not args.no_save_checkpoint: + checkpoint=dict(model={n:v.detach().cpu() for n,v in task.model.state_dict().items()},structured=task.structured_state(),history={n:h.cpu() for n,h in task.history.items()},arguments=vars(args),step=step,counts=task.counts, + data_order=order,cursor=cursor,rng=rng.bit_generator.state,probe_rng=probe_rng.bit_generator.state,torch_rng=torch.get_rng_state(),cuda_rng=torch.cuda.get_rng_state_all() if torch.cuda.is_available() else [],purpose='Inference checkpoint; training resume not implemented') + tmp=out/'model.pt.tmp';torch.save(checkpoint,tmp);tmp.replace(out/'model.pt') + progress('complete') + except BaseException: + save(out/'failure.json',dict(traceback=traceback.format_exc()));progress('failed');raise + finally:task.close() + +class Tee: + def __init__(self,*streams):self.streams=streams + def write(self,text): + for stream in self.streams:stream.write(text);stream.flush() + def flush(self): + for stream in self.streams:stream.flush() + +def main(forced_method=None): + args=parser().parse_args() + if forced_method:args.method=forced_method + elif args.method not in ('fix','adjust'):raise ValueError('fix_adjust entry accepts only --method fix or adjust') + args.lr=args.lr if args.lr is not None else (1.5e-6 if args.method=='node' else 1e-6) + args.lr_min=args.lr_min if args.lr_min is not None else args.lr*.1 + args.schedule=args.schedule or ('cosine' if args.method=='node' else 'constant') + args.refresh_every=args.refresh_every or (128 if args.method=='node' else 256) + if min(args.batch_size,args.eval_batch_size,args.train_samples,args.dev_samples,args.eval_samples,args.calibration_samples,args.eval_every,args.refresh_every,args.node_queries,args.rank)<=0:raise ValueError('Counts must be positive') + if args.probe_pairs<2 or args.budget<3 or args.lr<=0 or args.mu<=0:raise ValueError('Invalid budget, probe pairs, LR or mu') + if args.method in ('fix','adjust','node') and (args.rank!=1 or args.weight_decay!=0):raise ValueError('Our audited variant uses rank=1, weight_decay=0') + if args.method in ('fix','adjust','node') and args.dtype!='float32':raise ValueError('Structured basis/moment equivalence is audited in FP32; low precision needs a separate audit') + if args.checkpoint and args.action=='train':raise ValueError('Checkpoint supports inference only; train from a fresh model') + storage=paths()['results'].resolve();stamp=datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ') + out=(args.out or storage/f'{args.method}_{args.task}_{stamp}').resolve() + if not out.is_relative_to(storage):raise ValueError(f'Outputs must stay under {storage}') + out.mkdir(parents=True,exist_ok=False) + # Paths are serialized as strings; the complete effective config is retained. + hyper={k:str(v) if isinstance(v,Path) else v for k,v in vars(args).items()} + hyper.update(q=1 if args.method!='loren' else args.loren_queries,gradient_accumulation=1,tf32=False,dropout_active=False, + optimizer='SGD, momentum=0' if args.method in ('fix','adjust','node','mezo','agzo','lozo') else 'official LOREN sequential covariance/momentum update', + difference='one-sided shared clean' if args.method in ('fix','adjust','node') else ('official RLOO' if args.method=='loren' else 'central two-sided')) + save(out/'hyperparameters.json',hyper) + save(out/'source_manifest.json',{str(f.relative_to(REPO)):hashlib.sha256(f.read_bytes()).hexdigest() for f in sorted((REPO/'src').rglob('*.py'))}) + save(out/'environment.json',dict(python=sys.version,executable=sys.executable,versions={name:importlib.metadata.version(name) for name in ('torch','transformers','datasets','huggingface-hub','numpy')},command=sys.argv, + upstream=json.loads((REPO/'upstream.lock.json').read_text()),adapter='common task protocol with official numerical bodies; not native Trainer')) + print(f'Output: {out}',flush=True) + torch.set_num_threads(4);torch.backends.cuda.matmul.allow_tf32=False;torch.backends.cudnn.allow_tf32=False + with (out/'run.log').open('w',encoding='utf-8') as log,redirect_stdout(Tee(sys.stdout,log)),redirect_stderr(Tee(sys.stderr,log)): + execute(args,out) diff --git a/src/experiments_codebase/task.py b/src/experiments_codebase/task.py new file mode 100644 index 0000000..19e9e5b --- /dev/null +++ b/src/experiments_codebase/task.py @@ -0,0 +1,221 @@ +"""Forward-only common protocol; structured SGD and exact dense restoration.""" +import math +import numpy as np +import torch +import torch.nn.functional as F +from transformers import AutoModelForCausalLM, AutoTokenizer +from .paths import model_path, paths + +def seed_for(seed,stream,step=0): + return int(np.random.SeedSequence([seed,stream,step]).generate_state(1,dtype=np.uint64)[0]%(2**63-1)) + +def top_basis(x,rank=1): + x=x.float() + if x.shape[0]len(ds['train']):raise ValueError('Train/development sample counts exceed dataset size') + ids=rng.permutation(len(ds['train']))[:n];groups={} + specifications=[('train','train',ids[:args.train_samples]),('development','train',ids[args.train_samples:]),('validation','validation',range(min(args.eval_samples,len(ds['validation']))))] + for split,source,indices in specifications: + rows=[] + for i in indices: + row=ds[source][int(i)] + if args.task=='sst2': + tokens=tokenizer.encode(f"{row['sentence'].strip()} It was",add_special_tokens=True,truncation=True,max_length=args.max_length) + rows.append(dict(input_ids=tokens,label=int(row['label']),source_index=int(i),source_split=source)) + else: + answers=[str(v) for v in row['answers_spans']['spans']] + answer=tokenizer.encode(' '+answers[0],add_special_tokens=False)[:min(32,args.max_length//4)] + prompt=f"Passage: {row['passage']}\nQuestion: {row['question']}\nAnswer:" + tokens=tokenizer.encode(prompt,add_special_tokens=True,truncation=True,max_length=args.max_length-len(answer)) + if not tokens or not answer:raise ValueError('Empty DROP prompt or answer') + rows.append(dict(input_ids=tokens+answer,prompt_ids=tokens,answer_length=len(answer),answers=answers,source_index=int(i),source_split=source)) + groups[split]=rows + return groups + +def batch(rows,tokenizer,device): + width=math.ceil(max(len(r['input_ids']) for r in rows)/8)*8 + ids=torch.full((len(rows),width),tokenizer.pad_token_id,dtype=torch.long,device=device) + mask=torch.zeros_like(ids);targets=torch.full_like(ids,-100) + for i,row in enumerate(rows): + size=len(row['input_ids']);ids[i,-size:]=torch.tensor(row['input_ids'],device=device);mask[i,-size:]=1 + if row.get('answer_length',0):targets[i,-row['answer_length']:]=ids[i,-row['answer_length']:] + labels=torch.tensor([r['label'] for r in rows],device=device) if 'label' in rows[0] else targets + return dict(input_ids=ids,attention_mask=mask,labels=labels) + +class Task: + def __init__(self,args): + self.args=args;self.device=torch.device(args.device) + self.tokenizer=AutoTokenizer.from_pretrained(model_path(args.model),local_files_only=True,use_fast='opt' not in args.model.lower()) + if 'opt' in args.model.lower():self.tokenizer.bos_token_id=0 + if self.tokenizer.pad_token_id is None:self.tokenizer.pad_token=self.tokenizer.eos_token + self.tokenizer.padding_side='left' + self.model=AutoModelForCausalLM.from_pretrained(model_path(args.model),local_files_only=True,torch_dtype=getattr(torch,args.dtype),attn_implementation='eager').to(self.device).eval() + self.model.config.use_cache=False + self.named_parameters=list(self.model.named_parameters());self.parameter_map=dict(self.named_parameters) + self.parameters=[p for _,p in self.named_parameters] + self.linear_map={n+'.weight':m for n,m in self.model.named_modules() if isinstance(m,torch.nn.Linear) and n+'.weight' in self.parameter_map} + self.label_ids=[] + for word in (' terrible',' great'): + ids=self.tokenizer.encode(word,add_special_tokens=False) + if len(ids)!=1:raise ValueError(f'Verbalizer must have one token: {word!r} -> {ids}') + self.label_ids.append(ids[0]) + self.counts=dict(training=0,calibration=0,evaluation=0,diagnostic=0) + self.structured={};self.noise=None;self.handles=[];self.history={} + self.model.requires_grad_(True) + + def call(self,inputs,category='training'): + self.counts[category]+=1 + hidden=self.model.model(input_ids=inputs['input_ids'],attention_mask=inputs['attention_mask'],use_cache=False).last_hidden_state + if self.args.task=='sst2': + logits=self.model.lm_head(hidden[:,-1])[:,self.label_ids] + losses=F.cross_entropy(logits.float(),inputs['labels'],reduction='none') + else: + shifted=inputs['labels'][:,1:];valid=shifted!=-100 + logits=self.model.lm_head(hidden[:,:-1][valid]).float() + token_loss=F.cross_entropy(logits,shifted[valid],reduction='none') + owner=torch.arange(len(hidden),device=hidden.device)[:,None].expand_as(valid)[valid] + losses=torch.zeros(len(hidden),device=hidden.device).scatter_add_(0,owner,token_loss)/valid.sum(1).clamp_min(1) + if not bool(torch.isfinite(losses).all()):raise FloatingPointError('Nonfinite loss') + return losses,logits + + def loss(self,inputs,category='training'):return self.call(inputs,category)[0].mean().detach() + + def collect_basis(self,inputs,category='training'): + mask=inputs['attention_mask'].bool().reshape(-1);result={};handles=[] + for name,module in self.linear_map.items(): + def capture(mod,args,name=name): + x=args[0].reshape(-1,args[0].shape[-1])[mask];d=top_basis(x) + if name in self.structured and float((d.T@self.structured[name]['basis']).sum())<0:d=-d + result[name]=d + handles.append(module.register_forward_pre_hook(capture)) + try:self.call(inputs,category) + finally: + for h in handles:h.remove() + if len(result)!=len(self.linear_map):raise RuntimeError('Not every linear layer executed') + return result + + def configure(self,calibration): + bases=self.collect_basis(calibration,'calibration');self.model.requires_grad_(False) + for name,module in self.linear_map.items(): + d=bases[name];self.structured[name]=dict(basis=d,b=d.new_zeros(module.out_features,1),warm=[]) + def hook(mod,args,output,name=name): + state=self.structured[name];x=args[0] + for d,b in state['warm']:output=output+F.linear(x@d,b) + if self.noise is not None: + bases,z,scale,response=self.noise + delta=z[name]*scale if response is None else torch.zeros_like(z[name]).add_(z[name]*response,alpha=scale) + if bases[name] is state['basis']: + b=state['b']+delta if response is None else torch.add(state['b'],z[name]*response,alpha=scale) + output=output+F.linear(x@state['basis'],b) + else: + output=output+F.linear(x@state['basis'],state['b']) + output=output+F.linear(x@bases[name],delta) + else:output=output+F.linear(x@state['basis'],state['b']) + return output + self.handles.append(module.register_forward_hook(hook)) + + def bases(self):return {n:s['basis'] for n,s in self.structured.items()} + + def directions(self,seed): + gen=torch.Generator(device=self.device).manual_seed(seed) + return {n:torch.randn(self.structured[n]['b'].shape if n in self.structured else p.shape,device=p.device,dtype=p.dtype,generator=gen) for n,p in self.named_parameters} + + def dense_snapshot(self):return {n:p.detach().clone() for n,p in self.named_parameters if n not in self.structured} + + def shifted(self,inputs,bases,z,scale,old,response=None): + try: + self.noise=(bases,z,scale,response) + for n,p in self.named_parameters: + if n in old:p.copy_(old[n]);p.add_(z[n] if response is None else z[n]*response,alpha=scale) + return self.call(inputs)[0].detach().clone() + finally: + self.noise=None + for n,p in self.named_parameters: + if n in old:p.copy_(old[n]) + + def update(self,inputs,seed,lr): + z=self.directions(seed);old=self.dense_snapshot();clean=self.call(inputs)[0] + plus=self.shifted(inputs,self.bases(),z,self.args.mu,old) + slope=float((plus-clean).double().mean())/self.args.mu + if not math.isfinite(slope):raise FloatingPointError('Nonfinite ZO response') + square=0 + for n,p in self.named_parameters: + g=z[n].mul_(slope);square+=float(g.float().square().sum())*lr**2 + if n in self.structured:self.structured[n]['b'].add_(g,alpha=-lr) + else:p.add_(g,alpha=-lr) + if n in self.history:self.history[n].mul_(self.args.history_beta).add_(g,alpha=1-self.args.history_beta) + return dict(batch_loss=float(clean.mean()),response=slope,update_norm=math.sqrt(square),learning_rate=lr) + + def probe(self,inputs,reference,new,seed,lr): + z=self.directions(seed);old=self.dense_snapshot();clean=self.call(inputs)[0] + a0=float((self.shifted(inputs,self.bases(),z,self.args.mu,old)-clean).double().mean())/self.args.mu + a1=float((self.shifted(inputs,new,z,self.args.mu,old)-clean).double().mean())/self.args.mu + l0=self.shifted(reference,self.bases(),z,-lr,old,response=a0) + l1=self.shifted(reference,new,z,-lr,old,response=a1) + return dict(gain=float((l0-l1).double().mean()),old_loss=float(l0.mean()),new_loss=float(l1.mean())) + + def switch(self,new): + for n,d in new.items(): + s=self.structured[n];s['warm'].append((s['basis'],s['b']));s['basis']=d;s['b']=torch.zeros_like(s['b']) + + def configure_history(self): + names=[n for n in self.structured if n.endswith('self_attn.v_proj.weight')] + if len(names)<3:raise ValueError('Node proposal needs three v_proj layers') + ids=sorted(set(min(len(names)-1,int(len(names)*v/24)) for v in (15,17,19))) + if len(ids)<3:ids=list(range(len(names)-3,len(names))) + self.history={names[i]:torch.zeros_like(self.structured[names[i]]['b']) for i in ids} + + def node_refresh(self,inputs,seed): + clean,logits=self.call(inputs);mask=inputs['attention_mask'].bool();new={};metrics={} + if self.args.task=='sst2':residual=logits.softmax(1)[:,1]-inputs['labels'];margin=logits[:,1]-logits[:,0] + for ni,(n,hist) in enumerate(self.history.items()): + norm=float(hist.norm()) + if norm<=1e-20:metrics[n]={'skipped':'zero history'};continue + p=hist.flatten()/norm;est=[] + for k in range(self.args.node_queries): + gen=torch.Generator(device=self.device).manual_seed(seed_for(seed,ni,k)) + eta=(torch.randint(0,2,mask.shape,generator=gen,device=self.device)*2-1)*mask;features={} + def hook(mod,args,output): + x=args[0].reshape(*mask.shape,-1);features['x']=(x*eta[:,:,None]).sum(1) + return output+(self.args.node_epsilon*eta[:,:,None]*p).reshape_as(output) + handle=self.linear_map[n].register_forward_hook(hook) + try:pert_loss,pert_logits=self.call(inputs) + finally:handle.remove() + if self.args.task=='sst2':d=residual*((pert_logits[:,1]-pert_logits[:,0])-margin)/self.args.node_epsilon + else:d=(pert_loss-clean)/self.args.node_epsilon + est.append((features['x']*d[:,None]).mean(0)) + sketch=torch.stack(est).mean(0);sn=float(sketch.norm()) + if sn<=1e-20:metrics[n]={'skipped':'zero sketch'};continue + d=sketch[:,None]/sn;old=self.structured[n]['basis'] + if float((d.T@old).sum())<0:d=-d + new[n]=d;metrics[n]=dict(history_norm=norm,sketch_norm=sn,overlap=float((d.T@old).square().sum())) + self.switch(new) + for n in new:self.history[n].zero_() + return metrics + + def structured_state(self): + return {n:{'basis':s['basis'].cpu(),'b':s['b'].cpu(),'warm':[(d.cpu(),b.cpu()) for d,b in s['warm']]} for n,s in self.structured.items()} + + def close(self): + for h in self.handles:h.remove() + + def evaluate(self,rows): + losses=[];correct=0 + for start in range(0,len(rows),self.args.eval_batch_size): + chosen=rows[start:start+self.args.eval_batch_size];inputs=batch(chosen,self.tokenizer,self.device) + values,logits=self.call(inputs,'evaluation');losses.extend(values.double().cpu().tolist()) + if self.args.task=='sst2':correct+=int((logits.argmax(1)==inputs['labels']).sum()) + result={'loss':float(np.mean(losses)),'examples':len(rows)} + if self.args.task=='sst2':result['accuracy']=correct/len(rows) + return result diff --git a/tests/test_best_checkpoint.py b/tests/test_best_checkpoint.py new file mode 100644 index 0000000..47ecde9 --- /dev/null +++ b/tests/test_best_checkpoint.py @@ -0,0 +1,64 @@ +"""Development-only selection, disk restore, and tied-weight round trip.""" +from types import SimpleNamespace +import json +import pytest +import torch +from transformers import OPTConfig, OPTForCausalLM +from test_mezo_refactor import make_trainer + + +@torch.no_grad() +@pytest.mark.parametrize('sharded', [False, True]) +def test_best_checkpoint_keeps_earliest_minimum_and_restores_weights(tmp_path, monkeypatch, sharded): + from methods.large_models import trainer as module + monkeypatch.setattr(module, 'figures', lambda *args: None) + model = OPTForCausalLM(OPTConfig(vocab_size=16, hidden_size=8, ffn_dim=16, + num_hidden_layers=1, num_attention_heads=2, max_position_embeddings=16)) + engine = make_trainer(model, lambda batch: None) + engine.args.output_dir = str(tmp_path) + engine.args.select_best_checkpoint = True + engine.args.data_protocol = 'mezo' + engine.processing_class = SimpleNamespace(save_pretrained=lambda *args: None) + engine.train_dataset, engine.eval_dataset = [0], [1] + engine.curve = [];engine.started = 0 + engine.progress = lambda *args: None + loss = [3.] + def evaluate(*args): + engine.counts['evaluation'] += 1 + return dict(loss=loss[0], accuracy=.5) + engine.evaluate_dataset = evaluate + parameter = model.get_input_embeddings().weight + rng = torch.random.get_rng_state() + for step, value in enumerate((3., 2., 2., 4.), 1): + engine.state.global_step = step + engine.counts['training'] = step*2 + parameter.fill_(float(step)) + loss[0] = value + engine.measure() + assert float(parameter[0, 0]) == step # Saving does not rewind training. + assert engine.best_checkpoint['step'] == 2 # Tie retains earlier best. + assert json.loads((tmp_path/'best_checkpoint.json').read_text())['development']['loss'] == 2 + if sharded: + engine.restore_best_model() + model.save_pretrained(tmp_path/'best_model', max_shard_size='1KB') + parameter.fill_(4.) + engine.restore_best_model() + assert torch.all(parameter == 2) + assert parameter is model.get_output_embeddings().weight + assert torch.equal(rng, torch.random.get_rng_state()) + + +@torch.no_grad() +def test_initial_evaluation_is_not_a_train_checkpoint(tmp_path, monkeypatch): + from methods.large_models import trainer as module + monkeypatch.setattr(module, 'figures', lambda *args: None) + engine = module.OurTrainer.__new__(module.OurTrainer) + engine.args = SimpleNamespace(output_dir=str(tmp_path), select_best_checkpoint=True) + engine.state = SimpleNamespace(global_step=0) + engine.counts = dict(training=0, calibration=1, evaluation=0) + engine.train_dataset, engine.eval_dataset = [0], [1] + engine.curve = [];engine.started = 0;engine.progress = lambda *args: None + engine.evaluate_dataset = lambda *args: dict(loss=1.) + engine.save_model = lambda *args: (_ for _ in ()).throw(AssertionError('initial save')) + engine.measure() + assert not hasattr(engine, 'best_checkpoint') diff --git a/tests/test_curvature_steps.py b/tests/test_curvature_steps.py new file mode 100644 index 0000000..bc17423 --- /dev/null +++ b/tests/test_curvature_steps.py @@ -0,0 +1,147 @@ +"""Conditional implementation versus exact quadratic derivatives, not an LLM proxy.""" +import copy +import pytest +import torch +from test_node_descent import quadratic_engine + + +def options(): + return dict(certified_smoothness=10., basis_lr=.003, basis_radius=.02) + + +def quadratic_quantities(engine, batch): + x = batch['x'].reshape(-1, 2) + design = torch.cat([torch.ones(len(x), 1, dtype=x.dtype), x, x], dim=1) + # named_parameters orders the direct offset before child Linear weights. + theta = torch.cat([p.flatten() for _, p in engine.named_parameters]) + residual = design @ theta-batch['target'].flatten() + return theta, design.T @ residual/len(x), design.T @ design/len(x) + + +def lifted(engine, bases, seed): + return torch.cat([(z @ bases[n].T if n in bases else z).flatten() + for n, _, z in engine.directions(seed)]) + + +@torch.no_grad() +@pytest.mark.parametrize('smoothness', [None, 10.]) +def test_refresh_matches_exact_cross_batch_score_and_basis_gradient(quadratic_engine, smoothness): + engine, batch = quadratic_engine + batches = [dict(batch, target=batch['target']+shift) for shift in [.2, -.3, .4]] + old_basis = copy.deepcopy(engine.basis) + weights = [p.clone() for p in engine.parameters] + g_a = quadratic_quantities(engine, batches[0])[1] + g_b = quadratic_quantities(engine, batches[1])[1] + k = quadratic_quantities(engine, batches[2])[2] + # Eigenvalue certificate for this quadratic only, not for a neural network. + assert float(torch.linalg.eigvalsh(k).max()) <= options()['certified_smoothness'] + gen = torch.Generator().manual_seed(56) + tangents = {} + candidates = [{}, {}] + for name, d in old_basis.items(): + v = torch.randn(d.shape, dtype=d.dtype, generator=gen) + v -= d*(d*v).sum() + tangents[name] = v + for bases, sign in zip(candidates, [1, -1]): + bases[name] = torch.nn.functional.normalize(d+sign*.02*v, dim=0) + expected = [] + for bases in candidates: + u = lifted(engine, bases, 123) + h = u @ k @ u+(0 if smoothness is None else 2*smoothness)*(u @ u) + expected.append(float((g_a @ u)*(g_b @ u)*(1-engine.current_lr*h/2))) + before = engine.used() + event = engine.curvature_refresh(batches, 123, 56, **dict(options(), certified_smoothness=smoothness)) + assert event['curvature_quantity'] == ('local_hessian' if smoothness is None else 'certified_quadratic_upper_bound') + assert engine.used()-before == event['cost'] == 13 + assert engine.counts['evaluation'] == 0 + assert [p['score'] for p in event['probes']] == pytest.approx(expected, abs=1e-11) + q = (expected[0]-expected[1])/.04 + assert event['difference_quotient'] == pytest.approx(q, abs=1e-10) + for name, d in old_basis.items(): + target = torch.nn.functional.normalize(d+.003*q*tangents[name], dim=0) + torch.testing.assert_close(engine.basis[name], target, atol=1e-12, rtol=1e-12) + for old, actual in zip(weights, engine.parameters): + torch.testing.assert_close(old, actual, atol=1e-12, rtol=1e-12) + assert actual.grad is None + + +@pytest.mark.parametrize('remaining', [14, 15]) +@torch.no_grad() +def test_full_step_budget_and_exact_one_sided_weight_update(quadratic_engine, remaining): + engine, batch = quadratic_engine + engine.args.main_forward_budget = engine.used()+remaining + before = engine.used() + theta, g, k = quadratic_quantities(engine, batch) + draws = [] + def independent_batches(): + draws.append(1) + return [dict(batch) for _ in range(3)] # Deterministic objective; no sample noise. + result, event = engine.curvature_step(batch, 234, selection_batches=independent_batches, **options()) + assert len(draws) == int(remaining == 15) + assert engine.used()-before == (15 if remaining == 15 else 2) + if event is not None: + assert event['seed'] != 234 and event['cost'] == 13 + u = lifted(engine, engine.basis, 234) + slope = g @ u+engine.args.zo_eps*(u @ k @ u)/2 + expected = theta-engine.current_lr*slope*u + actual = torch.cat([p.flatten() for p in engine.parameters]) + torch.testing.assert_close(actual, expected, atol=1e-12, rtol=1e-12) + assert result['response'] == pytest.approx(float(slope), abs=1e-12) + + +@torch.no_grad() +def test_failed_refresh_restores_weights_without_switching_basis(quadratic_engine): + engine, batch = quadratic_engine + old_basis = copy.deepcopy(engine.basis) + weights = [p.clone() for p in engine.parameters] + original = engine._forward_outputs + def forward(inputs): + if engine.counts['training'] == 6: + raise RuntimeError('query failed') + return original(inputs) + engine._forward_outputs = forward + with pytest.raises(RuntimeError, match='query failed'): + engine.curvature_refresh([batch]*3, 123, 56, **options()) + for n in old_basis: + torch.testing.assert_close(old_basis[n], engine.basis[n], atol=0, rtol=0) + for old, actual in zip(weights, engine.parameters): + torch.testing.assert_close(old, actual, atol=1e-12, rtol=1e-12) + + +@torch.no_grad() +def test_refresh_does_not_clone_full_parameters_or_change_global_rng(quadratic_engine, monkeypatch): + engine, batch = quadratic_engine + before_rng = torch.random.get_rng_state() + original = torch.Tensor.clone + def clone(tensor, *args, **kwargs): + assert tensor.numel() == 1, 'Cloned non-scalar parameter/noise' + return original(tensor, *args, **kwargs) + monkeypatch.setattr(torch.Tensor, 'clone', clone) + engine.curvature_refresh([batch]*3, 123, 56, **options()) + assert torch.equal(before_rng, torch.random.get_rng_state()) + + +@torch.no_grad() +def test_fp32_refresh_restoration_has_bounded_rounding_error(quadratic_engine): + engine, batch = quadratic_engine + engine.model.float() + engine.basis = {n: d.float() for n, d in engine.basis.items()} + batch = {n: x.float() if x.is_floating_point() else x for n, x in batch.items()} + before = [p.clone() for p in engine.parameters] + event = engine.curvature_refresh([batch]*3, 123, 56, **options()) + assert event['cost'] == 13 + for p, old in zip(engine.parameters, before): + torch.testing.assert_close(p, old, rtol=1e-6, atol=1e-7) + for d in engine.basis.values(): + assert float(d.norm()) == pytest.approx(1., abs=1e-6) + + +@pytest.mark.parametrize('value', [0., -1., float('nan'), float('inf')]) +def test_invalid_curvature_constants_fail_before_queries(quadratic_engine, value): + engine, batch = quadratic_engine + opts = options() + opts['certified_smoothness'] = value + before = engine.used() + with pytest.raises(ValueError, match='positive finite'): + engine.curvature_refresh([batch]*3, 123, 56, **opts) + assert engine.used() == before diff --git a/tests/test_curvature_theory.py b/tests/test_curvature_theory.py new file mode 100644 index 0000000..18585b8 --- /dev/null +++ b/tests/test_curvature_theory.py @@ -0,0 +1,369 @@ +"""Independent checks of the supplied descent theorem, not production training.""" +import itertools +import numpy as np +import pytest +import torch +from methods.large_models.trainer import ( + curvature_descent_reference, curvature_input_gradient_reference, +) + + +def quadratic(): + generator = torch.Generator().manual_seed(73) + x = torch.randn(3, 3, generator=generator, dtype=torch.float64) + h = x.T @ x + torch.eye(3, dtype=torch.float64) + g = torch.tensor([.4, -.7, .2], dtype=torch.float64) + u = torch.linalg.qr(torch.randn(3, 2, generator=generator, dtype=torch.float64)).Q + return g, h, u + + +@pytest.mark.parametrize('mu', [0., .07]) +@pytest.mark.parametrize('n', [1, 2]) +def test_projection_derivative_matches_independent_autograd(mu, n): + g, h, u = quadratic() + raw = (u @ u.T).requires_grad_() + p = (raw + raw.T)/2 + pg = p @ g + s, t = g @ pg, torch.trace(p @ h) + expected = s - .03/2*((1+1/n)*(pg @ h @ pg) + s*t/n) + if mu: + ph = p @ h + expected -= .03*mu**2/(8*n)*(t**3 + 6*t*torch.trace(ph@ph) + 8*torch.trace(ph@ph@ph)) + derivative, = torch.autograd.grad(expected, raw) + value, actual = curvature_descent_reference(g, h, p.detach(), .03, n, mu) + torch.testing.assert_close(value, expected.detach(), rtol=1e-12, atol=1e-12) + torch.testing.assert_close(actual, derivative, rtol=1e-12, atol=1e-12) + + +def expected_next_loss(g, k, u, lr, n, mu): + # Degree-six Gaussian integrals are exact with four Hermite nodes per axis. + nodes, weights = np.polynomial.hermite.hermgauss(4) + nodes = nodes * np.sqrt(2) + weights = weights / np.sqrt(np.pi) + total = 0. + for indices in itertools.product(range(4), repeat=u.shape[1]*n): + z = torch.tensor(nodes[list(indices)], dtype=torch.float64).reshape(n, -1) + directions = z @ u.T + responses = directions @ g + mu/2*torch.einsum('bi,ij,bj->b', directions, k, directions) + update = -lr*(responses[:, None]*directions).mean(0) + loss = g @ update + (update @ k @ update)/2 + total += float(loss)*float(np.prod(weights[list(indices)])) + return total + + +@pytest.mark.parametrize('n', [1, 2]) +@pytest.mark.parametrize('mu', [0., .07]) +def test_gaussian_descent_exact_on_quadratics(n, mu): + g, h, u = quadratic() + value, _ = curvature_descent_reference(g, h, u @ u.T, .03, n, mu) + actual = expected_next_loss(g, h, u, .03, n, mu) + assert actual == pytest.approx(-.03*float(value), abs=1e-12) + + +def test_known_quadratic_upper_bound_gives_inequality(): + g, k, u = quadratic() + h = k + torch.eye(3, dtype=torch.float64)*2 + value, _ = curvature_descent_reference(g, h, u @ u.T, .03, 2) + assert expected_next_loss(g, k, u, .03, 2, 0.) <= -.03*float(value)+1e-12 + + +def test_ideal_formula_cannot_ignore_nonzero_single_sided_radius(): + g = torch.zeros(1, dtype=torch.float64) + h = p = torch.ones(1, 1, dtype=torch.float64) + ideal, _ = curvature_descent_reference(g, h, p, .1) + corrected, _ = curvature_descent_reference(g, h, p, .1, quadratic_mu=.2) + actual = expected_next_loss(g, h, p, .1, 1, .2) + assert ideal == 0 and actual > 0 + assert actual == pytest.approx(15*.1**2*.2**2/8, abs=1e-14) + assert actual == pytest.approx(-.1*float(corrected), abs=1e-14) + + +def test_structured_input_gradient_with_auxiliary_and_cross_blocks(): + generator = torch.Generator().manual_seed(17) + d = torch.nn.functional.normalize(torch.randn(3, generator=generator, dtype=torch.float64), dim=0) + x = torch.randn(7, 7, generator=generator, dtype=torch.float64) + h = x.T @ x + g = torch.randn(7, generator=generator, dtype=torch.float64) + def objective(v): + local = torch.kron(torch.eye(2, dtype=torch.float64), torch.outer(v, v)) + p = torch.block_diag(local, torch.ones(1, 1, dtype=torch.float64)) + return curvature_descent_reference(g, h, p, .001, quadratic_mu=.03) + _, m = objective(d) + tangent = curvature_input_gradient_reference(m[:6, :6], d, 2) + v = torch.randn(3, generator=generator, dtype=torch.float64) + v -= d*(d @ v) + eps = 1e-6 + normalize = lambda q: torch.nn.functional.normalize(q, dim=0) + fd = (objective(normalize(d+eps*v))[0]-objective(normalize(d-eps*v))[0])/(2*eps) + torch.testing.assert_close(tangent @ v, fd, rtol=1e-7, atol=1e-8) + assert abs(float(d @ tangent)) < 1e-12 + new = normalize(d+1e-5*tangent) + assert objective(new)[0] > objective(d)[0] + torch.testing.assert_close(new.norm(), torch.ones((), dtype=torch.float64)) + # Multiplying the objective gradient by two must double the basis gradient. + doubled = curvature_input_gradient_reference(2*m[:6, :6], d, 2) + torch.testing.assert_close(doubled, 2*tangent) + + +def estimator_moments(observed_gradient, h, u, n, mu): + nodes, weights = np.polynomial.hermite.hermgauss(4) + nodes, weights = nodes*np.sqrt(2), weights/np.sqrt(np.pi) + mean = torch.zeros_like(observed_gradient) + curvature = 0. + for ids in itertools.product(range(4), repeat=u.shape[1]*n): + z = torch.tensor(nodes[list(ids)], dtype=torch.float64).reshape(n, -1) + directions = z @ u.T + response = directions @ observed_gradient + mu/2*torch.einsum('bi,ij,bj->b', directions, h, directions) + estimate = (response[:, None]*directions).mean(0) + weight = float(np.prod(weights[list(ids)])) + mean += weight*estimate + curvature += weight*float(estimate @ h @ estimate) + return mean, curvature + + +@pytest.mark.parametrize('n', [1, 2]) +def test_independent_batch_covariance_and_single_sided_error_bounds(n): + g, h, u = quadratic() + p = u @ u.T + noise = torch.tensor([.3, -.1, .4], dtype=torch.float64) + covariance = torch.outer(noise, noise) + s, trace = g @ p @ g, torch.trace(p @ h) + l_u = torch.linalg.eigvalsh(u.T @ h @ u).max() + noise_cost = (1+1/n)*torch.trace(p @ h @ p @ covariance) + trace/n*torch.trace(p @ covariance) + ideal_c = (1+1/n)*(g @ p @ h @ p @ g) + s*trace/n + mean0, c0 = estimator_moments(g+noise, h, u, n, 0.) + mean1, c1 = estimator_moments(g-noise, h, u, n, 0.) + torch.testing.assert_close((mean0+mean1)/2, p @ g) + assert (c0+c1)/2 == pytest.approx(float(ideal_c+noise_cost), abs=1e-10) + mu = .07 + mean0, c0 = estimator_moments(g+noise, h, u, n, mu) + mean1, c1 = estimator_moments(g-noise, h, u, n, mu) + k = u.shape[1] + l_f = torch.linalg.eigvalsh(h).max() + b_mu = l_f**2*mu**2/4*k*(k+2)*(k+4) + actual_alignment = g @ ((mean0+mean1)/2) + assert actual_alignment >= s/2-b_mu/2-1e-12 + bound = 2*((1+1/n)*l_u+trace/n)*s + 2*noise_cost + 2*l_u*b_mu + assert (c0+c1)/2 <= bound+1e-10 + + +def test_independent_direction_noise_does_not_remove_batch_selection_coupling(): + batches = torch.eye(2, dtype=torch.float64) + projections = [torch.diag(row) for row in batches] + g = batches.mean(0) + average_p = sum(projections)/2 + expected_update = sum(p @ b for p, b in zip(projections, batches))/2 + coupling = sum((p-average_p) @ (b-g) for p, b in zip(projections, batches))/2 + torch.testing.assert_close(expected_update, average_p @ g + coupling) + assert coupling.norm() > 0 + assert not torch.allclose(expected_update, average_p @ g) + + +@pytest.mark.parametrize('n', [1, 2]) +def test_nonquadratic_single_sided_bias_and_error_bounds(n): + # F(x)=sin(x), theta=0: g=1, L_f=H=P=1 globally. + # E[z sin(mu*z)/mu] = exp(-mu^2/2), so the observation bias is nonzero. + mu = .4 + nodes, weights = np.polynomial.hermite.hermgauss(48) + z, weights = nodes*np.sqrt(2), weights/np.sqrt(np.pi) + ideal = z**2 + observed = z*np.sin(mu*z)/mu + error = observed-ideal + mean = float(weights @ observed) + mean_error = float(weights @ error) + assert mean == pytest.approx(np.exp(-mu**2/2), abs=1e-13) + assert mean_error == pytest.approx(mean-1, abs=1e-13) + assert mean_error < 0 + + # Average n independent directions; retain the off-diagonal mean products. + error_second = float(weights @ error**2)/n + (1-1/n)*mean_error**2 + curvature = float(weights @ observed**2)/n + (1-1/n)*mean**2 + cross = float(weights @ (ideal*error))/n + (1-1/n)*mean_error + ideal_curvature = 1+2/n + assert abs(cross) > 1e-3 + assert curvature == pytest.approx(ideal_curvature+2*cross+error_second, abs=1e-12) + b_mu = 15*mu**2/4 + assert error_second <= b_mu + assert mean >= 1/2-b_mu/2 + assert curvature <= 2*ideal_curvature+2*b_mu + + +def test_isotropic_curvature_is_a_declared_exact_special_case(): + g, _, u = quadratic() + p = u @ u.T + h = 5*torch.eye(3, dtype=torch.float64) + for n in [1, 2]: + value, _ = curvature_descent_reference(g, h, p, .001, n) + coefficient = 1-.001*5/2*(1+(u.shape[1]+1)/n) + assert coefficient > 0 + torch.testing.assert_close(value, (g @ p @ g)*coefficient) + + +def gaussian_rule(dimension, order): + nodes, weights = np.polynomial.hermite.hermgauss(order) + ids = np.array(list(itertools.product(range(order), repeat=dimension))) + return np.sqrt(2)*nodes[ids], np.prod(weights[ids]/np.sqrt(np.pi), axis=1) + + +def forward_score_pair(losses, directions, mu, lr, smoothness): + """Section 6.3, on tiny test objectives at theta=0; no derivative oracle.""" + clean_c = losses[2](np.zeros_like(directions[0])) + scores = [] + for direction in directions: + a, b = [(loss(mu*direction)-loss(-mu*direction))/(2*mu) for loss in losses[:2]] + c = (losses[2](mu*direction)-2*clean_c+losses[2](-mu*direction))/mu**2 + scores.append(a*b*(1-lr/2*(c+2*smoothness*(direction @ direction)))) + return np.array(scores) + + +def test_independent_forward_products_match_full_anisotropic_descent(): + g, k, u = quadratic() + v = torch.linalg.qr(torch.tensor([[1., 2.], [-1., 3.], [.3, -.5]], dtype=torch.float64)).Q + smoothness = float(torch.linalg.eigvalsh(k).max()) + h = k+2*smoothness*torch.eye(3, dtype=torch.float64) + # The stated certificate is global for these quadratic objectives. + assert torch.linalg.eigvalsh(h-k).min() > 0 + assert torch.linalg.eigvalsh(h).min() >= smoothness + z, weights = gaussian_rule(2, 4) + grad_noise = np.array([.3, -.1, .4]) + hess_noise = np.diag([.2, -.1, .3]) + average = np.zeros(2) + calls = [0, 0, 0] + for signs in itertools.product([-1., 1.], repeat=3): + losses = [] + for index in range(3): + gradient = g.numpy()+signs[index]*grad_noise + curvature = k.numpy()+(signs[index]*hess_noise if index == 2 else 0.) + def loss(x, index=index, gradient=gradient, curvature=curvature): + calls[index] += 1 + return gradient @ x+x @ curvature @ x/2 + losses.append(loss) + for noise, weight in zip(z, weights): + before = sum(calls) + scores = forward_score_pair(losses, [u.numpy() @ noise, v.numpy() @ noise], .05, .003, smoothness) + assert sum(calls)-before == 13 + average += weight*scores/8 + expected = [float(curvature_descent_reference(g, h, basis @ basis.T, .003)[0]) for basis in [u, v]] + np.testing.assert_allclose(average, expected, rtol=1e-11, atol=1e-12) + assert calls[0] == calls[1] and calls[2]*4 == calls[0]*5 + # Same-batch squaring has a nonzero extra quadratic-gradient contribution. + noise_term, _ = curvature_descent_reference(torch.tensor(grad_noise), h, u @ u.T, .003) + assert abs(float(noise_term)) > 1e-3 + + +def test_joint_basis_two_point_mean_converges_to_structured_gradient(): + generator = torch.Generator().manual_seed(130) + g = torch.randn(7, generator=generator, dtype=torch.float64) + x = torch.randn(7, 7, generator=generator, dtype=torch.float64) + k = x.T @ x + h = k+2*torch.linalg.eigvalsh(k).max()*torch.eye(7, dtype=torch.float64) + angles = np.array([.3, -.7]) + d = np.stack([np.cos(angles), np.sin(angles)], axis=1) + tangent = np.stack([-np.sin(angles), np.cos(angles)], axis=1) + def basis(v): + result = np.zeros((7, 4)) + result[:2, 0], result[2:4, 1], result[4:6, 2], result[6, 3] = v[0], v[0], v[1], 1. + return result + p = torch.tensor(basis(d) @ basis(d).T) + _, m = curvature_descent_reference(g, h, p, .001) + true_gradient = np.array([ + float(curvature_input_gradient_reference(m[:4, :4], torch.tensor(d[0]), 2) @ torch.tensor(tangent[0])), + float(curvature_input_gradient_reference(m[4:6, 4:6], torch.tensor(d[1]), 1) @ torch.tensor(tangent[1])), + ]) + z, weights = gaussian_rule(4, 4) + def score(v): + directions = z @ basis(v).T + a = directions @ g.numpy() + c = np.einsum('bi,ij,bj->b', directions, h.numpy(), directions) + return float(weights @ (a**2*(1-.001*c/2))) + outer, outer_weights = gaussian_rule(2, 16) + errors = [] + for delta in [.02, .01, .005]: + mean = np.zeros(2) + for v, weight in zip(outer, outer_weights): + plus = d+delta*v[:, None]*tangent + minus = d-delta*v[:, None]*tangent + plus /= np.linalg.norm(plus, axis=1, keepdims=True) + minus /= np.linalg.norm(minus, axis=1, keepdims=True) + mean += weight*(score(plus)-score(minus))/(2*delta)*v + errors.append(np.linalg.norm(mean-true_gradient)) + assert np.linalg.norm(true_gradient) > .01 + assert errors[1] < .3*errors[0] + assert errors[2] < .3*errors[1] + + +def test_nonquadratic_forward_score_has_controlled_finite_radius_bias(): + # F(theta+x)=sin(theta+x), known global L=M3=M4=1, H=2-sin(theta). + theta, lr = .4, .01 + g, h = np.cos(theta), 2-np.sin(theta) + z, weights = gaussian_rule(1, 48) + exact = g**2*(1-3*lr*h/2) + loss = lambda x: float(np.sin(theta+x[0])) + errors = [] + for mu in [.08, .04, .02]: + mean = 0. + for direction, weight in zip(z, weights): + score = forward_score_pair([loss]*3, [direction, -direction], mu, lr, 1.)[0] + radius = abs(float(direction[0])) + a, curvature = g*direction[0], h*radius**2 + b_bound, e_bound = mu**2*radius**3/6, mu**2*radius**4/12 + bound = abs(1-lr*curvature/2)*(2*abs(a)*b_bound+b_bound**2)+lr/2*e_bound*(abs(a)+b_bound)**2 + assert abs(score-a*a*(1-lr*curvature/2)) <= bound+1e-10 + mean += weight*score + errors.append(abs(mean-exact)) + assert errors[1] < .3*errors[0] + assert errors[2] < .3*errors[1] + + +def test_valid_upper_bounds_can_reverse_basis_ranking(): + k = torch.diag(torch.tensor([100., 1.], dtype=torch.float64)) + g = torch.tensor([np.sqrt(1.1), 1.], dtype=torch.float64) + p0 = torch.diag(torch.tensor([0., 1.], dtype=torch.float64)) + p1 = torch.eye(2, dtype=torch.float64)-p0 + scores = [] + for shift in [0., 500.]: + h = k+shift*torch.eye(2, dtype=torch.float64) + assert .0005 <= 1/(3*float(torch.linalg.eigvalsh(h).max())) + scores.append([float(curvature_descent_reference(g, h, p, .0005)[0]) for p in [p0, p1]]) + np.testing.assert_allclose(scores, [[.99925, 1.0175], [.62425, .605]], atol=1e-12) + assert scores[0][1] > scores[0][0] and scores[1][1] < scores[1][0] + + +def test_final_layernorm_global_option_loss_envelope(): + gen = torch.Generator().manual_seed(591) + h, vocab = 4, 7 + w = torch.randn(vocab, h, generator=gen, dtype=torch.float64) + gamma = torch.randn(h, generator=gen, dtype=torch.float64) + beta = torch.randn(h, generator=gen, dtype=torch.float64) + a = w.norm(dim=1).max() + t = np.sqrt(h)*gamma.abs().max()+beta.norm() + c = np.sqrt(h)+1 + a0 = np.log(2)+np.log(vocab)+2*a*t + a1, a2 = 2*(a*c+t), 2*c + for radius in [.001, .1, 1., 10.]: + change = torch.randn(vocab*h+2*h, generator=gen, dtype=torch.float64) + change *= radius/change.norm() + dw, dg, db = change[:vocab*h].reshape_as(w), change[vocab*h:-h], change[-h:] + # Arbitrary internal activations; their norms need not be bounded. + activations = torch.randn(2, 3, h, generator=gen, dtype=torch.float64)*1000 + hidden = torch.nn.functional.layer_norm(activations, (h,), gamma+dg, beta+db) + logits = hidden @ (w+dw).T + labels = torch.tensor([[0, 1, 2], [3, 4, 5]]) + option_scores = logits.log_softmax(-1).gather(-1, labels[..., None]).mean(1).squeeze(-1) + loss = torch.nn.functional.cross_entropy(option_scores[None], torch.tensor([0])) + assert logits.abs().max() <= (a+radius)*(t+c*radius)+1e-10 + assert loss <= a0+a1*radius+a2*radius**2 + + +def test_local_certificate_and_growth_envelope_patch_global_upper_bound(): + # F(x)=1+sin(x): nonnegative, globally <=2; local ell=G=kappa=1. + theta, radius = .3, .7 + ell = gradient_bound = kappa = 1. + a0, a1, a2 = 2., 0., 0. + q = max(ell, 2*a2+2*(a1+gradient_bound)/radius+2*a0/radius**2) + k = -np.sin(theta) + anisotropic_upper = k+q+kappa + assert anisotropic_upper >= q + delta = np.concatenate([np.linspace(-20, 20, 1001), [-radius, radius, -1e-5, 1e-5]]) + remainder = np.sin(theta+delta)-np.sin(theta)-np.cos(theta)*delta + assert np.all(remainder <= q*delta**2/2+1e-12) diff --git a/tests/test_history_free_coverage.py b/tests/test_history_free_coverage.py new file mode 100644 index 0000000..620aa15 --- /dev/null +++ b/tests/test_history_free_coverage.py @@ -0,0 +1,178 @@ +"""Actual forward queries versus exact Gaussian/sign quadrature; no training.""" +import itertools +from unittest.mock import patch + +import numpy as np +import pytest +import torch + +from test_mezo_refactor import make_trainer +from methods.large_models.trainer import seed_for + + +@torch.enable_grad() +def fixture(power=1): + model = torch.nn.ModuleDict({n: torch.nn.Linear(2, 1, bias=False, dtype=torch.float64) + for n in ('left', 'right')}) + with torch.no_grad(): + model['left'].weight.copy_(torch.tensor([[.3, -.2]])) + model['right'].weight.copy_(torch.tensor([[-.1, .4]])) + x = torch.tensor([[[1., .3], [-.4, .8]]], dtype=torch.float64) + c = torch.tensor([[[.7], [-.2]]], dtype=torch.float64) + def forward(batch): + t = (model['left'](x)*c + model['right'](x)*(1-c)).sum()/2 + loss = t if power == 1 else (t.square()/2 if power == 2 else t.square()/2+.1*t**3+.02*t**4) + return loss, t + engine = make_trainer(model, forward) + engine.basis = {'left.weight': torch.tensor([[.6], [.8]], dtype=torch.float64), + 'right.weight': torch.tensor([[-.8], [.6]], dtype=torch.float64)} + engine.history = {} # No EMA is needed. + loss = forward({})[0] + gs = torch.autograd.grad(loss, list(model.parameters())) + truth = {} + for (n, d), g in zip(engine.basis.items(), gs): + v = 2*g.T @ g @ d + truth[n] = v-d*(d*v).sum() + return engine, truth + + +def quadrature(power=1, mu=.04, eps=.06, targets=None): + """Order 4 integrates all moments of the quartic response product exactly.""" + engine, truth = fixture(power) + engine.args.zo_eps, engine.args.node_epsilon = mu, eps + names = list(engine.basis) + chosen = names if targets is None else targets + nodes, weights = np.polynomial.hermite.hermgauss(4) + nodes, weights = nodes*np.sqrt(2), weights/np.sqrt(np.pi) + mean = {n: torch.zeros_like(engine.basis[n]) for n in chosen} + second = {n: torch.zeros(2, 2, dtype=torch.float64) for n in chosen} + max_tangent = 0. + before = {n: p.detach().clone() for n, p in engine.named_parameters} + for indices in itertools.product(range(4), repeat=2): + zs = [nodes[i] for i in indices] + weight = float(np.prod([weights[i] for i in indices]))/16 + engine.directions = lambda seed: iter((n, engine.parameter_map[n], + torch.tensor([[z]], dtype=torch.float64)) for n, z in zip(names, zs)) + for signs in itertools.product((0, 1), repeat=4): + patterns = {seed_for(123, j): torch.tensor(signs[2*j:2*j+2]).reshape(1, 2) + for j in range(2)} + def draw(low, high, size, *, device, generator): + return patterns[generator.initial_seed()].to(device) + engine._estimate = None + with patch('torch.randint', draw): + result = engine.coverage_gradient_probe({}, 5, 123, chosen) + assert result['cost'] == 3 + for n, v in result['gradients'].items(): + mean[n] += weight*v + second[n] += weight*torch.outer(v.flatten(), v.flatten()) + max_tangent = max(max_tangent, abs(float((v*engine.basis[n]).sum()))) + for n, p in engine.named_parameters: + torch.testing.assert_close(p, before[n], atol=2e-13, rtol=0) + covariance = {n: second[n]-torch.outer(mean[n].flatten(), mean[n].flatten()) for n in chosen} + return dict(mean=mean, truth=truth, covariance=covariance, + max_error=max(float((mean[n]-truth[n]).abs().max()) for n in chosen), + max_tangent=max_tangent, forwards=engine.counts['training']) + + +@pytest.mark.parametrize('power', [1, 2]) +def test_exact_linear_and_quadratic_means(power): + result = quadrature(power) + assert result['max_error'] < 1e-11 + assert result['max_tangent'] < 1e-12 + assert result['forwards'] == 768 + + +def test_smooth_finite_difference_bias_is_second_order(): + # Vary each radius separately; extrapolate the other radius to zero. + for varying in ('mu', 'eps'): + errors = [] + for radius in (.08, .04, .02): + kwargs = dict(mu=1e-5, eps=1e-5) + kwargs[varying] = radius + errors.append(quadrature(4, **kwargs)['max_error']) + assert 3.8 < errors[0]/errors[1] < 4.2 + assert 3.8 < errors[1]/errors[2] < 4.2 + + +@torch.no_grad() +def test_probe_reuses_exact_old_basis_training_update_and_rng(): + engine, _ = fixture(4) + reference, _ = fixture(4) + rng = torch.random.get_rng_state() + old = {n: d.clone() for n, d in engine.basis.items()} + result = engine.coverage_gradient_probe({}, 41, 123, list(old)) + assert result['cost'] == 3 + reference.zo_step(reference.model, {}, 41) + assert result['response'] == reference._estimate['slope'] + with torch.no_grad(): + engine.zo_update(engine.model) + reference.zo_update(reference.model) + for (_, p), (_, q) in zip(engine.named_parameters, reference.named_parameters): + torch.testing.assert_close(p, q, atol=1e-14, rtol=0) + for n in old: + assert torch.equal(old[n], engine.basis[n]) + assert torch.equal(rng, torch.random.get_rng_state()) + assert all(not m._forward_hooks for m in engine.model.modules()) + + +def test_joint_covariance_penalty_matches_closed_form(): + joint = quadrature() + engine, _ = fixture() + x = torch.tensor([[1., .3], [-.4, .8]], dtype=torch.float64) + sensitivities = [torch.tensor([[.7], [-.2]], dtype=torch.float64)/2, + torch.tensor([[.3], [1.2]], dtype=torch.float64)/2] + names = list(engine.basis) + gs = [a.T @ x for a in sensitivities] + coefficients = [g @ engine.basis[n] for n, g in zip(names, gs)] + norm_a = sum(float(a.square().sum()) for a in coefficients) + for i, n in enumerate(names): + separate = quadrature(targets=[n]) + d = engine.basis[n] + pi = torch.eye(2, dtype=d.dtype)-d @ d.T + j = 1-i + factor = norm_a*float(sensitivities[j].square().sum()) + 2*float( + (sensitivities[j] @ coefficients[j]).square().sum()) + expected = 4*factor*pi @ x.T @ x @ pi + observed = joint['covariance'][n]-separate['covariance'][n] + torch.testing.assert_close(observed, expected, atol=1e-11, rtol=1e-10) + + +def test_failed_node_query_removes_hooks_and_leaves_no_pending_update(): + engine, _ = fixture() + forward = engine._forward_outputs + calls = 0 + def fail(batch): + nonlocal calls + calls += 1 + if calls == 3: + raise RuntimeError('node failed') + return forward(batch) + engine._forward_outputs = fail + with pytest.raises(RuntimeError, match='node failed'): + engine.coverage_gradient_probe({}, 41, 123, list(engine.basis)) + assert getattr(engine, '_estimate', None) is None + assert all(not m._forward_hooks for m in engine.model.modules()) + + +@torch.no_grad() +def test_downstream_sketch_uses_clean_inputs(): + model = torch.nn.Sequential(torch.nn.Linear(2, 2, bias=False, dtype=torch.float64), + torch.nn.Linear(2, 1, bias=False, dtype=torch.float64)) + model[0].weight.copy_(torch.tensor([[.2, .4], [-.3, .5]])) + model[1].weight.copy_(torch.tensor([[.7, -.2]])) + x = torch.tensor([[[1., 2.], [.3, -.1]]], dtype=torch.float64) + engine = make_trainer(model, lambda batch: (model(x).square().mean(), None)) + engine.basis = {n: torch.tensor([[1.], [0.]], dtype=torch.float64) + for n in engine.linear_map} + v_clean = model[0](x).sum((0, 1))[:, None] + with patch('torch.randint', lambda low, high, size, **kwargs: + torch.ones(size, dtype=torch.long, device=kwargs['device'])): + result = engine.coverage_gradient_probe({}, 41, 123, list(engine.basis)) + d = engine.basis['1.weight'] + factor = 2*result['response']*result['node_response'] + expected = factor*(v_clean-d*(d*v_clean).sum()) + torch.testing.assert_close(result['gradients']['1.weight'], expected) + z0 = next(z for n, _, z in engine.directions(41) if n == '0.weight') + wrong_v = v_clean+2*engine.args.node_epsilon*z0 + wrong = factor*(wrong_v-d*(d*wrong_v).sum()) + assert float((wrong-expected).norm()) > 1e-8 diff --git a/tests/test_history_free_steps.py b/tests/test_history_free_steps.py new file mode 100644 index 0000000..1ddccc3 --- /dev/null +++ b/tests/test_history_free_steps.py @@ -0,0 +1,42 @@ +"""Full step: actual old-basis SGD, magnitude-preserving basis retraction, budgets.""" +import pytest +import torch +from test_history_free_coverage import fixture + + +@torch.no_grad() +def test_full_step_matches_derived_retraction_and_old_basis_sgd(): + engine, _ = fixture(4) + reference, _ = fixture(4) + engine.args.basis_lr = reference.args.basis_lr = .003 + from methods.large_models.trainer import seed_for + probe = reference.coverage_gradient_probe({}, 41, seed_for(42, 1801, 1), list(reference.basis)) + expected = {n: torch.nn.functional.normalize(d+.003*probe['gradients'][n], dim=0) + for n, d in reference.basis.items()} + reference.zo_update(reference.model) + _, event = engine.coverage_step({}, 41) + assert event['cost'] == 1 and event['total_step_cost'] == 3 + assert event['variant'] == 'history_free_coverage_gradient_v1' + for (_, p), (_, q) in zip(engine.named_parameters, reference.named_parameters): + torch.testing.assert_close(p, q, atol=1e-14, rtol=0) + for n in expected: + torch.testing.assert_close(engine.basis[n], expected[n], atol=1e-14, rtol=0) + assert engine._estimate is None and engine.history == {} + + +@pytest.mark.parametrize('remaining', [2, 3]) +@torch.no_grad() +def test_refresh_reserves_three_queries(remaining): + engine, _ = fixture() + engine.args.basis_lr = .003 + engine.args.main_forward_budget = remaining + _, event = engine.coverage_step({}, 41) + assert engine.used() == remaining + assert (event is not None) == (remaining == 3) + + +def test_cli_selects_explicit_history_free_variant(tmp_path): + from methods.large_models.run import parse_args + args = parse_args(['--trainer', 'node', '--node_update', 'history_free', + '--output_dir', str(tmp_path)]) + assert args.node_update == 'history_free' diff --git a/tests/test_mechanisms.py b/tests/test_mechanisms.py new file mode 100644 index 0000000..34af6f3 --- /dev/null +++ b/tests/test_mechanisms.py @@ -0,0 +1,50 @@ +"""Small numerical checks, not pretrained-model performance evidence.""" +from types import SimpleNamespace +import copy +import torch +from transformers import OPTConfig,OPTForCausalLM +from experiments_codebase.task import Task,top_basis + +def tiny(): + torch.manual_seed(42) + t=Task.__new__(Task);t.device=torch.device('cpu') + t.args=SimpleNamespace(task='sst2',mu=.001,history_beta=.9,node_queries=2,node_epsilon=.001) + t.model=OPTForCausalLM(OPTConfig(vocab_size=32,hidden_size=16,ffn_dim=24,num_hidden_layers=3,num_attention_heads=2,max_position_embeddings=32,dropout=0,attention_dropout=0)).eval() + t.named_parameters=list(t.model.named_parameters());t.parameter_map=dict(t.named_parameters);t.parameters=list(t.parameter_map.values()) + t.linear_map={n+'.weight':m for n,m in t.model.named_modules() if isinstance(m,torch.nn.Linear) and n+'.weight' in t.parameter_map} + t.label_ids=[5,7];t.counts=dict(training=0,calibration=0,evaluation=0,diagnostic=0) + t.structured={};t.noise=None;t.handles=[];t.history={} + inputs=dict(input_ids=torch.tensor([[2,4,6,3],[2,5,9,3]]),attention_mask=torch.ones(2,4,dtype=torch.long),labels=torch.tensor([0,1])) + return t,inputs + +@torch.no_grad() +def test_basis_restoration_and_switch(): + t,x=tiny();t.configure(x);clean=t.call(x,'diagnostic')[0].clone();old=t.dense_snapshot() + t.shifted(x,t.bases(),t.directions(91),.001,old) + assert all(torch.equal(t.parameter_map[n],v) for n,v in old.items()) + torch.testing.assert_close(clean,t.call(x,'diagnostic')[0],rtol=0,atol=0) + t.update(x,33,1e-5);before=t.call(x,'diagnostic')[0].clone() + t.switch({n:-d for n,d in t.bases().items()}) + torch.testing.assert_close(before,t.call(x,'diagnostic')[0],rtol=0,atol=0) + t.close() + +@torch.no_grad() +def test_same_basis_probe_has_zero_gain_and_five_queries(): + t,x=tiny();t.configure(x);before=t.counts['training'];old=[p.clone() for p in t.parameters] + event=t.probe(x,x,t.bases(),17,1e-5) + assert event['gain']==0 and t.counts['training']-before==5 + assert all(torch.equal(p,v) for p,v in zip(t.parameters,old));t.close() + +@torch.no_grad() +def test_node_refresh_preserves_function_and_charges_seven_queries(): + t,x=tiny();t.configure(x);t.configure_history();t.update(x,18,1e-5) + before=t.call(x,'diagnostic')[0].clone();q=t.counts['training'];event=t.node_refresh(x,19) + assert t.counts['training']-q==7 + assert len(event)==3 + torch.testing.assert_close(before,t.call(x,'diagnostic')[0],rtol=0,atol=0);t.close() + +def test_pca_order_and_orthogonality(): + x=torch.tensor([[9.,0,0,0],[0,2.,0,0],[0,0,1.,0]]) + d=top_basis(x,2) + torch.testing.assert_close(d.T@d,torch.eye(2)) + assert abs(float(d[0,0]))>.9999 and abs(float(d[1,1]))>.9999 diff --git a/tests/test_mezo_refactor.py b/tests/test_mezo_refactor.py new file mode 100644 index 0000000..3580fb8 --- /dev/null +++ b/tests/test_mezo_refactor.py @@ -0,0 +1,226 @@ +"""Direct-weight SGD, in-place inverse restoration, and MeZO integration checks.""" +import ast +import copy +import math +from pathlib import Path +from types import SimpleNamespace +import pytest +import torch +from methods.large_models.trainer import OurTrainer, seed_for + + +def make_trainer(model, forward_loss, mu=.03, task='DROP'): + trainer = OurTrainer.__new__(OurTrainer) + trainer.model = model + trainer.args = SimpleNamespace(zo_eps=mu, task_name=task, history_beta=.9, + node_queries=2, node_epsilon=.001, refresh_every=1, + main_forward_budget=100000, seed=42, device=next(model.parameters()).device) + trainer._forward_outputs = forward_loss + trainer.init_zo() + trainer.current_lr = .01 + trainer.state = SimpleNamespace(global_step=1) + return trainer + + +def algorithm(trainer, mu=.03, task='DROP'): + trainer.args.zo_eps = mu + trainer.args.task_name = task + return trainer + + +@torch.no_grad() +def test_direct_weight_steps_match_explicit_coefficient_representation(): + """同一批方向/响应下,换基前后的直接W更新等于W0+C+B D.T。""" + model = torch.nn.Linear(2, 2, bias=True, dtype=torch.float64) + model.weight.copy_(torch.tensor([[.2, -.1], [.4, .3]])) + x = torch.tensor([[1., 2.]], dtype=torch.float64) + model = torch.nn.Sequential(model) + trainer = make_trainer(model, lambda batch: (model(x).square().mean(), model(x))) + name = '0.weight' + trainer.basis = {name: torch.tensor([[1.], [0.]], dtype=torch.float64)} + initial = model[0].weight.clone();offset = torch.zeros_like(initial) + coefficient = torch.zeros(2, 1, dtype=torch.float64) + reference_bias = model[0].bias.clone() + for step in range(4): + if step == 2: + offset += coefficient @ trainer.basis[name].T + coefficient.zero_() + before = model[0].weight.clone() + trainer.basis[name] = torch.tensor([[0.], [1.]], dtype=torch.float64) + assert torch.equal(before, model[0].weight) + trainer.zo_step(model, {}, 100+step) + estimate = trainer._estimate + noise = {n: z for n, _, z in trainer.directions(estimate['seed'])} + g = noise[name] * estimate['slope'] + coefficient.add_(g, alpha=-trainer.current_lr) + reference_bias.add_(noise['0.bias'] * estimate['slope'], alpha=-trainer.current_lr) + trainer.zo_update(model) + torch.testing.assert_close(model[0].weight, initial+offset+coefficient@trainer.basis[name].T, + rtol=1e-12, atol=1e-12) + torch.testing.assert_close(model[0].bias, reference_bias, rtol=1e-12, atol=1e-12) + assert trainer.counts['training'] == 8 + + +@torch.no_grad() +def test_tied_parameters_are_updated_once_and_remain_tied(): + from transformers import OPTConfig, OPTForCausalLM + model = OPTForCausalLM(OPTConfig(vocab_size=16, hidden_size=8, ffn_dim=16, + num_hidden_layers=1, num_attention_heads=2, max_position_embeddings=16)) + trainer = make_trainer(model, lambda inputs: None) + embedding = model.get_input_embeddings().weight + assert embedding is model.get_output_embeddings().weight + assert sum(p is embedding for _, p in trainer.named_parameters) == 1 + before = embedding.clone() + z = {name: direction for name, _, direction in trainer.directions(9)} + name = next(name for name, p in trainer.named_parameters if p is embedding) + expected = before.clone().add_(z[name]*2, alpha=-trainer.current_lr) + trainer._estimate = dict(seed=9, slope=2., clean=torch.tensor(1.)) + trainer.zo_update(model) + assert torch.equal(embedding, expected) + assert embedding is model.get_output_embeddings().weight + + +@torch.no_grad() +def test_shifted_restores_all_weights_even_when_forward_raises(): + model = torch.nn.Sequential(torch.nn.Linear(2, 1)) + trainer = make_trainer(model, lambda inputs: (_ for _ in ()).throw(RuntimeError('query failed'))) + trainer.basis = {'0.weight': torch.tensor([[1.], [0.]])} + old = {name: p.clone() for name, p in trainer.named_parameters} + with pytest.raises(RuntimeError, match='query failed'): + trainer.shifted({}, trainer.basis, 1, .01) + for name, p in trainer.named_parameters: + torch.testing.assert_close(p, old[name], rtol=1e-6, atol=1e-7) + assert trainer.counts['training'] == 1 + + +@torch.no_grad() +def test_step_rebuilds_noise_without_parameter_clones(monkeypatch): + model = torch.nn.Sequential(torch.nn.Linear(2, 2, bias=False)) + x = torch.ones(1, 2) + trainer = make_trainer(model, lambda inputs: (model(x).square().mean(), model(x))) + trainer.basis = {'0.weight': torch.tensor([[1.], [0.]])} + clone = torch.Tensor.clone + def checked_clone(tensor, *args, **kwargs): + assert tensor.numel() == 1, 'Training cloned a parameter/noise tensor' + return clone(tensor, *args, **kwargs) + monkeypatch.setattr(torch.Tensor, 'clone', checked_clone) + trainer.fix_step({}, 7) + assert trainer._estimate is None + assert not hasattr(trainer, 'snapshot') + + +def test_direction_stream_repeats_without_changing_global_rng(): + model = torch.nn.Sequential(torch.nn.Linear(2, 2)) + trainer = make_trainer(model, lambda inputs: None) + trainer.basis = {'0.weight': torch.tensor([[1.], [0.]])} + before = torch.random.get_rng_state() + first = list(trainer.directions(123)) + second = list(trainer.directions(123)) + assert torch.equal(before, torch.random.get_rng_state()) + assert [name for name, _, _ in first] == [name for name, _, _ in second] + assert all(torch.equal(a[2], b[2]) for a, b in zip(first, second)) + + +@torch.no_grad() +def test_partial_perturbation_failure_restores_touched_parameters(): + model = torch.nn.Sequential(torch.nn.Linear(2, 2), torch.nn.Linear(2, 1)) + trainer = make_trainer(model, lambda inputs: None) + trainer.basis = {name: torch.tensor([[1.], [0.]]) for name in trainer.linear_map} + candidates = dict(trainer.basis, **{'1.weight': torch.ones(3, 1)}) + before = {name: p.clone() for name, p in trainer.named_parameters} + with pytest.raises(RuntimeError): + trainer.shifted({}, candidates, 7, .01) + for name, p in trainer.named_parameters: + torch.testing.assert_close(p, before[name], rtol=1e-6, atol=1e-7) + assert trainer.counts['training'] == 0 + + +@pytest.mark.parametrize('method', ['fix', 'adjust', 'node']) +@torch.no_grad() +def test_direct_steps_run_on_tiny_opt_with_actual_refreshes(method): + from transformers import OPTConfig, OPTForCausalLM + torch.manual_seed(12) + model = OPTForCausalLM(OPTConfig(vocab_size=16, hidden_size=8, ffn_dim=16, + num_hidden_layers=3, num_attention_heads=2, max_position_embeddings=16, + dropout=0., attention_dropout=0.)).eval() + inputs = dict(input_ids=torch.tensor([[2,3,4,5]]), + attention_mask=torch.ones(1,4,dtype=torch.long), + labels=torch.tensor([[2,3,4,5]])) + def forward(batch): + result = model(**batch) + # Match MeZOLoss's repeated scalar loss for the collated batch rows. + return result.loss.expand(len(batch['input_ids'])), result.logits + trainer = make_trainer(model, forward, mu=.01) + trainer.current_lr = 1e-5 + trainer.configure_basis(inputs) + if method == 'node':trainer.configure_history() + trainer.probe_batch = lambda: inputs + trainer.state.global_step = 0 + getattr(trainer, method+'_step')(inputs, 100) + assert trainer.counts['training'] == 2 + trainer.state.global_step = 1 + before = trainer.used() + result, event = getattr(trainer, method+'_step')(inputs, 101) + assert math.isfinite(result['batch_loss']) + assert all(bool(torch.isfinite(p).all()) for p in trainer.parameters) + assert trainer.counts['evaluation'] == 0 + if method == 'fix': + assert event is None and trainer.used()-before == 2 + else: + assert event is not None + assert trainer.used()-before == event['cost']+2 + assert all(not module._forward_hooks and not module._forward_pre_hooks + for module in model.modules()) + + +def test_actual_mezo_zo_forward_is_reused(): + import inspect + root=Path(__file__).resolve().parents[1] + tree=ast.parse((root/'baselines/mezo/large_models/trainer.py').read_text()) + cls=next(n for n in tree.body if isinstance(n,ast.ClassDef) and n.name=='OurTrainer') + original=next(n for n in cls.body if isinstance(n,ast.FunctionDef) and n.name=='zo_forward') + import textwrap + port=ast.parse(textwrap.dedent(inspect.getsource(OurTrainer.zo_forward))).body[0] + # inspect.getsource + dedent changes docstring indentation, not executable code. + assert inspect.cleandoc(ast.get_docstring(original))==inspect.cleandoc(ast.get_docstring(port)) + original.body=original.body[1:];port.body=port.body[1:] + assert ast.dump(original,include_attributes=False)==ast.dump(port,include_attributes=False) + +def test_aliases_default_to_mezo_and_explicit_legacy(tmp_path): + from methods.large_models.run import parse_args + args=parse_args(['--method','adjust','--task','sst2','--budget','45','--lr','2e-6','--refresh-every','2','--lr_scheduler_type','constant','--output_dir',str(tmp_path)]) + assert args.trainer=='adjust' and args.task_name=='SST2' and args.main_forward_budget==45 + assert args.learning_rate==2e-6 and args.refresh_every==2 and args.data_protocol=='mezo' and args.dataloader_drop_last is False + assert args.zo_schedule=='constant' and args.max_grad_norm==0 + legacy=parse_args(['--data_protocol','legacy','--output_dir',str(tmp_path)]) + assert legacy.data_protocol=='legacy' and legacy.dataloader_drop_last is True + native=parse_args(['--trainer','node','--task_name','DROP','--data_protocol','mezo','--output_dir',str(tmp_path)]) + assert native.data_protocol=='mezo' and native.train_as_classification is False and native.zo_schedule=='cosine' + +def test_incompatible_native_and_structured_controls_fail_explicitly(tmp_path): + from methods.large_models.run import parse_args + with pytest.raises(ValueError,match='consistent'): + parse_args(['--output_dir',str(tmp_path),'--schedule','constant','--lr_scheduler_type','cosine']) + with pytest.raises(ValueError,match='clipping'): + parse_args(['--output_dir',str(tmp_path),'--max_grad_norm','1']) + + +@pytest.mark.parametrize('method', ['fix','adjust','node']) +@pytest.mark.parametrize('task', ['SST2','DROP']) +def test_all_methods_default_to_author_data_protocol(tmp_path,method,task): + from methods.large_models.run import parse_args + args=parse_args(['--trainer',method,'--task_name',task,'--output_dir',str(tmp_path)]) + assert args.data_protocol=='mezo' and args.dataloader_drop_last is False + assert args.only_train_option and args.train_as_classification==(task=='SST2') + + +def test_author_sampler_and_legacy_sampler_are_separate(): + from torch.utils.data import RandomSampler + from methods.large_models.data import ProtocolSampler + trainer=OurTrainer.__new__(OurTrainer) + trainer.train_dataset=list(range(5)) + trainer.args=SimpleNamespace(data_protocol='mezo',group_by_length=False,seed=42) + assert isinstance(trainer._get_train_sampler(),RandomSampler) + assert sorted(trainer._get_train_sampler())==list(range(5)) + trainer.args.data_protocol='legacy' + assert isinstance(trainer._get_train_sampler(),ProtocolSampler) diff --git a/tests/test_node_descent.py b/tests/test_node_descent.py new file mode 100644 index 0000000..d251491 --- /dev/null +++ b/tests/test_node_descent.py @@ -0,0 +1,239 @@ +"""Unconditional node refresh transitions and retained descent-probe reference.""" +import copy +from types import SimpleNamespace + +import pytest +import torch + +from test_mezo_refactor import algorithm, make_trainer + + +class QuadraticModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.left = torch.nn.Linear(2, 1, bias=False, dtype=torch.float64) + self.right = torch.nn.Linear(2, 1, bias=False, dtype=torch.float64) + self.offset = torch.nn.Parameter(torch.tensor([0.3], dtype=torch.float64)) + with torch.no_grad(): + self.left.weight.copy_(torch.tensor([[0.2, -0.1]])) + self.right.weight.copy_(torch.tensor([[0.1, 0.4]])) + + def forward(self, x): + return self.left(x) + self.right(x) + self.offset + + +@pytest.fixture +def quadratic_engine(): + model = QuadraticModel() + inputs = { + 'x': torch.tensor([[[1., 0.], [0., 2.]]], dtype=torch.float64), + 'attention_mask': torch.ones(1, 2, dtype=torch.long), + 'target': torch.tensor([[[1.], [-1.]]], dtype=torch.float64), + } + + def forward_loss(batch): + predictions = model(batch['x']) + return (predictions - batch['target']).square().mean() / 2, predictions + + engine = make_trainer(model, forward_loss) + with torch.no_grad(): + engine.configure_basis(inputs) + engine.basis = {name: torch.tensor([[1.], [0.]], dtype=torch.float64) + for name in engine.linear_map} + engine.history = { + 'left.weight': torch.tensor([[1.]], dtype=torch.float64), + 'right.weight': torch.tensor([[2.]], dtype=torch.float64), + } + yield engine, inputs + + +def snapshot(engine): + return { + 'parameters': [p.clone() for p in engine.parameters], + 'basis': copy.deepcopy(engine.basis), + 'history': {name: value.clone() for name, value in engine.history.items()}, + } + + +def assert_unchanged(engine, before): + for original, current in zip(before['parameters'], engine.parameters): + torch.testing.assert_close(original, current, rtol=1e-12, atol=1e-12) + for name, basis in before['basis'].items(): + torch.testing.assert_close(basis, engine.basis[name], rtol=0, atol=0) + for name, value in before['history'].items(): + torch.testing.assert_close(value, engine.history[name], rtol=0, atol=0) + + +@torch.no_grad() +def test_descent_probe_matches_actual_quadratic_update_and_restores_state(quadratic_engine): + engine, inputs = quadratic_engine + candidates = [engine.basis, dict(engine.basis, **{ + 'left.weight': torch.tensor([[0.], [1.]], dtype=torch.float64), + })] + before = snapshot(engine) + count = engine.counts['training'] + seed, lr = 451, 0.07 + probes = algorithm(engine, mu=.03, task="DROP").descent_probe(inputs, candidates, seed, lr) + assert engine.counts['training'] - count == 5 + assert engine.counts['evaluation'] == 0 + assert_unchanged(engine, before) + + clean = float(engine._forward_outputs(inputs)[0]) + for candidate, result in zip(candidates, probes): + updated = engine.shifted(inputs, candidate, seed, -lr, + response=result['response']) + assert result['predicted_descent'] == pytest.approx(clean - float(updated), + rel=1e-10, abs=1e-12) + assert result['response'] == pytest.approx( + result['slope'] + .03 * result['curvature'] / 2, + rel=1e-11, abs=1e-12) + assert_unchanged(engine, before) + + +@torch.no_grad() +def test_node_refreshes_proposed_bases_without_comparison(quadratic_engine, monkeypatch): + engine, inputs = quadratic_engine + before = snapshot(engine) + loss_before = engine._forward_outputs(inputs)[0].clone() + trainer = algorithm(engine) + trainer.probe_batch = lambda: inputs + proposed = torch.tensor([[0.], [1.]], dtype=torch.float64) + calls = [] + + def proposal(inputs, seed): + calls.append(('proposal', seed)) + trainer.counts['training'] += 1 + len(trainer.history) * trainer.args.node_queries + return {'left.weight': proposed}, {'left.weight': {'history_norm': 1.}} + + def next_update(inputs, seed): + calls.append(('update', seed)) + torch.testing.assert_close(trainer.basis['left.weight'], proposed, rtol=0, atol=0) + assert torch.count_nonzero(trainer.history['left.weight']) == 0 + return {}, None + + monkeypatch.setattr(trainer, 'node_proposal', proposal) + monkeypatch.setattr(trainer, 'descent_probe', lambda *args: pytest.fail('Unexpected comparison')) + monkeypatch.setattr(trainer, 'fix_step', next_update) + _, event = trainer.node_step(inputs, 81) + assert event['accepted'] is True + assert event['variant'] == 'node_unconditional_refresh_control_v1' + assert event['cost'] == 5 + assert all(name not in event for name in ('probes', 'old_descent', 'new_descent', 'gain')) + assert [kind for kind, _ in calls] == ['proposal', 'update'] + assert calls[1][1] == 81 + assert calls[0][1] != calls[1][1] + torch.testing.assert_close(engine.basis['left.weight'], proposed, rtol=0, atol=0) + torch.testing.assert_close(engine.basis['right.weight'], before['basis']['right.weight'], + rtol=0, atol=0) + assert torch.count_nonzero(engine.history['left.weight']) == 0 + torch.testing.assert_close(engine.history['right.weight'], before['history']['right.weight'], + rtol=0, atol=0) + for before_weight, weight in zip(before['parameters'], engine.parameters): + torch.testing.assert_close(before_weight, weight, rtol=0, atol=0) + torch.testing.assert_close(engine._forward_outputs(inputs)[0], loss_before, rtol=0, atol=0) + + +@torch.no_grad() +def test_empty_node_proposal_keeps_basis_and_history(quadratic_engine, monkeypatch): + engine, inputs = quadratic_engine + before = snapshot(engine) + trainer = algorithm(engine) + trainer.probe_batch = lambda: inputs + monkeypatch.setattr(trainer, 'node_proposal', lambda inputs, seed: ({}, {})) + monkeypatch.setattr(trainer, 'descent_probe', lambda *args: pytest.fail('Unexpected comparison')) + trainer.fix_step = lambda *args: ({}, None) + _, event = trainer.node_step(inputs, 81) + assert event['accepted'] is False + assert 'reason' not in event + assert 'probes' not in event + assert_unchanged(engine, before) + + +@pytest.mark.parametrize(('method', 'budget', 'refreshes', 'used', 'cost'), [ + ('node', 11, 0, 5, 7), ('node', 12, 1, 12, 7), + ('adjust', 10, 0, 5, 6), ('adjust', 11, 1, 11, 6), +]) +def test_trainer_reserves_full_refresh_and_next_update(monkeypatch, tmp_path, + method, budget, refreshes, used, cost): + from methods.large_models import trainer as module + + # Exercise the real scheduling loop without writing model/result artifacts. + events = [] + monkeypatch.setattr(module, 'save', lambda *args: None) + monkeypatch.setattr(module, 'append', lambda path, data: + events.append(data) if path.name == 'refresh.jsonl' else None) + monkeypatch.setattr(module, 'memory', lambda: {}) + trainer = module.OurTrainer.__new__(module.OurTrainer) + trainer.args = SimpleNamespace(output_dir=str(tmp_path), per_device_train_batch_size=1, + calibration_samples=1, trainer=method, preflight_only=False, seed=42, + main_forward_budget=budget, max_steps=2, refresh_every=1, node_queries=2, + eval_main_forwards=100, save_final_checkpoint=False, data_protocol='mezo') + trainer.state = SimpleNamespace(global_step=0);trainer.model = None + trainer.counts = dict(training=0, calibration=0, evaluation=0, diagnostic=0) + trainer.history = {name: torch.ones(1) for name in ('a', 'b', 'c')} + trainer.parameters = [];trainer.basis = {'a': torch.ones(1)} + trainer.refreshes = 0 + def configure(inputs): trainer.counts['calibration'] += 1 + trainer.configure_basis = configure + trainer.train_dataset = [0];trainer.curve = [];trainer.started = 0 + trainer.progress = lambda *args: None + trainer.collate = lambda *args: {} + trainer.get_train_dataloader = lambda: [{}] + trainer._prepare_inputs = lambda inputs: inputs + trainer.learning_rate_at = lambda q: 1e-3 + trainer.measure = lambda: trainer.curve.append(dict(main_forwards=trainer.used())) + def proposal(inputs, seed): + trainer.refreshes += 1 + trainer.counts['training'] += 7 + return {'a': torch.ones(1)}, {} + trainer.node_proposal = proposal + def descent_probe(*args): + pytest.fail('Unconditional node refresh must not query a descent comparison') + trainer.descent_probe = descent_probe + def collect_basis(inputs): + trainer.refreshes += 1 + trainer.counts['training'] += 1 + return {'a': torch.ones(1)} + trainer.collect_basis = collect_basis + def adjust_probe(*args): + trainer.counts['training'] += 5 + return dict(gain=1., old_loss=2., new_loss=1.) + trainer.adjust_probe = adjust_probe + def update(model, inputs, seed): + trainer.counts['training'] += 2 + trainer.zo_step = update + trainer.zo_update = lambda model: dict(batch_loss=1.) + trainer.configure_history = lambda: None + result = trainer._inner_training_loop() + assert trainer.refreshes == refreshes + assert result.metrics['main_forwards'] == used <= budget + assert len(events) == refreshes + if events: + assert events[0]['cost'] == cost + assert trainer.counts['evaluation'] == 0 + + +def test_minimal_cli_has_no_search_controls(tmp_path): + from methods.large_models.run import parse_args + args = parse_args(['--trainer', 'node', '--output_dir', str(tmp_path)]) + assert all(not hasattr(args, name) for name in ('node_variant', 'probe_pairs', 'gate_k', 'gate_margin')) + + +@pytest.mark.parametrize(('flag', 'value'), [ + ('--probe_pairs', '2'), ('--gate_k', '1'), ('--gate_margin', '0'), + ('--node_variant', 'unconditional'), ('--probe-pairs', '2'), + ('--gate-k', '1'), ('--gate-margin', '0'), ('--node-variant', 'unconditional'), + ('--node_variant', 'descent_gradient_proxy_v1'), + ('--node-variant', 'descent_gradient_proxy_v1'), +]) +def test_removed_search_controls_fail_explicitly(tmp_path, flag, value): + from methods.large_models.run import parse_args + with pytest.raises(ValueError, match='not used'): + parse_args(['--trainer', 'node', flag, value, '--output_dir', str(tmp_path)]) + + +@pytest.mark.parametrize('epsilon', ['-1', '0', 'nan', 'inf']) +def test_invalid_node_epsilon_is_rejected(tmp_path, epsilon): + from methods.large_models.run import parse_args + with pytest.raises(ValueError): + parse_args(['--trainer', 'node', '--node_epsilon', epsilon, '--output_dir', str(tmp_path)]) diff --git a/upstream.lock.json b/upstream.lock.json new file mode 100644 index 0000000..e725e91 --- /dev/null +++ b/upstream.lock.json @@ -0,0 +1,41 @@ +{ + "mezo": { + "url": "https://github.com/princeton-nlp/MeZO.git", + "commit": "552cb1b710767f9a6e1dc8f9645d7640376f9941", + "source_tree": "2b826d5880f84db1b8ebf3249ea6ade9c03ddedd", + "license_files": [ + "LICENSE" + ], + "native_transformers": "4.28.1", + "upstream_modified": false + }, + "lozo": { + "url": "https://github.com/optsuite/LOZO.git", + "commit": "5d1ade5bf41846471d33ba526f877829b9a19856", + "source_tree": "63488939fd9ac48e769affa28586c817100df17b", + "license_files": [], + "native_transformers": "4.28.1", + "upstream_modified": false + }, + "agzo": { + "url": "https://github.com/Yining-Jiang/ActivationGuidedZO-NPU.git", + "commit": "623e09a5a7dfdee697a603ec1e7aa01e3f5e6290", + "source_tree": "5fa4dfa64232f761b908ce4933de664ed4bf60ef", + "license_files": [ + "openPangu LICENSE", + "LICENSE" + ], + "native_transformers": "4.53.2", + "upstream_modified": false + }, + "loren": { + "url": "https://github.com/hseung88/loren.git", + "commit": "b80a32bc394332d1a1f115f41dfb5dcf7b326d37", + "source_tree": "c22d4a2050b517551e60b8a08f2fb76603dbcc7d", + "license_files": [ + "LICENSE" + ], + "native_transformers": "4.44.2", + "upstream_modified": false + } +} diff --git a/upstream_files.sha256.json b/upstream_files.sha256.json new file mode 100644 index 0000000..89639fd --- /dev/null +++ b/upstream_files.sha256.json @@ -0,0 +1,543 @@ +{ + "mezo": { + "commit": "552cb1b710767f9a6e1dc8f9645d7640376f9941", + "files": { + ".gitignore": "85fa6f97d301888b9763902185c1c8767d7a04e14d0c26fc7140c7ead8013aa5", + "LICENSE": "7735771cbaf9bbaedc38935d08ae54b0f9ea0891d910bff6bb99e63e0e0dd8bc", + "README.md": "a4135ee69db25c05bd27157e48e7405dc474fe8c194dd861e4a8dacec8179c43", + "assets/fig1.png": "4a303322b4ce472bcff5dfb67d55a60cb7d4dac29360c8bcc4814cbb572b8439", + "assets/fig2.png": "7b28780c217bc7295bbcf55e860e483ac50590ad6639f6df49aa5d1b6995b595", + "large_models/README.md": "a14844c4e4bd00f78933c439e23b6349c37c8f44fdcfb4f153717a7508283acf", + "large_models/finetune.sh": "0f4f400549af1d39fe1cd641da9d6d1a6ea952d0d063289ed2f30b690463630c", + "large_models/finetune_fsdp.sh": "abf2194143f7421608a47149c093103ad2b5447b53e08056b2596167aa996256", + "large_models/ht_opt.py": "515aa6610cf4cbbd928b6c617f5955d11efc74c76ee6823fd684182b30621d84", + "large_models/icl.sh": "cb1445f1f652c513b76394e54a43b66c057899ff46ea6ff074a37647cd7e61e3", + "large_models/lora.py": "06e3192b8b5485c05780747f33ea471d1f7634d0a04fa62101a682661b5a7868", + "large_models/metrics.py": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c", + "large_models/mezo.sh": "fca9d2d12530575553a7c08de500dc4163d5cd8f9050572e141f0c50e9d834e1", + "large_models/prefix.py": "a723f1bf7f1c8ace56a8e958eb30de9c3edd02cdd61594b20b924e40cacc9eda", + "large_models/run.py": "00b864c0e53c28f02572a510e6d612bfcca38682be843054bc1806354815bd81", + "large_models/tasks.py": "693c28ccc7e02997a7dced601f15a89d67a514581f98d1bc642768ef3271ed58", + "large_models/templates.py": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6", + "large_models/trainer.py": "afa12212d93f20ee34528f99c320c327dfa5d2ade080743fadd44c8ba8212bf6", + "large_models/utils.py": "04686e63041fcc9efce7284ead16c8b5a5aa6f6e648ede447b587cad9531b0aa", + "medium_models/README.md": "9b88df7b0152479f4ccb8526d27c2ae720eddc67ab3737c4aa1c38fa61ce106f", + "medium_models/data/download_dataset.sh": "58bd45e307d1dc344dbee822db30ec67fe447856bd1c365cee34a99a359b5d21", + "medium_models/finetune.sh": "9f40c1ad3435b35a20d982b3667c349b50c170d8083ba9356480d0457dce8861", + "medium_models/mezo.sh": "c7dea4a69a6a93e6a413004cc4b5fa0df6b0f0258fc07050cbbb159d60c58bff", + "medium_models/run.py": "82063678d81c8016f16e6e89f1116d6adb237a6bb4c843ba344d8f37bdee5fa7", + "medium_models/run_fewshot.sh": "681cc736a43153744dbe5ba4310a436a74ea3a154a5e37702a21662ad5b0a8c4", + "medium_models/src/dataset.py": "b5ae153d65e674a8d79066d7208132cdecb403ca813ffcf47f259d16b89e824a", + "medium_models/src/kernel_solvers.py": "9adcfdf9059f31dbe3ecda8e9ed3f47976b534e42bab5ccb52b3994f5eead46b", + "medium_models/src/kernel_trainer.py": "a381c962a8053778ceef6ee0dacb34851dbe872271e11026e6ad6c00ade2043d", + "medium_models/src/linearhead_trainer.py": "dd69fe9391c9c11768d09aa655156a24df5a971d204a3773f7af6be49a6af597", + "medium_models/src/modeling_opt.py": "1c5428264bf1bbd42bcc3d31291864700a86a2ed2a2d72b7448e928251677f1e", + "medium_models/src/modeling_roberta.py": "b96a9ad7ca184bec6521cbdb4968e27ab1ea2f0f6cdffa72c737dc3fd4af4c6a", + "medium_models/src/models.py": "8a9237124eee18ede80383092380502f91c4934cf82569a4dcb8f434e655edd9", + "medium_models/src/prefix.py": "b2ab39487c1fbb2ca9e443c7648cc3659016f7cd7e7683370970b0c63232cc3a", + "medium_models/src/processors.py": "0928e9c0579a2cca1a1edf5a0998a2a4c9c729952c425d13719bad1e7eab8cb7", + "medium_models/src/trainer.py": "03f8c0127f6c58ad8a7de24d2f6584720d79923c9a5ab65e30f0ea166989ff63", + "medium_models/tools/gather_result.py": "b7afa1abe2f5dc77a1be73f49d730d1ca55b4cf8a6142538eef14dcfe4c276f4", + "medium_models/tools/generate_k_shot_data.py": "5ed0bae1742b4f72818e8142cce308d66cfcd91f7147d16ffafdf75d0249cae5" + } + }, + "lozo": { + "commit": "5d1ade5bf41846471d33ba526f877829b9a19856", + "files": { + "README.md": "f5960fe3bbc5420db67df6715f93c39372047900ea7f5629f469b63db363b43b", + "assets/combined_loss_vs_epochs.png": "d450b60725a7d0f85597c672510a000b298e1eafc05c2b06067a083915acacd7", + "assets/memory_and_k16.png": "7a2ebbcbf6325f2b7301c277ecbe0fcf87a484bf8b6c171fe7cf1cef61d33f67", + "large_models/LOZOtrainer.py": "f23ce77d9064996382a2f64b191939e08c614a9c78983d46a8fa59d2ecc79a7d", + "large_models/README.md": "dc2f8bf3d0b916f5363623dec468a02b4eb03cc2c3541c6dae6887cc25f1cc20", + "large_models/finetune.sh": "0f4f400549af1d39fe1cd641da9d6d1a6ea952d0d063289ed2f30b690463630c", + "large_models/finetune_fsdp.sh": "abf2194143f7421608a47149c093103ad2b5447b53e08056b2596167aa996256", + "large_models/ht_opt.py": "515aa6610cf4cbbd928b6c617f5955d11efc74c76ee6823fd684182b30621d84", + "large_models/icl.sh": "cb1445f1f652c513b76394e54a43b66c057899ff46ea6ff074a37647cd7e61e3", + "large_models/lora.py": "06e3192b8b5485c05780747f33ea471d1f7634d0a04fa62101a682661b5a7868", + "large_models/lozo.sh": "57239f426d3ef81e99ed89e4f92afcdee7f6133eee5cb702ba886c2b94dc5a42", + "large_models/metrics.py": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c", + "large_models/mezo.sh": "2ce409341421ff70a906e7865391a471ef4c5e4a067f86f5dc36c3adc4c3f244", + "large_models/prefix.py": "a723f1bf7f1c8ace56a8e958eb30de9c3edd02cdd61594b20b924e40cacc9eda", + "large_models/run_lozo.py": "47ba8a0a0fc3b43882b0bc7f40aa6d8a1c8e9820451f4e78f9005cabd21d52c5", + "large_models/run_mezo.py": "f6a4744dfa897727bd8d8aed96f7e575a512346e4bcfbaf90bee42222eb67407", + "large_models/tasks.py": "693c28ccc7e02997a7dced601f15a89d67a514581f98d1bc642768ef3271ed58", + "large_models/templates.py": "bc80e8f55c4d7cfdd3ca8493131297b6c7687d7ebc714ee5aebe16c6856ec2f6", + "large_models/trainer.py": "afa12212d93f20ee34528f99c320c327dfa5d2ade080743fadd44c8ba8212bf6", + "large_models/utils.py": "04686e63041fcc9efce7284ead16c8b5a5aa6f6e648ede447b587cad9531b0aa", + "medium_models/README.md": "381af9104e7fc07f9ca40847fa439c7e3fae364edbb2dcddd347b436486de18f", + "medium_models/finetune.sh": "42013fdb1497e036e5eb89e3f51c09be1f46ad89e52a5743393ececb7ab7e8bc", + "medium_models/lozo.sh": "3edb3f4037e24faf7babe59df087c204447607a274b4080e64f54844e916c1eb", + "medium_models/mezo.sh": "c76e97bb67e51577decbd30dfed9eb2c9e0adcd36d23a0311bd1f2e6d09a6668", + "medium_models/run_fewshot.sh": "f1c1abca1cc6eb162df8f4d3971b1d3617270bf2b78c450cf131b15dca9cf788", + "medium_models/run_fewshot_lozo.sh": "5c75bf13436100800152c964a8055a3a48371425da55c05a66d5c614735f78de", + "medium_models/run_lozo.py": "f58374ea3be26b9f25a0be92f1af559127c0fda996a065ae3a5eae36f9dfbf1b", + "medium_models/run_mezo.py": "82063678d81c8016f16e6e89f1116d6adb237a6bb4c843ba344d8f37bdee5fa7", + "medium_models/src/LOZOtrainer.py": "91c05ba5b3f9fa5667e5649613543d432f1045c961c745f1bbc3adc6f66d3459", + "medium_models/src/dataset.py": "b5ae153d65e674a8d79066d7208132cdecb403ca813ffcf47f259d16b89e824a", + "medium_models/src/kernel_solvers.py": "9adcfdf9059f31dbe3ecda8e9ed3f47976b534e42bab5ccb52b3994f5eead46b", + "medium_models/src/kernel_trainer.py": "a381c962a8053778ceef6ee0dacb34851dbe872271e11026e6ad6c00ade2043d", + "medium_models/src/linearhead_trainer.py": "dd69fe9391c9c11768d09aa655156a24df5a971d204a3773f7af6be49a6af597", + "medium_models/src/modeling_opt.py": "1c5428264bf1bbd42bcc3d31291864700a86a2ed2a2d72b7448e928251677f1e", + "medium_models/src/modeling_roberta.py": "b96a9ad7ca184bec6521cbdb4968e27ab1ea2f0f6cdffa72c737dc3fd4af4c6a", + "medium_models/src/models.py": "8a9237124eee18ede80383092380502f91c4934cf82569a4dcb8f434e655edd9", + "medium_models/src/prefix.py": "b2ab39487c1fbb2ca9e443c7648cc3659016f7cd7e7683370970b0c63232cc3a", + "medium_models/src/processors.py": "0928e9c0579a2cca1a1edf5a0998a2a4c9c729952c425d13719bad1e7eab8cb7", + "medium_models/src/trainer.py": "03f8c0127f6c58ad8a7de24d2f6584720d79923c9a5ab65e30f0ea166989ff63", + "medium_models/tools/gather_result.py": "b7afa1abe2f5dc77a1be73f49d730d1ca55b4cf8a6142538eef14dcfe4c276f4", + "medium_models/tools/generate_k_shot_data.py": "5ed0bae1742b4f72818e8142cce308d66cfcd91f7147d16ffafdf75d0249cae5" + } + }, + "agzo": { + "commit": "623e09a5a7dfdee697a603ec1e7aa01e3f5e6290", + "files": { + ".gitignore": "d3abea335f8caadcb319fa34c0de51cf9b8cb62212ad2776d816f1bf7d7c6bf1", + "LICENSE": "3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986", + "README.md": "3d8fd3b7283c62ac27769f712b26eb48c2a7ec0434bdd5e3e76d39bb55b4b1a8", + "openPangu LICENSE": "747083c8c24995c75ed641d5c031a95a859b1ec37cd3deeb033425a75249a3cb", + "requirements.txt": "b2fbdbcb927961e4064e16e3881bd8c555ba213cce5dcccb6bc38437f073bdb7", + "run_agzo_pangu-1b.sh": "368379bcb192e5410d07b2ef57666c20f989183a10de3d1a5f9903b5844c61de", + "run_fo_pangu-1b.sh": "342cd7629f72aa4730b0ec5d19c8ee4ec1e1a72ada96fce2df3350f244824ca9", + "run_icl_pangu-1b.sh": "da0e6463e16a7c9115467bc9f56b5259e92fecc8a6771bd6698fc0c84f6ee16c", + "run_lozo_pangu-1b.sh": "467942394dd4784e2a93c5200fe2e582ae35aadc7c6100c7b258c01659461c63", + "run_zeroshot_pangu-1b.sh": "40d086589042494aa1df2213ffe4399cbe181f809b6c2478ccc2cd0a77a2c7db", + "run_zo_sgd_pangu-1b.sh": "7d910eb80276564337a1bf4213fa0d2ec03dc0d00b89989b1105d231cec00c36", + "zo-bench/__pycache__/metrics.cpython-310.pyc": "97487eb0cbc1cc186158ee44ee4165632f1a36dd9bd6fa2ae92e82af54459c78", + "zo-bench/__pycache__/run.cpython-39.pyc": "e65b17e2765f1db40e0773ff0668484f74d697711460837ea5ce12697afc62a5", + "zo-bench/__pycache__/tasks.cpython-310.pyc": "de9385df813833e71ec5cc1b528def11d32a973218196d219dd2a932b9aad41d", + "zo-bench/__pycache__/templates.cpython-310.pyc": "fd3644d0746adaaf59528ad7005831f8eed3037fe2916a5e91c93b55ed7dcc47", + "zo-bench/__pycache__/trainer.cpython-310.pyc": "b1d6a269e2de776101b3dd11629d8b3f7286d9b0979d9ff877407bd5d4635b93", + "zo-bench/__pycache__/trainer.cpython-39.pyc": "8e77e0a97e2829c7c34b2734400b14860b28ad4b21042a1befd082b88ee4dfd3", + "zo-bench/__pycache__/utils.cpython-310.pyc": "a856f46cbb026671a8f4402856a58c6fcbdd482f9b15b2454bd0c16a58cc9639", + "zo-bench/fusion_result.json": "74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b", + "zo-bench/gradient_pruning/__init__.py": "06e728d3aad2503cb089a9fcab5ee34eb2ea37c503cb68003926c6d607ba0f02", + "zo-bench/gradient_pruning/__pycache__/__init__.cpython-310.pyc": "11619cdbd01a4a1c40d789f1178f7a0b82ec78ad84962b4b5d54339d31605d5a", + "zo-bench/gradient_pruning/__pycache__/pruning_utils.cpython-310.pyc": "445f1c89ee5d2baa998e954c7affd2345ead8f918ee1eefb3376407b22bde0bc", + "zo-bench/gradient_pruning/pruning_utils.py": "ac3d563b6cfbee990d6f956ce77897f747e31388a80c063e159713cc664102bc", + "zo-bench/gradient_pruning/wanda.py": "8f1ac529f1b2b7ce7d41841793d9483aa7c51f06d2f75f3044ce26f3600f8419", + "zo-bench/lora.py": "1deb64862661fca1897c5b8f811469ebf24be559029943eb12986633a57317f4", + "zo-bench/metrics.py": "a9146177b85b5aa654583ac2ed1f0c6aefb8940bf86aa4964ad02bd46165c94c", + "zo-bench/modeling_llama.py": "721879a5b83ed86dde79c78b89f46e7adf15b14fb898c95f199270ce6f0d94d2", + "zo-bench/modeling_mistral/__init__.py": "8cdd4598db48cda9e4077485d97073df8ec943ea263ee3c8d4d2c215d26d6941", + "zo-bench/modeling_mistral/__pycache__/__init__.cpython-310.pyc": "a734d79bcadee34eb658ef28ca1f99ec196a5e8c5926dddccb62be9f69821d38", + "zo-bench/modeling_mistral/__pycache__/configuration_mistral.cpython-310.pyc": "e01be5a744fce70143730083282ab64e5f5df2501e52f29b556e9bb8a0bf8907", + "zo-bench/modeling_mistral/__pycache__/modeling_mistral.cpython-310.pyc": "09562864675325bd28f04c1b29470435a4b4d90ee3e18d40cf51f5313d8c3370", + "zo-bench/modeling_mistral/configuration_mistral.py": "370910fa5b5bb5a727f336164ebecbae2b58452329e4192c3f4b97f9296f6a86", + "zo-bench/modeling_mistral/modeling_mistral.py": "5e891f45e9cbd53c04d33d2c65eced7cbcddbe5d6916b284aa980dc879ec6918", + "zo-bench/modeling_opt.py": "515aa6610cf4cbbd928b6c617f5955d11efc74c76ee6823fd684182b30621d84", + "zo-bench/npu_compat.py": "dd8d0e2f645d45135cc2784cd34b71b63de330a0c760347543f78fe486ba9148", + "zo-bench/prefix_tuning.py": "3f82384deb99a632376ed34a14bc527b8bab5df64702f7452230f4c8b3d62e43", + "zo-bench/prompt_tuning.py": "9b875b768d48406fcb5adb3257c4775d9ff4bbb4bbe87eb81674fc26f36f8ba9", + "zo-bench/run.py": "1dd9f60ea26d2e3ca7a8b172ff6786eb55665ad8414c847d818bdc21a9b03d6a", + "zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_ft.yml": "eacb00a09622703065ee81374ad6badf7cf8420f3a4e3a7e53e504f6de4a13a7", + "zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_lora.yml": "8113acb1d62b617fa4fff6821e712c866b92a81005b1c29e713dadf8fd4168ba", + "zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_prefix.yml": "aee6921497a85ccfdced28c125c06657e8101d7e5e4be40cc7956c8e2f122464", + "zo-bench/sweeps/Copa_llama-13b/adam/adam_copa_prompt.yml": "2ecf8c9839e3fa4445b4c2a30de3351940a5e660f1f8ec3cc9c55c891b6383e4", + "zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_ft.yml": "035a450468649291c23b651dd0cbe47e8e966ab5d286b4fd9257f9c23b349cc8", + "zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_lora.yml": "e1cbd2ad5d76f59a86d792f626973995cb1ca3dbff031fd2d4eec9ec810d397e", + "zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_prefix.yml": "07ffdbe7131d064560e3e6e8163bfcd2497d3e91f7388ace0fff28f3af9343ce", + "zo-bench/sweeps/Copa_llama-13b/forward_grad/forward_grad_copa_prompt.yml": "fb6a9eba3485096df7dfcb6e4efa02b5a6f56fde7d3ad809677e815377f44fa9", + "zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_ft.yml": "aef1588ee8a7e78fee865981e175f00d47c08c0eddaaab2e58159f10163b2b34", + "zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_lora.yml": "406e1d0b14f83ac39a4f0e7d6f4f074f06d2df8ebcd7284e3da2c1b3e66197cb", + "zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_prefix.yml": "7858cd311b78f8320a40844079d45302028768f4ce20e4975353b90f4431f900", + "zo-bench/sweeps/Copa_llama-13b/sgd/sgd_copa_prompt.yml": "d6d7e2090e4c8930ce683018a45e96bbc48e735c58d160073d69efb8245e3701", + "zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_ft.yml": "41d4af2af0aeac6e926f4a33768931680b52003bc8b152bbb4bafca276566c7c", + "zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_lora.yml": "9508fbb5d5119d9fe4b883b7bd15a8d46d920cbf59feab1607a1a77107896474", + "zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_prefix.yml": "508f9ce47c19023ca865de61812a3d2884ab2290911cb6e4cc017f2bab5371fd", + "zo-bench/sweeps/Copa_llama-13b/sign_sgd/sign_sgd_copa_prompt.yml": "a1af9a9b069b4544498c957c02302e6e226fc6c375d8b8e9c7761802cc2f456d", + "zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_ft.yml": "69e79eb2d3cdba78d333996cc9b941b377e806f70ac88df08f590668c72fcfda", + "zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_lora.yml": "801ee2c38e3960827d3e0c0410962abc69b6e5cad9d9e8488694ff0ba8502ec2", + "zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_prefix.yml": "43ea6aa4143ae45d8a3f80220896a0ee0b7ac58cc327223a5fd580d5cadccb75", + "zo-bench/sweeps/Copa_llama-13b/zo_adam/zo_adam_copa_prompt.yml": "9d5de541dff83cd8a0de6015de1e988259c03a93de5f280cb6b93e63a08c1416", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_ft.yml": "4095adb1bb4c60d5876edf4a94fbe2e4599fdad5c0a03bf115d4fbe93de042f2", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_lora.yml": "908ebe2bc669b09cdfa3a320d4a4476e425d311cacbe0b5c0fbe756e1e82b953", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_prefix.yml": "c6b5fb3a073ffde788b3a3bb31927925e05281e2ce4f94f13d409d797893ca69", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd/zo_sgd_copa_prompt.yml": "389d7a415ee50800d64f03e32f0e38b928daf46e1ccc59b5702826d118624a6b", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml": "b9e7480847908a1b5d84d14d6ae5712f9e6ef0852c60257a4dd9893d34b2795c", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml": "0a182a859b9cdec6f45a64da5537c6aa48183db67eb5b55406f114d9a79b23ca", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml": "7c756e1fd4874b9a931eb4caa26b8cb476f0ed4631baebf4d6a36ad7a2460576", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml": "1df19e96d3d459368e06a4467213544dd61e4fa5b603d7ae5823b1943a76bd28", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml": "9396e65079bfb23ceeab958ae095571d9bd0759fd6d5c981ffc3e9426a71ee04", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml": "39023f0a1549716cadc6c3cd79b297a68eacb51b0e4869dfbc017d8bb574e0b9", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml": "ce0985da63872ea7339c386d1a8c2746a85c4f460cd6411ee34eb9a66a75402f", + "zo-bench/sweeps/Copa_llama-13b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml": "51f8ddc6083d8e51b5a9d4a8a5239724191987db2749fb86b143ecbb13b902ce", + "zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_ft.yml": "b5a59ddbefde23b1b23a1090ef336ac165ac6aaf66796a25ae544b58f0beb091", + "zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_lora.yml": "bda84c35790ee41887f593660eec6d9f1f630e195d91838b48fd0d80c72b8480", + "zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_prefix.yml": "23dad4732a1700564ef485829fe4af27790dc8610091d274bf720b7b3eb91b7d", + "zo-bench/sweeps/Copa_llama-7b/adam/adam_copa_prompt.yml": "f5c077693dace88f4ab2f8ec6f3ca9722072ce0a5d1a4ae0e1062bec13df089d", + "zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_ft.yml": "9f2aedb1a10ef11de044913a9a1f091323ef0ffe8aa8840aba7e9ad44866c088", + "zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_lora.yml": "cd3c63513971f89aea8fa392dd07eff1c6ad5dd934034c2349162b2781a75c21", + "zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_prefix.yml": "7a195ebfa1bebe0cb2fc2a5d950b03a116a52374f9f47d2b8b0fb3e13c0b11b2", + "zo-bench/sweeps/Copa_llama-7b/forward_grad/forward_grad_copa_prompt.yml": "84a4f381720724bef0fc63b2dae9522f25a3dde0d532d3015145c26ee8ceaeb2", + "zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_ft.yml": "919bd4ce6f2d14e60d234086acc2d356a67d431f02d58817f0dfd68fc4653738", + "zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_lora.yml": "89498a32023d4392b685a80254ecdb158a89378c9f7dc929cd6fedc56ac49812", + "zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_prefix.yml": "54a2f6e65541f5768b3c010047e43181b58221afe433b96de73d3245074d14e0", + "zo-bench/sweeps/Copa_llama-7b/sgd/sgd_copa_prompt.yml": "ffbe1d76cb3e862ec864f8df838eb920fe0feba558b674c3f9faf29cf532c37e", + "zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_ft.yml": "98b1970dd44b286f22f90c40de834e5b8d9e7329abc69529d02d90ed2f57afef", + "zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_lora.yml": "b484e27d6f2db87b217735793bc8c753bf41396f7975f36d3edc04eac6b75d6d", + "zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_prefix.yml": "7b2d1d5413e152f2ba7a51a7e5280bd31fb18fe97f4d863413f17443550d00f7", + "zo-bench/sweeps/Copa_llama-7b/sign_sgd/sign_sgd_copa_prompt.yml": "cc77102bfc09cdca1ac79a1779c87a6b68311a662ace0d2af7f0778814440d2e", + "zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_ft.yml": "67278630f5de92030d0c0b986fbe3b4ebf8327f8a20567b1af59461dacb00b0e", + "zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_lora.yml": "ca81b21ddc5af57b3b75b1617084f1ca5b3d1cc8ee79bc49c719960cdcc30bd8", + "zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_prefix.yml": "e0cb99839d06a160ed785071622d8b0757acdfefe06bec5d42e96a17a0c11bf5", + "zo-bench/sweeps/Copa_llama-7b/zo_adam/zo_adam_copa_prompt.yml": "b04da28f182f606c9740bf6a69f5cb6fb639b9604ff0e819768a73a53a38fa94", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_ft.yml": "d35a20518b9f5c006f1872d653292022b415aef0c75ad7f026516c7ea2d60147", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_lora.yml": "4aa4f373173d409e68b9ce0981a2dfc9d5cb66369f5424993300d6720b899800", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_prefix.yml": "4a84933bfe9d89de5df7fe183a7c2a2c35796a43eb90f90e1237a872bad9bae9", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd/zo_sgd_copa_prompt.yml": "00a7721d6588c632a8a99332190b2d0430dc3555eb8f5b70f419ae0af3d2bb8e", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml": "8cf84aa9926ca0ef8680e692f8eae31fc049397c0c76d0da0e8ea61e1cead50b", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml": "86a498fd2bcec0505cfb99658749227d6827a1990faf08a261d675b24faa1b20", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml": "3c599a19f992607b216b03da55694c214852a9e7b892f2a494e2318fa06c354d", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml": "3690795bb46ae60d561d321ad12da4962e05485c0f557060aac7606787fdbba1", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml": "f27d9a91852421a3b2dc048f1e705c38a362d0aa381c88c41a8551f8523e5638", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml": "c37497affc4065c29f1a34154e42cf874c6a8235fc5f84b9b861b9df543a89c1", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml": "e6a97d7ae512cbd2f4162319df83b41169627f9e0c0193cf225c6a187eab2ba5", + "zo-bench/sweeps/Copa_llama-7b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml": "9ff5157e267ad6f67b77904c03c4269beb9128086f7ec603b17c5a7094a3d32b", + "zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_ft.yml": "31d0d30779525f5a7b821b903bc9fefc0fd4e9b44e8b42efddab7bb8ffb56d58", + "zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_lora.yml": "286cce48efe6b94ab5f25b6d87de50b1499df74f209b1ebf4207b9a62804268c", + "zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_prefix.yml": "d9ac4b93199990aeb78cbc35609759e98902ba1c4ba43615e1615df9ded55a60", + "zo-bench/sweeps/Copa_mistral/adam/adam_winogrande_prompt.yml": "71e27b051cdb8ff474aa6ce5fe941f50958626230eb1dc7ee38a3b77db1c2072", + "zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_ft.yml": "d99a65d87abfb8e908e4c8df1bc27754c1606a43cfb5c8f0c8361da4dcfc15f9", + "zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_lora.yml": "50db0d42175c5a31f4868703337c6a15ecf84ccba243e9d0bd26777e95ad733c", + "zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_prefix.yml": "669a0bfc6ed5c989736a30121a25566720d5b8132ecb7fb52f2076f16bd2310d", + "zo-bench/sweeps/Copa_mistral/forward_grad/forward_grad_winogrande_prompt.yml": "0e50af394d8d97556f44aeac8ee368c562496089d77d2b778b9c4568a1cd7a8f", + "zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_ft.yml": "ecd3beb7b3be173a6b3a4902284275397b6875297757f2b47631b6cb2e90d184", + "zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_lora.yml": "77cda4fcf576744c3dcfecdd8f0a6c2f12ed4a0bfe2230f3513ee2583b46c431", + "zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_prefix.yml": "bb5b8c2fb78c92a7900e937a6bce4bb66b988b185af288797c5f9c0de6f34bf7", + "zo-bench/sweeps/Copa_mistral/sgd/sgd_winogrande_prompt.yml": "2b873a42e5d37704a0e3dfbad1b43d3f65995c84c4f79622898b4f36b46da9be", + "zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_ft.yml": "233b99bbc7a128c17c040c4d812c15a47f5eefa57a99f84233b79ead536b9105", + "zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_lora.yml": "380b2aff349f9a95f4d46f782cde010d9619aa0d5b47ea49bca1e320aa35b84b", + "zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_prefix.yml": "112d6ffdef9733692bcad886f90df8f8469ad0a30f1bd6e41073527d91aed28f", + "zo-bench/sweeps/Copa_mistral/sign_sgd/sign_sgd_winogrande_prompt.yml": "6367c686ea2632695da278766b5304e32181f74d30d178681a7f4fb29204bc20", + "zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_ft.yml": "93763a7f6e0cb043ce944c3091e3a986a3b60457fdc627f91a6c4761887af67d", + "zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_lora.yml": "13a4977d6a8d3409f512bdea505c27fcfa6ca390283859a4302325f820e21ceb", + "zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_prefix.yml": "04ac5a031efa81e7b160f2a6ca64c45c8326ac3250c4bc099863e66add30f5b7", + "zo-bench/sweeps/Copa_mistral/zo_adam/zo_adam_winogrande_prompt.yml": "717e4d6e017e46dff560aea776443318bc1a926476f3918ae7a57f37b886b698", + "zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_ft.yml": "0f25be2747999fcf93e2717a74f23555c64e5ba464e530f32a15b4fafb43fbf1", + "zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_lora.yml": "4d0bcea5f20eaff8f69cdb0b34a5dbd0a687d69cdd7101ec0fa6ff2c5e87b3bb", + "zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_prefix.yml": "77b6b86c0122e0a6d871b6f4ee17ef8ae5716c7cf6057e21ca597a0502304f98", + "zo-bench/sweeps/Copa_mistral/zo_sgd/zo_sgd_winogrande_prompt.yml": "f603eaeca7621b5f99e03e1396d8e21b3ee2389ed8cde272d351d4190d61e3b8", + "zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml": "c21a5f8b861b54d8c315e329215a733af0d741032b909c7de3fc28e158065eb8", + "zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml": "ddff8d32550c5e57d07dad376a8a0078e56523b7ed7ffa021d14c6e342a98414", + "zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml": "8179670676f5fd3a4259976a0f4f65eb4e535c77803056111c4e4ee114bbb2dd", + "zo-bench/sweeps/Copa_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml": "cf68ad9b44d3eeb6e7f9f082117d2b5f3c2a7f9ea888c64726e886665bf17762", + "zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml": "bfd4e08d892cefa59d2fbd74dcf438fd5d9beb74cefebed31d6795202a41cc32", + "zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml": "82481df1b5bb76c278c1e8d076fc0a13b44112ddd1abb37b8c85999f5dad30cd", + "zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml": "0dfb0ec90c4eeae7cc06011b4a6a955e0959a4172e2e334dd01940a5fb929b16", + "zo-bench/sweeps/Copa_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml": "1cbdb9b9dc4a0ecb91d907c0161ba2910ea4204ad96e003052568ed553fcc0e5", + "zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_ft.yml": "806210c04f655ca7bbdb973c78b71a22737546305e25c576a4842ca2613cc47d", + "zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_lora.yml": "03196b84e775715c95feceeca25bdfc5bc92bccbadd02703acf01b07e043dd73", + "zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_prefix.yml": "b2d5b23ca663488993790f44c4952cea4140764a21896815f0a34b11a1ec24b8", + "zo-bench/sweeps/Copa_opt-13b/adam/adam_copa_prompt.yml": "df0c69da9e34bb6320985ab6d1922f9e58b4ebd093dbc1e06baff087be796ce6", + "zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_ft-ablation.yml": "f7a938ac57c65cae266190070ee9f5b8fca342264e82236666d3049206cf3f1f", + "zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_ft.yml": "5883e8e8fdf90babd2d36235a656fd4cef54f3553086a7b8a70d4ef3a5e1b0a7", + "zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_lora.yml": "efa34ec11f0e318f4e8196ec7938d9cc49a51bf693bafaa11db750ef9a3d3a64", + "zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_prefix.yml": "cabebc99988031a3f3db7c6896f2f16f09d19f48254b61a1e0b3bf3e2c6c9daa", + "zo-bench/sweeps/Copa_opt-13b/forward_grad/forward_grad_copa_prompt.yml": "821be7a488775f2be3a9b8d148bc52473bd4ffd73b9a1c749ad673696458c021", + "zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_ft-ablation.yml": "021d976968f2983345b5dff3b7fe7f1f790b77bace6a1718325685e2d5792180", + "zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_ft.yml": "d6c2a2a316f4b005a977ec14ebfdd1bfbc4c6ecd2188f24f40f47bcd6552b132", + "zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_lora.yml": "cc2725c50c9d41898fb60c16b781715aec03df93e2f83551c8e1ff4a8b52c847", + "zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_prefix.yml": "904f1b68081efd7a7a6b17b334dedf58cf6ca004668dc844b66f86d1f8289504", + "zo-bench/sweeps/Copa_opt-13b/sgd/sgd_copa_prompt.yml": "eee99bd28d4506b90757862dc2b2b17022179d7b687d7e49ef110bbf8b11bead", + "zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_ft.yml": "d4c4d09a9f144e4f66cc3977d9b3e93a115aeef905d449724e25d166a610d8f5", + "zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_lora.yml": "70f5e14e6a29d6bb100264d1d26654f61d51d1ce01a6ce7703553beb6d73f44e", + "zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_prefix.yml": "d19154c245ab2fe97ebd264e304653043d0985808ecad2eb4c190a01dd3e4d5b", + "zo-bench/sweeps/Copa_opt-13b/sign_sgd/sign_sgd_copa_prompt.yml": "9a97d6f9e6c50dc4709d26e538d25b88a39aae1e5ddf73aaf0ddff29c1e1b22e", + "zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_ft.yml": "c7a151bfce8fb328f592d40127d5530ee02ec70cfa7d4d47f4a6f08da0054042", + "zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_lora.yml": "fb31c0ddfc9857d6fd06c2bdfd3de4019764c8720b7007c4a6507cb9c623bd29", + "zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_prefix.yml": "df315010329d44ac942dec1ed4cbc5ffcd625bd9c92e2db49e5a79f23255c661", + "zo-bench/sweeps/Copa_opt-13b/zo_adam/zo_adam_copa_prompt.yml": "777de87085f33c3e5bfc3acbfd1187b7dbbcb60424579aa669476e5700d9ec54", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_ft-ablation.yml": "6fff41a21e4725a163ab175f7e7d42892f4d4a26f11a0c5ad1fb0b6cca468bf9", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_ft.yml": "7a69ff4fc73a7e0fb2883cd932c32e5be4e973d30c5c142c12c113e73556cb02", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lora.yml": "dc950e3b0e75f175faf77485f4fe04d475720d3a6a5767e96fba125a50e88ffa", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lp-ablation.yml": "68d150e2c0c074ec8d035968737584462996b5aa4ecee48fe164f381b86c2e4e", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_lp.yml": "db92f0402704da3f4d64822f8bad9bcfb4fbf3f07eb764cb0a74de542c130a0c", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_prefix.yml": "60e6837dbb02359edcc7feec7ba4f496646e2c97a54e490e32a161ac0f75fa54", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd/zo_sgd_copa_prompt.yml": "9347ae7956cd4bde54dd5d00f59c45a7532cea8a777666f57073d4f6b5e6ad6a", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_ft.yml": "199ce8992d7349e06535aa5dbd417d5f9b7e7856f6d7e82c12dccf779f39d329", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_lora.yml": "baa78f8af044b6777f1ccd080e800740e237de258dbf948687ebba8adba50276", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prefix.yml": "f2aaba87d72ec729f2df7dd56672134f0893a0ca814984ce4696f7c4b6ea0ce1", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd_conserv/zo_sgd_conserv_copa_prompt.yml": "5e40e95996de57aff76b6a2ba41bf3d143d449099fa6d21a99dae4d4586ffb81", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_ft.yml": "6a06ba2e396985ef2acf5b4dc3c56c3f1d158b8768672f007761b6dd57e7ea6b", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_lora.yml": "75c9be5510833f7160daf0f3c17c63da1057e9eb408d757bd8b14d1576d80909", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_prefix.yml": "7117ad77ef0f9cb33ac69ae088894f2bb42e63259025a569b4ddfb7b21919f3e", + "zo-bench/sweeps/Copa_opt-13b/zo_sgd_momen/zo_sgd_momen_copa_prompt.yml": "6a7670ff000da43a4bbffd88b3cb2a174ea2b603e979fbbb5b2a76a3610e4f22", + "zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_ft.yml": "61b4811eb6cd9f10aa126a316fd071b8fd4d5d7429bc7281f896ac266c48f17a", + "zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_lora.yml": "6e7c188c672f98285d84ce0e41e98db9eb64908712bcf307833162438fb04080", + "zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_prefix.yml": "18d20579d43a70856b4459365d22550734547b1aa4539c5fc29ac972a80458d5", + "zo-bench/sweeps/Copa_vicuna/adam/adam_winogrande_prompt.yml": "9a8457183bdb9be8613bb309138de370497189b1834daac0b61e49a13ac97ebd", + "zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_ft.yml": "b9aa4264a4f880900c698fe3081d9e6c62e8a02529d4bbd2f511fc83781eb4f1", + "zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_lora.yml": "352c22e1e574db1c1cf4c395a0f144f26786619ebdf4222eea7a87df61486044", + "zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_prefix.yml": "eb0c5ed0d7d685afa48643a4ea493578b33cd5ec68f8edb8f6613c543e221f27", + "zo-bench/sweeps/Copa_vicuna/forward_grad/forward_grad_winogrande_prompt.yml": "ac38efd406dcb64475cdf78ee9b1c8953226fd6b93a8dd3345f8be43ef92e493", + "zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_ft.yml": "1d7189980d64465c72d7aeef562975c614d16a693077818d1bdb6a14a666788c", + "zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_lora.yml": "d48c4a3a3897569fb0b5491ae30ec823c0de8db5bb19ba606ce0d32e8598e1fe", + "zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_prefix.yml": "bda72ff10eeff327ae078fde3d6dbae60a3db8e1041bc177ae6fb925f8112b39", + "zo-bench/sweeps/Copa_vicuna/sgd/sgd_winogrande_prompt.yml": "3119c397db36380b70fd37bd41a6034db7da20a9efb9f95121fa81a759c409ec", + "zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_ft.yml": "37c9ad92a32ce2b3dd127ff53bf1be8a98d3d40b3a4c2d894f90b76aa72ff4e3", + "zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_lora.yml": "00edfc4d3d3ea3f533a0460620433b4c04b5ae579f6556929c43715dffafc58a", + "zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_prefix.yml": "d9a997923a25a4c893fc65787e7da1eb724c5c424231aa4b182230e84abf1ba5", + "zo-bench/sweeps/Copa_vicuna/sign_sgd/sign_sgd_winogrande_prompt.yml": "9eea110ff6afea131ff130d36cb775bec30095b4e9cbbf4eb5a8f0597830db44", + "zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_ft.yml": "628b214a148e7042ae6f7bfbf362f8a1dcc86d8cb8d4090573fcf771566c406c", + "zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_lora.yml": "11c8bbf795d35f8a16df45c7a1088f302983a83d6e3a17b47a1ec1227ac82371", + "zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_prefix.yml": "d4e8095c0fa2171fed47303c612349f5be33246e630ceb2dd9d854b9e5c46eeb", + "zo-bench/sweeps/Copa_vicuna/zo_adam/zo_adam_winogrande_prompt.yml": "0f0ce3c3ee8f10d49682f3e1895cb57e39b050c5661723f4b76620204beffd8c", + "zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_ft.yml": "8ec3a2f434f09f4b5b07228c6a8638038691d278d812851f28ec8d7129abbcab", + "zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_lora.yml": "8a3861a4e5bfef5c0a490a4351543bc5b3641ea2d877aa4f1568c7a5560a3c89", + "zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_prefix.yml": "3b8cc5d1145d47a392d2b20d3de64c0debd76ca59815811a483c14108c3e29dd", + "zo-bench/sweeps/Copa_vicuna/zo_sgd/zo_sgd_winogrande_prompt.yml": "09a91f6d2601bf2d227f07fac107fcae250f699bf625bd58f66bab3135a450b5", + "zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml": "03b11aec415f7c053e4048e7b2197ad9380885ee513c5dd1fd02474ee75607f4", + "zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml": "faac53fb10b51e8a78d11c86463cb86413295c5512297aa311a3376aa3079dfb", + "zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml": "0df338e9434dc72e2301c7b33bbf8f8cf26da458cda64ee9bee5b05ce4bb8475", + "zo-bench/sweeps/Copa_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml": "8d0a9d9161338fc89a55fc8feb414fbb5a74c88d5247d75596adf010b3b4b1fb", + "zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml": "dab13b7f531339de70daba654a26256f302320eabb17fe4446bf7e9e479b59d7", + "zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml": "ada80f452a3e2e4a6a6abd4c3a0e8c4dda2f4719d2874ed0ee0d0bcadf66dacf", + "zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml": "a6da3a4367303d8e95d9cb7a03f98be9255db9d5386b3f8904072c23e0308837", + "zo-bench/sweeps/Copa_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml": "4e98c48def7c9c72b058e6bc916b3ee3f2c61e655accb201dd77b3bca98dc033", + "zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_ft.yml": "9e807ee3d96714ad818b2c03137f57f15b5bfc5573fd527f2711f45e9e52032b", + "zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_lora.yml": "145d8188d1220338dae4b14204451c32b4ba05bc3a2ef182e0cc41035b02c538", + "zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_prefix.yml": "70d055bd95bc5d61029b062be4dbc3d4f85fc5a576594e707157968ac000ebf1", + "zo-bench/sweeps/SST2_opt-1.3b/adam/adam_cls_prompt.yml": "b604be8813181dd8955948162b0570ef5413bf0d7b85c1b18083b44a27e0bf46", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_ft-ablation.yml": "7fd69b8419e675f1ab6ab57fb66ddbfd4e8c4febf362df7feb83aa84d956c38f", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_ft.yml": "468ee4f2d99ed86ae2444ee19e95d4cba3c5560d9c151aa85f1a48434cadaf20", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_lora.yml": "b76d5a8484b761053c876b95480a7bcd34a98686f2f41773da58b11fcffa3fda", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_prefix.yml": "6d43ee917fb715067c8a301d920bc301bdd0a6afc11d03207c3d8565ae91a34e", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_cls_prompt.yml": "7b1bd47439c96b982ce3ffbbf392e8886773a62d9cc53dda5c97afc8e4aef245", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_ft.yml": "f9777a859be0b09c3120879593d51dd541c76073b27bf792eeb7d69115c0289b", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_lora.yml": "3acc5fdacc0f4fb378698c3c53088cdda58f713725dbeaed194b23b0892bae5b", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_adam/forward_grad_cls_prefix.yml": "9c3eb83eff62291c68b98d6bf4ecfd020ba30ffbb59e6af21b7f3e4d2407e024", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_ft.yml": "8373d929952b494cebc99da70619adf7e4bafd49d4c7a8875c87f123f487cd50", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_lora.yml": "21888c765246d27c9474793ef911e634bf48d796c52ca5e546fecac2d34ecfda", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_lr_scheduler/forward_grad_cls_prefix.yml": "08cae67f689e760f4fd59c3a7c416eb56cad8929e72c4f331173f07619765bf9", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_q_number/forward_grad_cls_lora.yml": "de2819f7eb9bcfc515b761474b0cba0656d771b1cd1570550655507372b3c28f", + "zo-bench/sweeps/SST2_opt-1.3b/forward_grad/forward_grad_with_q_number/forward_grad_cls_prefix.yml": "a7ae6c1c7a1b75ed124cf20709280b3508fa9542b541892afa9c6a378fa060ed", + "zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_ft.yml": "614f7e8ac17e7425c0faa4c282298dbcaee8ab91f34f3301184c7a52ebdbcd64", + "zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_lora.yml": "7cb8607e86439b022d403510eaab0f4ae31413954d8245e73292017c01e40d09", + "zo-bench/sweeps/SST2_opt-1.3b/sgd/sgd_cls_prompt.yml": "7dde2d249b27e428b1ce5c82f1d65d29e8476309c0d2277b6caec67e91c9394a", + "zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_ft_wjan.yml": "f229ff13ca44b96a7a081c0b56eb29e6a4f0cce6165be47e81ebe295181cd36d", + "zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_lora.yml": "6d75b378342a9da68904688124ed9ac07df2f86c8602d5ce53a38004b2beb480", + "zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_prefix.yml": "ee75cde67f316d5409ce520b067edfb7d1d6581284c9c9caffd848ff4b5fa41b", + "zo-bench/sweeps/SST2_opt-1.3b/sign_sgd/sign_opt_cls_prompt.yml": "3b8c5133ef03dc5dd68ad3ea2cfba05b9fd236f50341baea91947e2858298f61", + "zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_ft.yml": "bcadd0e8cb6ffdd1724b2dcbe5120d778f232cc9f438378a56853686939c839d", + "zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_lora.yml": "bf0d1c8266f2b18019d2a240a3d9369e2e04581c49270df2755fc038e3ce6459", + "zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_prefix.yml": "1a62d5a7a129f8cd9581aed9ba05b7b1ff908f049f3631c0d13727294d507685", + "zo-bench/sweeps/SST2_opt-1.3b/zo_adam/zo_adam_cls_prompt.yml": "619f467e5fc81352ef77e9859906e3fc531442fc86a87d522cb2b92d40fc685b", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_ft-ablation.yml": "9efa2a90ad483a21542da5ecc5b73fa184f02a158eeef37b6b9115829324be88", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_ft.yml": "0f9abc2bf72bfea6e7de202530f3da8fede22f4d729b10f7e1808a97574ef069", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lora.yml": "6ce7801d1f3a951a627472f849611dbc2bfe4b156bdcc031604967b92ee896bd", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lp-ablation.yml": "345ca79059be6e7684ba0e3552b27174f646ab67b8033d588c5c11416176ac19", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_lp.yml": "86f7589901c105ae1f90a98ee312b791752f74fdfb97e040c4156c2d22aac21c", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_prefix.yml": "a700e93b69f01f0cb6525ff51716b45329fe8ba2a4c272467d125cc2eeac786b", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_cls_prompt.yml": "d15b4fd8d4af3c3ba5a378022272703cc6d3b7891e4000a39df7f5fecc2929a2", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd/zo_sgd_squad_lora.yml": "ffe68d57f6ceaef3b522827d67b7ef84588f4ae66ce363bd707e7edf2a57a942", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_ft.yml": "53dfbd4ea3d4cc3691d7f2912bfa48bbc99e6ce290e0ecfd58b19b256d7eb4b2", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_lora.yml": "3141ccd441b1a5944ef750346e0e7dfed5049c27f8dd2c793421ea2f05298cda", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_prefix.yml": "ee7adc0c225ebaf28ef0d0e37c81aec63eed6ae16370684fe55b7f4d37921535", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_conserv/zo_sgd_conserv_cls_prompt.yml": "0ae298d88b132c8f7dd3c299edef53c0892775db585d0f8cdcf00dc178a01544", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_ft.yml": "622f3a8eaaa500bbbbdb06ac3cd289b056aa729fc402a2d202b4c3df07c218e3", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_lora.yml": "83d2fad7d00ec088d5b888bb767dd39f86b0a98b4ae9a1512b4bea5e4f795b6a", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_prefix.yml": "9184bdf082b0eeb29d0aab7d66ee3d1e3372bfd785809ec4cbe1445bfc9bd1e9", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_momen/zo_sgd_momen_cls_prompt.yml": "d8c421822e90e1638087b0b8a2e40df3377619ad68e25c85772a2a79aea236ae", + "zo-bench/sweeps/SST2_opt-1.3b/zo_sgd_sparse_grad/zo_sgd_sparse_grad_cls_ft.yml": "869993c63b4e41f7e2bb6a04f06ca86aaa3d6a5f6d62ef6a79d4c6733d258efc", + "zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_ft.yml": "d154603921d9b78a59010771b27eeac8d94e6f300aad41961397057c479fe606", + "zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_lora.yml": "a9a0a08226f2147b80774618e116f85e52ae5729ea56453bcc478f10b73c52a7", + "zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_prefix.yml": "df6e2b2f77d70e1c6f942879c20d6cae265cb8da810d284cbc0631b3ded733e0", + "zo-bench/sweeps/WinoGrande_llama-13b/adam/adam_winogrande_prompt.yml": "4c5361f61a1bc41ef8b642fb80aa7dc63a3dffcd194f5ac1b1518ebd3491b5ac", + "zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_ft.yml": "a470dcf202255d6f4eaee7a59637d2ed2c25bc5a612f92be45d6f0ada319796d", + "zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_lora.yml": "653045f8b077c11a278e3e90750bcc46f5b947ed97309d176ca3a030a59b07fa", + "zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_prefix.yml": "b79867644ec3afca4b4129279055768988612131b6d8d9bb16e633be4535f110", + "zo-bench/sweeps/WinoGrande_llama-13b/forward_grad/forward_grad_winogrande_prompt.yml": "eff72fe978cf06e27f31eee6d0bcf66a691846e0477cc48d701bd558fffec162", + "zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_ft.yml": "17c1b734f309064720fe59e3c6bb440c781fd046a1359afa5faa67d503f409e9", + "zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_lora.yml": "774a6853e1ada0d9e7368433d4e800f8e78cbd8061631fb78b42bcf27fab6c38", + "zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_prefix.yml": "d79be26e61e542f09c99943d75ba679c0235cfc2bc2e5764726cb723dad36f94", + "zo-bench/sweeps/WinoGrande_llama-13b/sgd/sgd_winogrande_prompt.yml": "83526870caa6aea6fb84db9bb1b18a5b1a7af8378d5eea3531115edaf06d927c", + "zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_ft.yml": "830a80af59355abafc17da75f7e2abfd7f8eec13beaa0ed41eb2ba7727e488d8", + "zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_lora.yml": "1e341b6b9f03db3e003ee5c08550eff692291ac6decbdb57a99820eca2529e8e", + "zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_prefix.yml": "60c2db2d55749fe2f7201e1400e1bb527ebc8f4b94822e72742c7c9114a59c1c", + "zo-bench/sweeps/WinoGrande_llama-13b/sign_sgd/sign_sgd_winogrande_prompt.yml": "f53d6aec1b6d68142a82e12c7e52fb4f29467168c07a787cdd5538c2e1ad1789", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_ft.yml": "77925f9d1439dedf932471f3c748dfa8304071b708d92a86bc8a1f42e872977f", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_lora.yml": "181cefac665527fd12cc9ac12801503b15589bbd4c1da92e8119617098d914a3", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_prefix.yml": "ec62bd8edae4c013deec80c78fc94efbfa70f966f543b8c882da33a1610a97b1", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_adam/zo_adam_winogrande_prompt.yml": "375c8123ff0ae2009d7149555d659ad7c0de0f1abe3e80ba6e4797430e20e903", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_ft.yml": "84433d685c6b34ef21d4085a183277031cec5ae619d88419421b12564d09e8f1", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_lora.yml": "462d36560d8b674a3a56886dee075fc702bf0184eeb345972a3daa8cc4bc87e8", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_prefix.yml": "158390cf1e9816c562b7231cc5f880d87ddeea5566dda9b3e509a1f0df4e029c", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd/zo_sgd_winogrande_prompt.yml": "f9574a989e04de3d6630a912059b73ea3727a4213d3ce04fdaa7530b1ceeaf14", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml": "770a3f4bab63f4b1c732e080eed191cc5744ec58f73f3abf228ce86feacebeab", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml": "8d9517a68bcc9f89256588676bee008b2a5853e9055f25cc6a10d784b13c2a79", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml": "77e04e9b3e01809f7bcbe74eace266f97d833c2697ddb66fb4f35939fe41406c", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml": "2418d2635f7e580cf2a9fba02ba63fe308044dde02083af207129cb538af03ed", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml": "59b2f6c69b6d55a7243a4daa1e4d22b24afcaf02e59a946fb8b7d01725afbacf", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml": "684e7f58427d2c7a366ce40221d567810c98f3f131b7cd15a42de1dc379e5afc", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml": "af63339ef6fb219fd12a9c48b509bdd2f729a1998569f292d4b7520175a7e29c", + "zo-bench/sweeps/WinoGrande_llama-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml": "f7c4f649f203bf81db3bcee75e3ddca820fef98f2e541634db5c6280d6a9b761", + "zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_ft.yml": "6fb325334f62d302be21c0537edb3fd2beed9eccf31109d5510cc73e1aec6df7", + "zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_lora.yml": "cd40b8057d1eaf502a16831ef55be06abde975d279ed2304c2cd271b776490d6", + "zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_prefix.yml": "e09c0b8fafba6f026b26446e49ddb52e929e6a5f3c78862519d9dc4fafb194fe", + "zo-bench/sweeps/WinoGrande_llama-7b/adam/adam_winogrande_prompt.yml": "6d1a9799133f27e23608e6afd3ed68ee9ce85828379e80f1a448ecee39d8c9c0", + "zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_ft.yml": "f41ba94a26e89ffa390c616550bba2526b08bed3896c4a5aa105725e4d28b3b4", + "zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_lora.yml": "f5960ce0cf8c56820086b8eda53824641179711d84b6a6d44618494775411efb", + "zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_prefix.yml": "0b11ca39eaefca2841b57d810b93913b1f31e1d3fddfd4df9d0d44d4109c1bcb", + "zo-bench/sweeps/WinoGrande_llama-7b/forward_grad/forward_grad_winogrande_prompt.yml": "b7ef3078b504f319b22eb45e48b0c56a5b59f22f4ad70fddaa5856e88a73ae70", + "zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_ft.yml": "680a6d3a4b06ebaa6720834c9630e30450f4f9473ceaed1fa086a3db271e1837", + "zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_lora.yml": "85bd0b4b51521a68d84998898e88ef5f55296b106fb04a63c073629aa8c3a116", + "zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_prefix.yml": "8b28838218ad70f69dc6cd72670957e002f089a951dbd8be275529f3ce4fb2a0", + "zo-bench/sweeps/WinoGrande_llama-7b/sgd/sgd_winogrande_prompt.yml": "3adb8682b8aab28fcd8660aeae4768dfc53df8010454c7a004ec056c3bf44a0a", + "zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_ft.yml": "f0f22805d7d2012a70c89455aa292411511679854ba9168c701b1d7e5613edea", + "zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_lora.yml": "0c8a05b348d5eb17d7e7b3bb0dddd3b75c0ed6a9cb301b3d981cc2321498b577", + "zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_prefix.yml": "31c6e227daad8a81bf1f49f196e12c71eb141eb5c68189c3be12c93c9ee4e590", + "zo-bench/sweeps/WinoGrande_llama-7b/sign_sgd/sign_sgd_winogrande_prompt.yml": "98a832a00c34ec455e8c1a35e7213686ef608b6347efa02a2dba26aae9fac86b", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_ft.yml": "2f16efc20d4cec804701c2f5076a76fe882b4798902abfd698d647cdf92b7375", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_lora.yml": "91a77b556319d0555f16ae1f9b577fc29ea83d97bd16e1b011ffc294c7c7acd1", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_prefix.yml": "8925946cf95e8af75abcde018185d75c1e7d81908e560064191c1391205eadc2", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_adam/zo_adam_winogrande_prompt.yml": "5914478069df7e25e120f36f0e73680ffcf2c40401d69a86cfde8f7257a40bb0", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_ft.yml": "9c0a2f274ff23b7220739e02406b2db8d92eb182165ac3d7e7bf62c48a13babb", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_lora.yml": "cced6086289bcd2650a20566b648c20f98b60a5768146b1160da4c8b1df2cd76", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_prefix.yml": "20c0b3a740ba505d5e2a75f70a87dc5f32ea4aa86a39c6d558ba5a0d6d7d1815", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd/zo_sgd_winogrande_prompt.yml": "891f848b9e584a99f1bc6dc74dde51f7b59319d4183a387a61089ef82f162a58", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml": "a3f74eb4e0e3bac197fb55bd24d7338af5a1628b03df01ba17d72c3a82b400a2", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml": "c08df0b08fd8a25252fa2488c2f3eb3a22d4b046c5ff0ee1c02cd598c2944355", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml": "0c2197ba49d6af1022775108ca87775a214a374f96b34db2f6a911330e92bdc1", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml": "bc04d6535bc741e550b02bd7317f5011deb06e216d8633d3e780e381c07e5cf0", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml": "128314f65cf5d8454379fcff301416eafe0ba3ac651ab9498894b771bf0a06b3", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml": "588b10ba519fc9fb82b6579a7edb260aa1df0d85f5da058866075956e7efdc17", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml": "bb9e18a5ff180328415428014233662eda5f3b362bc3cd79b40e813ebdc85062", + "zo-bench/sweeps/WinoGrande_llama-7b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml": "209522626140999aad91e72207da52e4006d426cb2125fe94eff54f8f5aa3458", + "zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_ft.yml": "2f3bda994ded4946f770730fa20880cb285fa81cc9ce6e90a8e22ff5903dd25d", + "zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_lora.yml": "81f2c432f9f9bcba3b7ecbdde829b122ab1c427b1464151d5e242043bedca090", + "zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_prefix.yml": "beaf803338db7466c45d9026a585d27ce07a5abc500635a07a129cbd08e7f5a6", + "zo-bench/sweeps/WinoGrande_mistral/adam/adam_winogrande_prompt.yml": "e5dc7c471ceda128e56dfbb116bd73d0f471684443e2854f661bd459302bab6e", + "zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_ft.yml": "b2efc38d77ee7f82b4174785cc6f8ff4b6513ef95e4fb78a33e92b2f94c7dc76", + "zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_lora.yml": "0a68b73ce266c943637c412c8920702e7fb0ca25e766bec64bfd069f0b3e1d78", + "zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_prefix.yml": "6db3ca494f11396a3abde43d3897b0ae7d501bb135540001d69a01485ced425f", + "zo-bench/sweeps/WinoGrande_mistral/forward_grad/forward_grad_winogrande_prompt.yml": "27a3e0d79434cb8abf80e38965b0e06907cdfaf11bfec92c631d53189722da3f", + "zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_ft.yml": "29e83be56ef893004e18e3f6aa6d9a681d9b4a74d0a4cf612edd81f187b58cbc", + "zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_lora.yml": "8bc52f22010b6c268bd2935c1c93b15f3e37c79b201b758cd4233389707e354e", + "zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_prefix.yml": "16cba7a65cd942ef2ef70df7666b655ed2346814ce82530459c8d375971b59c6", + "zo-bench/sweeps/WinoGrande_mistral/sgd/sgd_winogrande_prompt.yml": "fd6f3eb4eeecc3f5b7dfdc97406735500c0108b2f222667c1ab3f25b0067d8a8", + "zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_ft.yml": "d743331461406eeeba1f6402e824b337353d27285021a1813909dd6aff0a7913", + "zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_lora.yml": "f8fb8ad3aadb072bd47cce77973cb8271e950c6d78ebb59747c946d5e94a9a6e", + "zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_prefix.yml": "078dd185b114d90dcc3031e169f0a2735004ecb0700439c57b5237bfa4b638e8", + "zo-bench/sweeps/WinoGrande_mistral/sign_sgd/sign_sgd_winogrande_prompt.yml": "5a93c0f17fd1fe0ec8afe750e3ee99e867981a045ebab867acd980e5265c317b", + "zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_ft.yml": "1fe37db87e5c1f30906549b3e9270848c572e4e3d87b578f7149b857067de47d", + "zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_lora.yml": "989ccc89733f49c0cfb2517c7140879375aa347025e8e062d80b3f457d7cdba0", + "zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_prefix.yml": "f6c000efd156df87ef70860f59965438389f4073ca405d292900039822bf0724", + "zo-bench/sweeps/WinoGrande_mistral/zo_adam/zo_adam_winogrande_prompt.yml": "1de92155801565ff3eeb7d9e053d1e501a554398a28011a856631f4d2ce37e3c", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_ft.yml": "f8cdec15c6f77126cbf66e9f66ab91d3c68309a96a71431ddcb9f2a739eb7455", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_lora.yml": "112d511ba0ce11bb59e307f7a66d0f16857857fa1fa1d816f55d3f744f87850b", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_prefix.yml": "94958fd649d620a52ada4ac4a427774c87277e4291c6dc24aaeb531a1091f50b", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd/zo_sgd_winogrande_prompt.yml": "ef5d41a52d54af3f2153fc537569578e8c7ea5ef1a6b4caf86ea3af902b5ead7", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml": "9046951d496e3f06323af43deec580a4d83f3903b54b26ed1db283b8e74c69c9", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml": "93359ae5402629ae43a3ca0d8c7bacb3b54cdef0a4d18283275425519d23fb21", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml": "4b362ed05170a12a7ebb4f615478ea2503e150d1216fdb93c2fe6db0fab10ec5", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml": "d25e6d246b4605a5986a0816d8b23c9d96770a1ca5de057a6b1346499ad8fa9a", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml": "9d451d05068620ce69e610afd8a99e8f45d3cd08a5caa6e34d6a42c29c6fe5c4", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml": "efc4b0256df2d9cbb4d73c43b607d61172183c14a0274b3dba296070d3d8418c", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml": "87bdd0a8dd1f8fb3b10473db3f110da2f8a04d2dd47b3af84aec122cdaf11d9c", + "zo-bench/sweeps/WinoGrande_mistral/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml": "616942f64324b9904681214d3b01d02f99b1e0dacee1f74cc9b0ba9531bdf11c", + "zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_ft.yml": "1c59437336179df6f2f9e5390a3df9df9b905f81f0554bcf7448b6af0720cfc7", + "zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_lora.yml": "3a55bc58f63d086d6fdcf6b66133c72104553487f6c4baec28a4acfec21703c1", + "zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_prefix.yml": "1acec7112b346750c0b741c7042100ffac84129bb3b293d767a8ee2d50dda334", + "zo-bench/sweeps/WinoGrande_opt-13b/adam/adam_winogrande_prompt.yml": "521541bd51a205790e97f0083034ae3d1bf003a241e991f880e6c942b6b5cd2c", + "zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_ft.yml": "ad195aecb534a7b25ade33254f56daba2b4b152fb0e01202ff26997216e86669", + "zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_lora.yml": "780f27a2dc2d3d29628ae8970c467dde7ebe5d35b446d182dc02ed8788962d6e", + "zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_prefix.yml": "1876823c3348d57854c21c321667eb745ef1e652f7d20624ebd434e7c727f579", + "zo-bench/sweeps/WinoGrande_opt-13b/forward_grad/forward_grad_winogrande_prompt.yml": "768bd7e8a57bb025c95937ee32f50ba4c6314bb28e035b1f58f89f067193118b", + "zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_ft.yml": "2950fe4b02dea7fcf5b366d3946fd8cdf13d22047a56c7ab9f6c231cb67c2a19", + "zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_lora.yml": "610afe0093b9f29d3608dabd412b31801da65597d29a7bfbf8abbb50bf06c813", + "zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_prefix.yml": "73683f9fea215bf3750bc1f764ef26f8f2b1c71429640003797ea041a0665421", + "zo-bench/sweeps/WinoGrande_opt-13b/sgd/sgd_winogrande_prompt.yml": "b0d0c2fffe5632141f1fb538e8d988e366094edf5c0051345538f2eecd6778bf", + "zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_ft.yml": "468c7f62c0564c238fc5c53e198b5ef8051a96de815f3865d4e6ae522f0c7cf7", + "zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_lora.yml": "12cbe551683dd3b05d4d770cb0dfdbcbec9ae09cebcb8a9214bd5a323ac26f0a", + "zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_prefix.yml": "1de5521a7069c95966e02230363c2edd832eff7d8bb4a366c165c4c030047555", + "zo-bench/sweeps/WinoGrande_opt-13b/sign_sgd/sign_sgd_winogrande_prompt.yml": "7f9d32aaaa7ab5a38f3eb18a2901e4403d3f48b1ada2b12c1b5c0c75eb3cac8a", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_ft.yml": "b5b3a2582f2b97375674a55da40eb70c9bd4942bf3630b4ee745d13486df7e8a", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_lora.yml": "627addffbde3e949bdd9cf8bf926fd0ce8215ec1ebc1e5aa9a778d8407aa3efb", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_prefix.yml": "96a03d942cb540f3e0d70b901298c1f99a0a5503b4f634df55f5ae88f00c3669", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_adam/zo_adam_winogrande_prompt.yml": "6f4e55ce61ca406c17e9ea0caf0e5a980710184b372cf88bf7853f368c53527d", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_ft.yml": "89a7a7cb441317ea847277807ce5765daeed0306499e6d04d47f36c8f10ee16e", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_lora.yml": "7a6384c269e8d844323010cf3c6a028e6fb6df1fd36547f6161477d0c3dd0d79", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_prefix.yml": "dc50cc1542d6b2d1bbedd3114cf7b65363f62c2852781dadf53fad5b3c81cf04", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd/zo_sgd_winogrande_prompt.yml": "9b9043ca5af8f0ac02a8620164dbdb7210c885f2c80ac32567c0bd35c2203fea", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml": "582004e16a06b70e69b14bca792e04e98e1e340b73d9451ad7f711bc1a6e1934", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml": "bf53b9139cb6f1da949b9df252d118700b01c04eab42886416a54de8cff4c0a5", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml": "7c0ad5e912577d0824ce3e3be652c2ac91dd4d2ffb6fa86a80b88e6e08365623", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml": "104990757bf402e52bf7bab75d37d3e2c4de6fcc2acb22bc648d808fdbd839e3", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml": "dd86acf41eb6197e7bab8914621234d7bbf0fa345d9571a317ebba9cc55583aa", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml": "97dee431e6d30554e9d49f5479bc390b055ad703703a0739d6043982b2e3f3bf", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml": "4c2ec80f88a4971cd60494d22edd864f74ae57ae4ea6c901d0098626b7a6c0e3", + "zo-bench/sweeps/WinoGrande_opt-13b/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml": "f326f4c460215e8d48162fd0c5bd51727ecc47a35cf13834e63b2f49f7030008", + "zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_ft.yml": "709df1c1ec859558b8c614da85beb5058e167342e59ae26bd8e613dbad78d465", + "zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_lora.yml": "5b6e653bc4d57a61c9f7bb68f99b71e95e5259df8cc17e085b7aa54b600ff859", + "zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_prefix.yml": "55562fdde66823279d2f19c5f94255dca86f2dcd524458c580d84b015114deff", + "zo-bench/sweeps/WinoGrande_vicuna/adam/adam_winogrande_prompt.yml": "9903833f5771de0b8f35daa8ecf6da4a1d92bfbf19cbc0dc6c2ec27440108a82", + "zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_ft.yml": "32910e9781a0dfb33bd28025bccbad594d8e060171a434ec36af80e82a14d1b3", + "zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_lora.yml": "429c12b5fed15df2a9e8854c5bec9ce8681b5f60e231af0bc4d3da33ee30a950", + "zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_prefix.yml": "e20ebe4cb585fa0436164c9a178a389fae4657867e172550c9f002450e29f934", + "zo-bench/sweeps/WinoGrande_vicuna/forward_grad/forward_grad_winogrande_prompt.yml": "c54a362f99aa21aab680e0cfd0fcdae8fa05729aa41e74124047c261f9f73698", + "zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_ft.yml": "060eba249305f24a85524dd3b91feca710e8e138bf46cb1105f269a7f62e4530", + "zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_lora.yml": "786c5224aeb9cbe1426adad7c2f980c79aef12a15ed7d2b1f27dfffd78a29b3e", + "zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_prefix.yml": "00bcc05364630c661bd36409cce9a4666b73313e884d3c779c80289426d9a749", + "zo-bench/sweeps/WinoGrande_vicuna/sgd/sgd_winogrande_prompt.yml": "52b83e48b3da6163ad64163c38b70d9de9176d8f96b7ce8cf8a64535e14efcd6", + "zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_ft.yml": "c7033ad9c3bd8c787a4c83936a6226110bea293dc3602ea352428994e8810b66", + "zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_lora.yml": "69d18600ffbabe954d10ba34b2b9505d885b380dabdd163a336f8f7f4145561b", + "zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_prefix.yml": "d3983d87c499a745c5bd17bc05ec91c062dbbfada2a5f72c41c8adb0f53452d2", + "zo-bench/sweeps/WinoGrande_vicuna/sign_sgd/sign_sgd_winogrande_prompt.yml": "5abf0c3a1909795e399439a732b23d34759a5102a576595b994211f63a6f68be", + "zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_ft.yml": "5e1dab6ed08146da5c546324d07c22cb3a238b0fb30e4fa534fd015bb80c8671", + "zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_lora.yml": "21bb7ae9b484561615134b738e556fbdddef3171060a4be2c370c599c1fdca43", + "zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_prefix.yml": "1ad4ca5f6f3c0ec1b0d28d759eb4a7d5a559b9aaa6bf7a09db7f6139b3afd545", + "zo-bench/sweeps/WinoGrande_vicuna/zo_adam/zo_adam_winogrande_prompt.yml": "3a5b765e28e12eb9437c9d44c9f7c66c4502a7e04b736c17e220fca71c8eb178", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_ft.yml": "87e27d8b7977e088572dd60bb290df530185400d9206e2bb2d4cb37a7a849cfd", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_lora.yml": "27d487b656c5847d3f7cc517f7b4cf2e464253a79f163d70e8cb739ab88cd060", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_prefix.yml": "5630a91107f90e905e954eb694ddb5637ed9b6a72b9e3dde56e6213592bc9288", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd/zo_sgd_winogrande_prompt.yml": "8b30a8e1622d786122231c7aed5438ca4aa2f21b8b477735a76a3e08e217d786", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_ft.yml": "1da0ada076d1475d97cfda8746464f88cd9d1f88d0934267ac82a43e9681af05", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_lora.yml": "859528dc1ac072ef732f05f6b0a0b63b10e81c340940febab2ea30169242dd16", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prefix.yml": "2b343b4146deeac2f88bf48c124968aa77df17792aa904ea1696095138e4cd33", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_conserv/zo_sgd_conserv_winogrande_prompt.yml": "78f36f2cebc290970ebfcf870b4ca3269c6686e4fe26da0590bdf98e227a203d", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_ft.yml": "8439a4eab951adb2992a9db5f731a97ee2a90111ef513517cb6168532b8ba374", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_lora.yml": "0046bdb149a54a25fed585c87d5c7b016b7ab9487ea5d35d863b7dac240292c8", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prefix.yml": "87f2b35f1e3e3856f6a975cdc1879939808a863ea211095b8d37c1591af546d6", + "zo-bench/sweeps/WinoGrande_vicuna/zo_sgd_momen/zo_sgd_momen_winogrande_prompt.yml": "29c38cde899cdc35f151ec7ef9313cce9a7fe1721e93e34ca39e6cadb135ed7c", + "zo-bench/tasks.py": "9e0a027c32bfe0f2f0400e15e21e148f782893db9e7b4b32c9059692adbd5a55", + "zo-bench/templates.py": "8abcf572bbdb9bbae97cda60bb5bbb36a64cb699aed7e7038335eb1b76f6ef15", + "zo-bench/test_fake_text_memory.py": "1f1e241f49d604b70dfac48782086407fb5762f549d5116bffbefb7ab5f17566", + "zo-bench/trainer.py": "b98537921bba51274016d1aaab2072556ec6122ca09891f2822d96f17164d6c0", + "zo-bench/utils.py": "7365816fa7a90fb32f2ba52e2fd9696e72306282b5c63a3fba42f896e27c0ef4" + } + }, + "loren": { + "commit": "b80a32bc394332d1a1f115f41dfb5dcf7b326d37", + "files": { + "LICENSE": "fddf6ddbc5c8008c05f4f5f19cecc52423f44fefa6ebf5231c0bb26f7965dda4", + "README.md": "ca1c43f600e420a9b4b3cc575141bef453b1600bfbd208765b5e1fda1bbd787d", + "common/__init__.py": "beba3e6631bad6be89c7b73794933985e397ef06a9801dbe44743c966aaf4aeb", + "common/alg_utils.py": "d2b84832ae51f1df86b84f97e4ebdf7a1375e754a231df6c212ed61e47bb0d38", + "common/hessian_smooth_scheduler.py": "608b1715d0a336649e8c50d22f63af7186af15a6cd518e86cee11cbca144faf8", + "common/logging.py": "c3fb0c2eb7e2867aff876a4c19e643ffa9e5cbbfac06225d7d1317e591a73288", + "common/utils.py": "f522c5f122fa1d04849e35d2709aa7213a2fe049f85388260917dc10e43ac09e", + "dataset/__init__.py": "9848f9d25a78644df32145d5f11a5f68d0492d6087ff7e15edb38671cecf1faa", + "dataset/glue.py": "9a71c7715067832db8d321fff4c02b8c4ddc21723a79c1861fc9972cb4d477c6", + "dataset/mezo_dataset.py": "1c9e4be31faf27695967e731cd3502abc8ee7a034ee5ab1adfc21d275b9013c8", + "dataset/superglue.py": "5ebec6b5c20098166d7895dc6856eaeed6059f38c031d92e33701fba47c2bb58", + "figures/gpt_qnli_acc.png": "82d7b60bc490f1f67206321b0ecadb8e876d4c8a2cc53a85629204950c595129", + "figures/opt13_cb_acc.png": "6c237a9ff2b1c9b76816245802bef363b70736f7f6e5a1a59b6cb4437dd00cc8", + "figures/opt13b_train_loss.png": "fef6cf53089645b6911dbb5d53394f396134c471bd584860cca1ccb3be11ae15", + "main.py": "605c4725c85f67233d1c14926b2ba3a988f2642f9b8f35228106351c3dcdbc10", + "model/__init__.py": "0148d1b15841439c2afd019e5bc94671add1f4ab2d4843d7aebb7f6bd06918ff", + "model/glue_transformer.py": "6083f3711cb118572cd6d11f358bf1b3ac8cb470841fa05f192f75b230fb8a5f", + "model/glue_transformer_adam.py": "01a0e3294e0330dded4f5596e5620e86d57f55ff85841b9a5c94106e0ba4c0de", + "model/glue_transformer_fo.py": "1092713190f99e4d4f60dbd12dc18d43d3fd7193d9dff97f5823ed364cce72c0", + "model/glue_transformer_hizoo.py": "ed589999a978afa0be87c0b87bd5b56bf653ec0dd638015fbbb2e7d70cbbfa8e", + "model/glue_transformer_loren.py": "7685d8ec677b6fc6541c82359e6af76f330dc15f1f0673f390a47b3d594f4b9a", + "model/glue_transformer_lozo.py": "0c67f99325a1ad30348865b84d418f5a866cb3c284d54f9fa693f3021b8bf750", + "model/glue_transformer_mezo.py": "94af563ad45d02bf236a0aaf2859c453d17a28da4d8098a2564927e9d9d50e44", + "model/glue_transformer_svrg.py": "089d401c7c78e9036e06965fb041f1cb340c41c14bb5b57c91eefbf97f7a1fdd", + "model/opt.py": "cadab0f420ce8debb0f6d6ae2379442b734ddd0216163e5f256cc0b42850914f", + "model/prompt_finetune.py": "7fec1c8b434184fb94b4038a5ee0d84b3eff1da45d3b87db27e74f586b4431d1", + "model/roberta.py": "b89f606957cef1ced7580489e48509c85fdad2248b82fb5d2763de15f6851a80", + "requirements.txt": "45401bb73b1b573023c874e07eb150eb1d27873a754f16bd7c9d6c4e1ccf8461", + "trainer/__init__.py": "82a220241254c0ed04c513ea286afd732498cd880dfc5c5a9e78a76ec5bf0217", + "trainer/train_loop.py": "62767ad36b758cad43d0f3e26f27b2b537d7fe5495c82a4e64f4bd917f77cabb" + } + } +} \ No newline at end of file diff --git a/uv.lock b/uv.lock new file mode 100644 index 0000000..78ac7c7 --- /dev/null +++ b/uv.lock @@ -0,0 +1,1365 @@ +version = 1 +revision = 3 +requires-python = "==3.13.*" +resolution-markers = [ + "sys_platform == 'win32'", + "sys_platform == 'emscripten'", + "sys_platform != 'emscripten' and sys_platform != 'win32'", +] + +[[package]] +name = "accelerate" +version = "1.12.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "psutil" }, + { name = "pyyaml" }, + { name = "safetensors" }, + { name = "torch" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/4a/8e/ac2a9566747a93f8be36ee08532eb0160558b07630a081a6056a9f89bf1d/accelerate-1.12.0.tar.gz", hash = "sha256:70988c352feb481887077d2ab845125024b2a137a5090d6d7a32b57d03a45df6", size = 398399, upload-time = "2025-11-21T11:27:46.973Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9f/d2/c581486aa6c4fbd7394c23c47b83fa1a919d34194e16944241daf9e762dd/accelerate-1.12.0-py3-none-any.whl", hash = "sha256:3e2091cd341423207e2f084a6654b1efcd250dc326f2a37d6dde446e07cabb11", size = 380935, upload-time = "2025-11-21T11:27:44.522Z" }, +] + +[[package]] +name = "aiohappyeyeballs" +version = "2.7.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/f4/eec0465c2f67b2664688d0240b3212d5196fd89e741df67ddb81f8d35658/aiohappyeyeballs-2.7.1.tar.gz", hash = "sha256:065665c041c42a5938ed220bdcd7230f22527fbec085e1853d2402c8a3615d9d", size = 24757, upload-time = "2026-07-01T17:11:55.501Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/43/1947f06babed6b3f1d7f38b0c767f52df66bfb2bc10b468c4a7de9eceff2/aiohappyeyeballs-2.7.1-py3-none-any.whl", hash = "sha256:9243213661e29250eb41368e5daa826fc017156c3b8a11440826b2e3ed376472", size = 15038, upload-time = "2026-07-01T17:11:54.055Z" }, +] + +[[package]] +name = "aiohttp" +version = "3.14.5" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "aiohappyeyeballs" }, + { name = "aiosignal" }, + { name = "attrs" }, + { name = "frozenlist" }, + { name = "multidict" }, + { name = "propcache" }, + { name = "yarl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/6c/4c/bdccd81e9ee225b69c60e7766c9a5b05364f118f4d383713b89a682d772d/aiohttp-3.14.5.tar.gz", hash = "sha256:5558a7f5a05af9ecf744af91e5baefc436f93c9333e656c27ec253f9a6bbe178", size = 8078052, upload-time = "2026-10-11T01:05:12.408Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d3/e1/2841e020ebb7aefae5513586193e011e06313d9a6bdbd296622afbbce204/aiohttp-3.14.5-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:9ad7e6aa38c20da1be697874349c4c273c8a03b7887169665081706398d0439a", size = 538932, upload-time = "2026-10-11T01:00:54.3Z" }, + { url = "https://files.pythonhosted.org/packages/f7/a6/7fb8ea8fe96bcc7b7c7a36d10f021d99d01a8dc8a4b3f0ddacecfad9a80e/aiohttp-3.14.5-cp313-cp313-android_24_x86_64.whl", hash = "sha256:f59c7673465908cbe506117176156c127f29f917677afceada34957179221d91", size = 553329, upload-time = "2026-10-11T01:00:56.442Z" }, + { url = "https://files.pythonhosted.org/packages/de/64/d056e3c27647dc25af1a592cf356245382ea7c808171b9dac7677afedfc8/aiohttp-3.14.5-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:1b5416552740edf07234cc9437d0706f2acb67b93c198670b1a68e1b2b587dec", size = 521367, upload-time = "2026-10-11T01:00:58.345Z" }, + { url = "https://files.pythonhosted.org/packages/3e/e4/95226147e11d4db916fd1d495dcf85af8e3816e38333e42718241196e848/aiohttp-3.14.5-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:43351bdb5e4c3cb7d1772368e988534e869a74db7778079a83782c11c69535c7", size = 528322, upload-time = "2026-10-11T01:01:00.211Z" }, + { url = "https://files.pythonhosted.org/packages/17/cd/1d3c9192cafdb51cad62b2d3ded96cff9cc8af51893210aadd448a325389/aiohttp-3.14.5-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:c8c4478bef6d57fcfda15dae461ea3c9f06aa7b257c58df3f2300174ccbb185a", size = 539874, upload-time = "2026-10-11T01:01:02.06Z" }, + { url = "https://files.pythonhosted.org/packages/f6/0c/dfa33aecc7d4d1dc75e05248f5eac5a0edf4d09e7b44d93ab62529b0c1db/aiohttp-3.14.5-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:c2c30484dd1417ef98b51021ffa2cc0d7f3c78918adaaaab7e70817335ab3e02", size = 813836, upload-time = "2026-10-11T01:01:04.01Z" }, + { url = "https://files.pythonhosted.org/packages/33/17/4a63738052d20567d55529d6daa1b9480d906fd52930fbcf6d3fbed618f0/aiohttp-3.14.5-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:dab9ac5a67c8d1f070c00fa8fccb7cbd1b8dcc1a8d6b42f37540df9b3d4cc603", size = 548070, upload-time = "2026-10-11T01:01:06.035Z" }, + { url = "https://files.pythonhosted.org/packages/15/e5/b57e58695a757fd4c02497c033fced96a69c631b13866c43d336530c9670/aiohttp-3.14.5-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:e1cc2bfaee8c214f06080a7c7d5772419b8a1108e8e5349236189811823fb02a", size = 545786, upload-time = "2026-10-11T01:01:07.817Z" }, + { url = "https://files.pythonhosted.org/packages/9a/68/8c2c67a3aedf46e00f3c42f04fbc6983de80d4ed5786151e33681ba45883/aiohttp-3.14.5-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:74efb69332b85675b1eabd760a8cfc2e2cf42c60607c66f88014c1bdfb40942d", size = 1886492, upload-time = "2026-10-11T01:01:09.834Z" }, + { url = "https://files.pythonhosted.org/packages/ab/4b/74aab5e8d28c62e8f795b4fe8f38cf5586fd264a9a27bd2141ef6490333d/aiohttp-3.14.5-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:42b5e616946dbaf505e2bff18c9af2cd4ef9e7ef300ee58a6e951a5b7cf147ae", size = 1870057, upload-time = "2026-10-11T01:01:12.045Z" }, + { url = "https://files.pythonhosted.org/packages/a8/f7/eafc3b1988302b1815d9fd4a21071be5c360d616c0a430d02fd92dc97688/aiohttp-3.14.5-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f9033b43f511f27547c557dcaba0177649e10a3725336ccd2cce0fdc1dc4850d", size = 1925119, upload-time = "2026-10-11T01:01:14.09Z" }, + { url = "https://files.pythonhosted.org/packages/a1/04/78d8f294f74dd570f3898ff20402349fce524176045df98ba727d6846a68/aiohttp-3.14.5-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:15a310d3c71398e3d7bfc93a1a73fbe664315cd9e9016b8efc1cff85eeab7155", size = 2053137, upload-time = "2026-10-11T01:01:16.344Z" }, + { url = "https://files.pythonhosted.org/packages/32/51/395d225ef36f5a50d8e548dcd3141bfdbcd31fb6eed859022c573d2c4d66/aiohttp-3.14.5-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:1ffa3a523a36d8628f98c06492ae16a31a23d14c0b4ec721757b477319f656d6", size = 1911038, upload-time = "2026-10-11T01:01:18.653Z" }, + { url = "https://files.pythonhosted.org/packages/ff/a4/2aec1aa06d82e8a244843b5dae31d78061e5e76744270a86dd0ee051c889/aiohttp-3.14.5-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:5fb6a6e919bfb703227bc1ce6579281b84b1a2ba57deb9794dfdbec7dcd1e40c", size = 1702205, upload-time = "2026-10-11T01:01:20.904Z" }, + { url = "https://files.pythonhosted.org/packages/16/27/6051bfde7b6f418f70edd60d655fa426abb3355fa0981764739d87ecf160/aiohttp-3.14.5-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:43e1b7994a8b038125f722bff07492ef501110722c2727c408995d9fb864c421", size = 1848588, upload-time = "2026-10-11T01:01:22.918Z" }, + { url = "https://files.pythonhosted.org/packages/9e/44/55efc06fc26c4e6e1c095f231b4c222bf2d86d64a8eebbc24b2bb5958ea8/aiohttp-3.14.5-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:5f3e96071686755d9cd3600c3880183eb94b012178e92746d68101800f0ed8a3", size = 1887540, upload-time = "2026-10-11T01:01:25.278Z" }, + { url = "https://files.pythonhosted.org/packages/48/dc/1502bfdc2a65760d386ac6a00090b0addaa8a3c9c60b3f8127fad3a9afb2/aiohttp-3.14.5-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:cd88b01f3d37b7a2a34f91d98f14720206f1ea3d540843fab2d649dd5fb91fec", size = 1895030, upload-time = "2026-10-11T01:01:27.316Z" }, + { url = "https://files.pythonhosted.org/packages/93/7e/44174bb6288264418c9eec07a5e35180969c0d5a796c7af544db3cb8a33a/aiohttp-3.14.5-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:f2ed8b64dc0c651c0f5a9c926777719770021251b8f336d97c4b80b660836ce1", size = 1693244, upload-time = "2026-10-11T01:01:29.39Z" }, + { url = "https://files.pythonhosted.org/packages/47/dd/b507d64e50db23888582fff08eda13998b12f9dea70c072edaac19218380/aiohttp-3.14.5-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:a9918e58faf62ba2c7147927d06057aec78f42475aff5048047ec47e7265a600", size = 1926308, upload-time = "2026-10-11T01:01:31.634Z" }, + { url = "https://files.pythonhosted.org/packages/98/4b/5b51b4f63e3f2793151f4aea49c48fe1e00baeb7cec9c7a206de499f8de0/aiohttp-3.14.5-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:42f320d4a5b00b9af0bddcfec5407dc6f2d9816f006b2f79ebbaa31f16895df3", size = 1888406, upload-time = "2026-10-11T01:01:33.715Z" }, + { url = "https://files.pythonhosted.org/packages/ff/13/d5e818a5eaba9f822016727299f41c0e1075799f82a6433ec508a93ab867/aiohttp-3.14.5-cp313-cp313-win32.whl", hash = "sha256:3ae800a20947e2c2e53088047d021e6bf7d51560cc49f6a0737a1f79d2e3a13c", size = 479970, upload-time = "2026-10-11T01:01:35.677Z" }, + { url = "https://files.pythonhosted.org/packages/8d/d0/8eca2c65aa467320990d78fb2005f38ed3588944280c39ff9deb6423fef1/aiohttp-3.14.5-cp313-cp313-win_amd64.whl", hash = "sha256:d05e94cdfe0d15d0206f970722d2554780ce562787b21b218b275447f8751319", size = 505985, upload-time = "2026-10-11T01:01:37.574Z" }, + { url = "https://files.pythonhosted.org/packages/7a/f8/4cdd65305d2fca14b886bea9ed2abb1fe726287872524e56e3d26692b47d/aiohttp-3.14.5-cp313-cp313-win_arm64.whl", hash = "sha256:f001b571ead90ca1770f1e616db255351a1703317f20374c361ef22f12c06d09", size = 487629, upload-time = "2026-10-11T01:01:39.477Z" }, + { url = "https://files.pythonhosted.org/packages/68/30/173960c42b05a6c59f7558e4b12a4b0d9ba376cf6aa9bde7f9e08a30ca8d/aiohttp-3.14.5-py3-none-any.whl", hash = "sha256:efc21a454892828368b11c2c780de0ff8bc991f73f6b99c6b66e56205470929b", size = 279517, upload-time = "2026-10-11T01:05:08.523Z" }, +] + +[[package]] +name = "aiosignal" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "frozenlist" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/61/62/06741b579156360248d1ec624842ad0edf697050bbaf7c3e46394e106ad1/aiosignal-1.4.0.tar.gz", hash = "sha256:f47eecd9468083c2029cc99945502cb7708b082c232f9aca65da147157b251c7", size = 25007, upload-time = "2025-07-03T22:54:43.528Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/fb/76/641ae371508676492379f16e2fa48f4e2c11741bd63c48be4b12a6b09cba/aiosignal-1.4.0-py3-none-any.whl", hash = "sha256:053243f8b92b990551949e63930a839ff0cf0b0ebbe0597b0f3fb19e1a0fe82e", size = 7490, upload-time = "2025-07-03T22:54:42.156Z" }, +] + +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + +[[package]] +name = "certifi" +version = "2026.10.23" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/fd/11/b524cbd9bbdaca58608e4cf4053fd463417549e1959fa8d3aa18319f9555/certifi-2026.10.23.tar.gz", hash = "sha256:a9895e6e2758b371e0545e321a3a8fd1fcfd9829ada8824a936dfb16aaaf36cd", size = 136225, upload-time = "2026-10-23T11:36:16.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/32/d1/a3652fe2c19134d0d15922177821d863cbd7e842d53a21bbe7e8e3a1b5ac/certifi-2026.10.23-py3-none-any.whl", hash = "sha256:e9b54de76e530bb6cf0ccd036787103acb58fd42ba930ea8bf948ddbaa2f61d1", size = 135082, upload-time = "2026-10-23T11:36:14.763Z" }, +] + +[[package]] +name = "charset-normalizer" +version = "3.5.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/33/1c/f41d4e74c28ab327ff3acd36053f7ea506c55872d7a90b0fa71aa3ab0c89/charset_normalizer-3.5.2.tar.gz", hash = "sha256:39de2a259fc954455c57274dc94c79d5842774e1247a016aff30bc0efed0f4ef", size = 172659, upload-time = "2026-09-30T04:39:23.398Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/34/68292d68512768591aaff07c59bb53ee31341c87759433a859c4641a50c2/charset_normalizer-3.5.2-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:ed905975ab14056a2e5eb1c376cb2e1ebc5396baf84163939c518556fccde9f5", size = 225946, upload-time = "2026-09-30T04:35:55.313Z" }, + { url = "https://files.pythonhosted.org/packages/e3/80/bee0b01b90ccd5322ae1d0abb33fab1bd95b7c2eadaf02aeccf22e04ee83/charset_normalizer-3.5.2-cp313-cp313-android_24_x86_64.whl", hash = "sha256:a66c3bc5ab1f0ff2164fc9965ddd611ff0802173f4b9d24554c563f6ab7e1d6e", size = 238619, upload-time = "2026-09-30T04:35:56.863Z" }, + { url = "https://files.pythonhosted.org/packages/78/6e/60ce52a85a7fd631ae8482ae6d74521014ca2f255892679484dc04d7ef56/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:d2374b62878abb00cd8309b32af6c0b715cd02dec0ca74ef12e5069bdc64144a", size = 206701, upload-time = "2026-09-30T04:35:58.639Z" }, + { url = "https://files.pythonhosted.org/packages/36/8c/71aafad23f971afc84c2b295bc0c560739ce1dac558aad9fec22e39f3639/charset_normalizer-3.5.2-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:d376bbd28b3a8999db1a103b3b388aee6f1ddeb3e51bc2172993efdcd86e064d", size = 210506, upload-time = "2026-09-30T04:36:00.147Z" }, + { url = "https://files.pythonhosted.org/packages/91/da/3c5a7798c046df7d2d68ad653cf5b6c5a8bfee225055a843c6f2f42aac1a/charset_normalizer-3.5.2-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:6045373d5a89a5ec71afde535db987ca28e76dfa276c2d4c818265b375d4b055", size = 366626, upload-time = "2026-09-30T04:36:01.77Z" }, + { url = "https://files.pythonhosted.org/packages/e1/16/710ac3de2ee354e2bd1a9c94efe45a2d27b5c6ad39b2d6a905be2c094b6c/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:849df64e889b2e17230d58410a03dba311a65b163508fd33679b2b737d4b7858", size = 244624, upload-time = "2026-09-30T04:36:03.389Z" }, + { url = "https://files.pythonhosted.org/packages/d6/39/45c7439f5b63d24f7d5b2a1d760f34af7628782d7144b4cc8ded45c2d4bc/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:15c44f7edfd477b06f517a5cc317fc1707edb9de2c865f43d4b6513907473234", size = 235731, upload-time = "2026-09-30T04:36:04.987Z" }, + { url = "https://files.pythonhosted.org/packages/4d/34/38f3154785ce92e9f56eb226f4d35bdfae6b008480dd055f58837a89c810/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a89012d6d5476ee112d20d998570ed58df2260a852afb1758809cd6900411d21", size = 270352, upload-time = "2026-09-30T04:36:06.412Z" }, + { url = "https://files.pythonhosted.org/packages/04/f3/859f74e7babc977705026b30593b3be04049632a522fb7000f83c033d747/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:0c951d5e6dd9c2ff60609476752bee49da4206adde960ebc247766937f72e718", size = 267393, upload-time = "2026-09-30T04:36:07.865Z" }, + { url = "https://files.pythonhosted.org/packages/4b/85/41d27f234b82e47c167a5f6c0f62501dc0c640585ff4aba79e08a390336a/charset_normalizer-3.5.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7218e8f32b0956cfcd048fd42d9d5779809745ca1d86113ca56f66e7ae1549c4", size = 254660, upload-time = "2026-09-30T04:36:09.248Z" }, + { url = "https://files.pythonhosted.org/packages/58/ca/5d1a997587febe5b26d8daffe363b5c1a091cece19828eec6502fd09c5ef/charset_normalizer-3.5.2-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:a19a731138fc27d5682277d3b9df22855cea1239bce7fcec5f78f42ef2d1f3c3", size = 249996, upload-time = "2026-09-30T04:36:10.73Z" }, + { url = "https://files.pythonhosted.org/packages/b3/1f/d1e78246f7ed60c8c8d606b4ac27f66ce49cc3e95f24893ccbeba9f77302/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:62603db9a7caa0802eaa28c1c46fecd7b3a263a774069c24c3c28c302448721c", size = 247028, upload-time = "2026-09-30T04:36:12.294Z" }, + { url = "https://files.pythonhosted.org/packages/8e/37/eba316edd4f0c4d3a5d945924c4eeeae59abac4056aa815d8a4268f863a2/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:b6856554c4f44d79fc2307d5768854310a8f0096e501c75637542c82292b0429", size = 240562, upload-time = "2026-09-30T04:36:13.887Z" }, + { url = "https://files.pythonhosted.org/packages/c8/8e/aaa037d40ca9ef045977f1a661048b1aa33f223adfce3452fe9be9f79d14/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:1bc0baf5ef96b6ede57d47f4b8fe4d9d84019c3bfcbeb20a41edc6a6ee341f1f", size = 271699, upload-time = "2026-09-30T04:36:15.41Z" }, + { url = "https://files.pythonhosted.org/packages/26/19/1c1c9f75974adf523b87f34b8a2adc5a435cd65916812bcbd0dfa45f9a29/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:56bc200a365efb37383b7852e4cc5898d3b2da5987289b543956cf8cad71018a", size = 252030, upload-time = "2026-09-30T04:36:16.839Z" }, + { url = "https://files.pythonhosted.org/packages/bc/90/0660ef18e18df0a4d2a1a0edff7dfbba42d4e50ef2425557a5bb7051f77b/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:2c9ad19a6cfcd5ea5c0d41161d22f9df1dcc277e9bef2751391334546a314c00", size = 268565, upload-time = "2026-09-30T04:36:18.468Z" }, + { url = "https://files.pythonhosted.org/packages/79/ba/57adc269824e8658f1a0f97a9e514c247445a9632b3419b97e0ba37f16dc/charset_normalizer-3.5.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e243bd13217235fc7290c621941c3f5cc8b66e4872495be821d7436ba2fb838d", size = 257627, upload-time = "2026-09-30T04:36:19.938Z" }, + { url = "https://files.pythonhosted.org/packages/9a/85/33abd4315c052d3d4f54c92b1ee49bfbc0dc7115a981e462a793b6d2ab87/charset_normalizer-3.5.2-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:a090bb2c68df85450502e3e20d665e3a5af9c65a84d6508ed477badd49166fd3", size = 143407, upload-time = "2026-09-30T04:36:21.376Z" }, + { url = "https://files.pythonhosted.org/packages/4f/de/6435e18d1aaa5d910b896d551411c96af1f42a0c56c29afc2016c61ccc2e/charset_normalizer-3.5.2-cp313-cp313-win32.whl", hash = "sha256:2b7b3bbfb4fe8ef40600792d762fbaa9057559f9d3fad209525b7a22b99e91fd", size = 183207, upload-time = "2026-09-30T04:36:22.776Z" }, + { url = "https://files.pythonhosted.org/packages/9c/76/b8ec57f4e9ee3253541abf95e4a462c0175fe8032dcd070f1f2421240942/charset_normalizer-3.5.2-cp313-cp313-win_amd64.whl", hash = "sha256:78456a747de8dc58360ffa581f30a002baf5aa28cb262536545e91f113ed7639", size = 206489, upload-time = "2026-09-30T04:36:24.306Z" }, + { url = "https://files.pythonhosted.org/packages/3e/60/c647c6ae47480221e875ea5d743ff94946f7416e3c69415ab772928e8d32/charset_normalizer-3.5.2-cp313-cp313-win_arm64.whl", hash = "sha256:11912e4bb14baae7c5d8791aa55ba0a3a03ec6729073307b0f57270abaa713d3", size = 195501, upload-time = "2026-09-30T04:36:25.846Z" }, + { url = "https://files.pythonhosted.org/packages/8c/ab/176fbfd5b64939c55d652366aa5b9ef1d767af207a3aa6ebeb0d226c484d/charset_normalizer-3.5.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:4275811936e2f06feff5e598fb42a1b7ae852da8e39605211892b56b81a34efd", size = 331815, upload-time = "2026-09-30T04:38:26.216Z" }, + { url = "https://files.pythonhosted.org/packages/7e/84/371eac6b30bdbcbf2d632a1a01809103459216fcaae61b8b8d922c1bfb8a/charset_normalizer-3.5.2-cp37-abi3-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:1c50fe28bbc2ced33386f298650d91218076c05420e6cbd790b913adc41659e7", size = 253276, upload-time = "2026-09-30T04:38:28.032Z" }, + { url = "https://files.pythonhosted.org/packages/43/6f/c4fbae58febff71709c51bc7e18fdfa55341dc382704740f9f0cbf03817b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d19fbd981a488e22cd04883659ca6b08f50b5974f9fd7c95655ef6a043e5893f", size = 241239, upload-time = "2026-09-30T04:38:29.732Z" }, + { url = "https://files.pythonhosted.org/packages/61/71/458c3f42164a07d0c5210798e9e704b39e540a6793b05aba67f3a35243a9/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:0fed1d06615f022ee3b13caf5e8b180cfea32bb2c5aded8a9d44277afc040f93", size = 231121, upload-time = "2026-09-30T04:38:31.462Z" }, + { url = "https://files.pythonhosted.org/packages/09/54/ab9e89367076f6331bb6c65c4bf14a5361fa5191cb6561bf534f18504e1b/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:838dcc90063569a0448120554591a1d6c4a4ffe11babf048908793154ab86ade", size = 260350, upload-time = "2026-09-30T04:38:33.239Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c1/061431ecc688d9d76602502cb57cc01e691e682c18f1beb45f9673b5bbd2/charset_normalizer-3.5.2-cp37-abi3-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2ce45c6627b22c47e390bc91a41c3d13032192e699fa0bea96e9671b373d69b0", size = 255430, upload-time = "2026-09-30T04:38:34.865Z" }, + { url = "https://files.pythonhosted.org/packages/8d/1f/20c8949f0676f7ab811abdeb7f4d7f1cbc6e61ff20bef08b44edeb092bc8/charset_normalizer-3.5.2-cp37-abi3-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:0774bf9bf620249fee3e0b8b9fd3065de213be30f3aa94ce2494b3b638949e26", size = 250612, upload-time = "2026-09-30T04:38:36.649Z" }, + { url = "https://files.pythonhosted.org/packages/2b/9e/46f2fa4c431fc98c4ae76a8cb5bdca54e0341e3cfc3fcfd8e82740250818/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:1db38f4c5496827c1a501846d64d14c3b80c7e6714e406cd7dc36a9899fa1011", size = 242083, upload-time = "2026-09-30T04:38:38.26Z" }, + { url = "https://files.pythonhosted.org/packages/bd/39/559be29a0c0f086e0bba6922babd38916cc5e0b58ced4de13ee01ea05508/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:304d8e4d493af723536393eee0c689eb7813f4a474c8b479dee63f1fdd98f621", size = 232738, upload-time = "2026-09-30T04:38:39.81Z" }, + { url = "https://files.pythonhosted.org/packages/ff/6c/387b0e4f756a282831c1d9fc6aeb6c51ca4507ca202767c8de15ce9b12e2/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_ppc64le.whl", hash = "sha256:9b7f416ff0978e2f2249330527f0ad6fa02f4932e6199692d3b52da2048c19e4", size = 260703, upload-time = "2026-09-30T04:38:41.346Z" }, + { url = "https://files.pythonhosted.org/packages/96/92/1fdf015f09ef449f50d3ac4b67c90887c9c318b727daa95cc4f866e6521d/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_riscv64.whl", hash = "sha256:01077390b03f7988f11d700a2194e69b119741a86b1a638b1db88891e3eced8e", size = 247622, upload-time = "2026-09-30T04:38:42.937Z" }, + { url = "https://files.pythonhosted.org/packages/dc/3c/8e7b8a5671ad5d433669fb2a76f1a0164df2d9b1718b0206bc2a16d840cc/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_s390x.whl", hash = "sha256:7e841fb9010836c992c9f12fcbd43a831de93a5f726fc1ccd8ca1d0268c5014c", size = 257500, upload-time = "2026-09-30T04:38:44.604Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f0/45b579df5cabc1d5d53ea1cc35e8437d3ca768c0acccc7041517cb6fbb32/charset_normalizer-3.5.2-cp37-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9cae88599c7219005d879f98e5ed53341e9a122af585e1091200358a3003d2a0", size = 255100, upload-time = "2026-09-30T04:38:46.289Z" }, + { url = "https://files.pythonhosted.org/packages/31/68/fdec18a343f5fb3f310588dd478b09ac4799e0b187dbade3a8cd776f03ef/charset_normalizer-3.5.2-cp37-abi3-win32.whl", hash = "sha256:01b0c0d2262a9e28e8484a278c7e1b5d650e3ac8cf2683d2967e25899f208bdf", size = 174499, upload-time = "2026-09-30T04:38:47.999Z" }, + { url = "https://files.pythonhosted.org/packages/9d/8a/b618149cc5207943a0242068d7a27897f56a62947b5a039085f2a22029f8/charset_normalizer-3.5.2-cp37-abi3-win_amd64.whl", hash = "sha256:9f56f72050826f63dcee7a7f55b0a77168cb3bfc553fd405e7f8f9ece75a4036", size = 200092, upload-time = "2026-09-30T04:38:49.707Z" }, + { url = "https://files.pythonhosted.org/packages/03/cf/4c66866fa9e2b1c78e3c911516d1de497a677b7ac60f1eceda74ce777ca3/charset_normalizer-3.5.2-cp37-abi3-win_arm64.whl", hash = "sha256:40ab6bffa02ae10a0581e6c198be7d2d8ca5c2a0c64e4ed3465d766df457573e", size = 294363, upload-time = "2026-09-30T04:38:51.312Z" }, + { url = "https://files.pythonhosted.org/packages/fc/ad/d07d7862a62ffa6d79d68074d14823243dd235a77c45262acbf6adeb28bf/charset_normalizer-3.5.2-py3-none-any.whl", hash = "sha256:b6b751274acb69d77b3323d6b7dbaa3c7fdfc1eb829b7eb61d262f32e1af9685", size = 68872, upload-time = "2026-09-30T04:39:21.828Z" }, +] + +[[package]] +name = "cloudpickle" +version = "3.1.2" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/27/fb/576f067976d320f5f0114a8d9fa1215425441bb35627b1993e5afd8111e5/cloudpickle-3.1.2.tar.gz", hash = "sha256:7fda9eb655c9c230dab534f1983763de5835249750e85fbcef43aaa30a9a2414", size = 22330, upload-time = "2025-11-03T09:25:26.604Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/88/39/799be3f2f0f38cc727ee3b4f1445fe6d5e4133064ec2e4115069418a5bb6/cloudpickle-3.1.2-py3-none-any.whl", hash = "sha256:9acb47f6afd73f60dc1df93bb801b472f05ff42fa6c84167d25cb206be1fbf4a", size = 22228, upload-time = "2025-11-03T09:25:25.534Z" }, +] + +[[package]] +name = "colorama" +version = "0.4.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44", size = 27697, upload-time = "2022-10-25T02:36:22.414Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, +] + +[[package]] +name = "contourpy" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/5a/a55177dd22553a277388e8a1b3220e92de91bacb28356cdc73caa240121d/contourpy-1.4.0.tar.gz", hash = "sha256:20156f5a1ac4f8ce02656e39a61e82164a3d359796dc8026f75b062783d500e1", size = 13323726, upload-time = "2026-09-11T19:05:05.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/8b/62a6eacea08ea0b6ab0159a7783df7ed421ff9c1ff58fef7c31f58fa5e52/contourpy-1.4.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e21d1d4a9db5b3a793649c7ab0ddb4697f2818929eec871a7b9c45fce7b2a1ea", size = 297330, upload-time = "2026-09-11T19:03:11.809Z" }, + { url = "https://files.pythonhosted.org/packages/3f/2f/103cdc5b7077cd569989d3ddb99ee3d4e96ee31bde8df2a6e426b2dc6195/contourpy-1.4.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:196759a3e4db60e1546167e361090ebb6d199aa3aafc9e34ea17a5ac3b23e814", size = 285037, upload-time = "2026-09-11T19:03:13.781Z" }, + { url = "https://files.pythonhosted.org/packages/bf/25/97001d1fdf940e6f5adfc592d4f5899fff95daf7dceead3988fe09987d2d/contourpy-1.4.0-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c0e07c691f3b3321913ed9b8161c50ea5f77fadd006f52f5e755359b0dcbfc5", size = 356675, upload-time = "2026-09-11T19:03:15.374Z" }, + { url = "https://files.pythonhosted.org/packages/a6/5e/9a7241a89e2f74402aefa2569e1349ad2750ff77823c04c788eaaedb7fdd/contourpy-1.4.0-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7f861af508fca2384eef392bc1d8377cfa349b2b854cb11b45d89c75780e2561", size = 406990, upload-time = "2026-09-11T19:03:17.44Z" }, + { url = "https://files.pythonhosted.org/packages/36/81/3a4fbbf6a806eada5453a6d16f6c7d96b9f4b3e57a3127368fb545986b8a/contourpy-1.4.0-cp313-cp313-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a03b32c2e7eda8b17757c022162c13c86f5c3d6f937dddf9ba3c3ff7b513953b", size = 407271, upload-time = "2026-09-11T19:03:19.523Z" }, + { url = "https://files.pythonhosted.org/packages/68/77/8f93ecbde1a4d11dfd460cd19a0c159f5487352e751fa87f5d78cc9db08e/contourpy-1.4.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f1219a8898523cba821085f2da8a1b962cc696325763f09d7f93538ba43b2d70", size = 384707, upload-time = "2026-09-11T19:03:21.208Z" }, + { url = "https://files.pythonhosted.org/packages/05/07/e5cdf94d68961ee464de6b4fedd3d2f666584f59ccd124bb1290597122ab/contourpy-1.4.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:20da2f86bfaed60dbba729fe738c8241b1dd22b6cf7e8cbbf30df290bd04ba28", size = 1356741, upload-time = "2026-09-11T19:03:23.621Z" }, + { url = "https://files.pythonhosted.org/packages/fd/8a/2301d07accb257ac08daeb631875fada06fedd019c20ff7b00ee07e9d211/contourpy-1.4.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6ced1670fafee703b8277ab1645072a226e74f167166eae146fb743916119b67", size = 1426793, upload-time = "2026-09-11T19:03:25.955Z" }, + { url = "https://files.pythonhosted.org/packages/7d/5d/a62648f06259d15c139b14eb8cf3c58fe53cb970a55f2bb77d1070e80a41/contourpy-1.4.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:abd0f7e51ecc52bf8c95713bd80b1c17c516a71fa391c54475308a4377903c2b", size = 117961, upload-time = "2026-09-11T19:03:27.713Z" }, + { url = "https://files.pythonhosted.org/packages/71/31/c5b7771ba6982f319ec90c0cf5c425b36891adfeee2d9f667f90b2d0c166/contourpy-1.4.0-cp313-cp313-win32.whl", hash = "sha256:510f7d93d94cf6ebf4e2cd0640bea16ab8affac7547230175b6745b596ce0599", size = 347438, upload-time = "2026-09-11T19:03:29.829Z" }, + { url = "https://files.pythonhosted.org/packages/68/c1/a59df0754bf83a6f3e153cc19d550a5b01f607e389b1c4d57f436f9139e0/contourpy-1.4.0-cp313-cp313-win_amd64.whl", hash = "sha256:6507a016976a75a15aee47809a34605de6244ccc056e6164bf9fb14b27eecad4", size = 234084, upload-time = "2026-09-11T19:03:31.657Z" }, + { url = "https://files.pythonhosted.org/packages/41/48/97224f5decb1efa5a610f912195deb45321f73ec9b9dac485cd6fe2d5a6a/contourpy-1.4.0-cp313-cp313-win_arm64.whl", hash = "sha256:423bd5f4b3f11d54a8c597234e513382e3454bb106b8ec7ae32ba4ed63f8d99b", size = 559559, upload-time = "2026-09-11T19:03:33.528Z" }, +] + +[[package]] +name = "cuda-bindings" +version = "13.5.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-pathfinder" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/89/94/e90cb85fbe77d6d9b0d3d3d60c0964a59e7fbcc5b21be64a2fda6aff9e21/cuda_bindings-13.5.0-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cf525b2c2113fdfd2b10899a3e5d280520e970aa13c6ca021e83d9d02f895ed1", size = 7388832, upload-time = "2026-11-05T12:06:11.458Z" }, + { url = "https://files.pythonhosted.org/packages/66/05/6a2ab20fefb584d469d2daaf9d8cb65661a8fe938b850cb2534c016f1ae2/cuda_bindings-13.5.0-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d47b6f6d0398f97c82e2525eefb02e7252848e48c902824f6a6b6467a5902894", size = 8385548, upload-time = "2026-11-05T12:06:13.46Z" }, +] + +[[package]] +name = "cuda-pathfinder" +version = "1.8.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6a/9e/08555797c979322def080814686417ea93f66d38f5c48ebab6867a85a21e/cuda_pathfinder-1.8.6-py3-none-any.whl", hash = "sha256:bf6b3b06323cf95a11d671818392da5da23ddbbb4dfc4b77ca10622783c25980", size = 62603, upload-time = "2026-11-05T21:22:51.229Z" }, +] + +[[package]] +name = "cuda-toolkit" +version = "13.0.3.0" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/c7/a79086a62c98befcdb8349656c6f114e2db3b8b2422f6e25c97a7f2a9a3c/cuda_toolkit-13.0.3.0-py2.py3-none-any.whl", hash = "sha256:d693caaa261214ddd7dbb60d68e71cbed884e68c2be7509778f3051da0b91c3f", size = 2512, upload-time = "2026-04-14T00:50:08.173Z" }, +] + +[package.optional-dependencies] +cublas = [ + { name = "nvidia-cublas", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cuda-nvrtc", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cudart = [ + { name = "nvidia-cuda-runtime", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cufft = [ + { name = "nvidia-cufft", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cufile = [ + { name = "nvidia-cufile", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cupti = [ + { name = "nvidia-cuda-cupti", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +curand = [ + { name = "nvidia-curand", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cusolver = [ + { name = "nvidia-cublas", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cusolver", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-cusparse", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +cusparse = [ + { name = "nvidia-cusparse", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +nvjitlink = [ + { name = "nvidia-nvjitlink", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +nvrtc = [ + { name = "nvidia-cuda-nvrtc", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] +nvtx = [ + { name = "nvidia-nvtx", marker = "platform_machine == 'aarch64' or platform_machine == 'x86_64'" }, +] + +[[package]] +name = "cycler" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, +] + +[[package]] +name = "datasets" +version = "3.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dill" }, + { name = "filelock" }, + { name = "fsspec", extra = ["http"] }, + { name = "huggingface-hub" }, + { name = "multiprocess" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pandas" }, + { name = "pyarrow" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "xxhash" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/1a/89/d3d6fef58a488f8569c82fd293ab7cbd4250244d67f425dcae64c63800ea/datasets-3.6.0.tar.gz", hash = "sha256:1b2bf43b19776e2787e181cfd329cb0ca1a358ea014780c3581e0f276375e041", size = 569336, upload-time = "2025-05-07T15:15:02.659Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/20/34/a08b0ee99715eaba118cbe19a71f7b5e2425c2718ef96007c325944a1152/datasets-3.6.0-py3-none-any.whl", hash = "sha256:25000c4a2c0873a710df127d08a202a06eab7bf42441a6bc278b499c2f72cd1b", size = 491546, upload-time = "2025-05-07T15:14:59.742Z" }, +] + +[[package]] +name = "dill" +version = "0.3.8" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/17/4d/ac7ffa80c69ea1df30a8aa11b3578692a5118e7cd1aa157e3ef73b092d15/dill-0.3.8.tar.gz", hash = "sha256:3ebe3c479ad625c4553aca177444d89b486b1d84982eeacded644afc0cf797ca", size = 184847, upload-time = "2024-01-27T23:42:16.145Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c9/7a/cef76fd8438a42f96db64ddaa85280485a9c395e7df3db8158cfec1eee34/dill-0.3.8-py3-none-any.whl", hash = "sha256:c36ca9ffb54365bdd2f8eb3eff7d2a21237f8452b57ace88b1ac615b7e815bd7", size = 116252, upload-time = "2024-01-27T23:42:14.239Z" }, +] + +[[package]] +name = "experiments-codebase" +version = "0.1.0" +source = { virtual = "." } +dependencies = [ + { name = "accelerate" }, + { name = "datasets" }, + { name = "huggingface-hub" }, + { name = "matplotlib" }, + { name = "numpy" }, + { name = "psutil" }, + { name = "pytest" }, + { name = "scikit-learn" }, + { name = "sentencepiece" }, + { name = "torch" }, + { name = "transformers" }, +] + +[package.metadata] +requires-dist = [ + { name = "accelerate", specifier = "==1.12.0" }, + { name = "datasets", specifier = "==3.6.0" }, + { name = "huggingface-hub", specifier = "==0.36.0" }, + { name = "matplotlib", specifier = "==3.10.7" }, + { name = "numpy", specifier = "==2.2.6" }, + { name = "psutil", specifier = "==7.1.3" }, + { name = "pytest", specifier = "==8.4.2" }, + { name = "scikit-learn", specifier = "==1.7.2" }, + { name = "sentencepiece", specifier = "==0.2.1" }, + { name = "torch", specifier = "==2.13.0" }, + { name = "transformers", specifier = "==4.57.1" }, +] + +[[package]] +name = "filelock" +version = "4.2.10" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a1/cf/05bcdacabdc0aec7dc8e19d76281bd82325df62dae3b6430e9ba57397689/filelock-4.2.10.tar.gz", hash = "sha256:fcc3c0cb8bfe7f4b3bb0e231c04b15dbad068cb3c2515f343d8fde4dce93bd5d", size = 670595, upload-time = "2026-11-09T18:58:00.54Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/90/5d0096a325aa0f83ba7a3968bfb485b67e32c947bdf9cd0fcb4b485be718/filelock-4.2.10-py3-none-any.whl", hash = "sha256:9479aaeb4db20b5a53e3da28493edd24720b66b8a0b84030aa56ccdf243d6857", size = 218040, upload-time = "2026-11-09T18:57:59.088Z" }, +] + +[[package]] +name = "fonttools" +version = "4.68.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/0c/b5/672312ae80ce8b8eb9779c56052a24c8f36652aa7293a1a420553bcf03e5/fonttools-4.68.0.tar.gz", hash = "sha256:73294e233070f71e2b3653b6bd8564af676d57f26d075761fb06d1ab2e4a7a5d", size = 3848583, upload-time = "2026-10-27T16:30:26.451Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/05/ae/e2d75b7f582c1cc018ab94b8bbfbad7ab501b340debfa256f48125cae3eb/fonttools-4.68.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:f15de48b82a816c72f358e772792801bd3788a156caa76e1806cb0aa8148cd61", size = 3141370, upload-time = "2026-10-27T16:28:41.721Z" }, + { url = "https://files.pythonhosted.org/packages/fe/80/73d5297441b42d42b64d91cd4fffdff1541fac6171b0aca0a167c26d1c33/fonttools-4.68.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:86d319a1feedfc75c8ff582d947b21fa1854e2829cb8cf9428784d750a05f1d9", size = 2633412, upload-time = "2026-10-27T16:28:43.612Z" }, + { url = "https://files.pythonhosted.org/packages/36/29/16501aa69a586b8e8f810d7be19584aa026a0bca46c598ac516cfdd2a31a/fonttools-4.68.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:04a4868dcfcc23f00bb033147d5afc1a118a992842644c3eb9da55467ab4fd74", size = 5435968, upload-time = "2026-10-27T16:28:45.651Z" }, + { url = "https://files.pythonhosted.org/packages/79/c6/4b44abbffa01f85d6d0f0b9325a712019b4e2e6208f999ac6846d8da1346/fonttools-4.68.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:08851f7d2b983412f490b73a7c56f17cbda1d4d85d2ad3f857564bf15b5d9475", size = 5418193, upload-time = "2026-10-27T16:28:49.238Z" }, + { url = "https://files.pythonhosted.org/packages/98/0d/15cffdf13e156bb75ee421eee319fa8c5fb91a48a9a3e84685bf786df5be/fonttools-4.68.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b6f7c5fabf5b1d9ca79f204664f2c3e2f8218e50aebc43e85e02df0b2d9cc313", size = 5378957, upload-time = "2026-10-27T16:28:51.889Z" }, + { url = "https://files.pythonhosted.org/packages/9f/18/174052f12611c1088b61eeaa4019a8f1aedbcb1e985c33ef8fbe0c1ba674/fonttools-4.68.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e3ecdb0b248cd0bf43100a8b3cb40f7b45d52ea4be8616edea5dea8fefe90229", size = 5536796, upload-time = "2026-10-27T16:28:54.445Z" }, + { url = "https://files.pythonhosted.org/packages/35/d6/892213f45f63565f3f7eca3bce484a6f52ab7f7eda61851f93b1be829d5e/fonttools-4.68.0-cp313-cp313-win32.whl", hash = "sha256:4da99b83ae17f531838bc750abf56164ff37e1543e8e9b2b5403548f50497ce0", size = 2479972, upload-time = "2026-10-27T16:28:56.749Z" }, + { url = "https://files.pythonhosted.org/packages/61/2b/6c6f578176edeec83c5e02b7e745c1c8029f8cec4e32b4898d2c573bb881/fonttools-4.68.0-cp313-cp313-win_amd64.whl", hash = "sha256:6ed796b220654b4d37ad20af73419ec7969b669dd678cab88afb602c5683a331", size = 2531658, upload-time = "2026-10-27T16:28:59.013Z" }, + { url = "https://files.pythonhosted.org/packages/3c/b9/7cc71534bc954346451003bf5c9c117af835aea681a13a2847222ccf19b2/fonttools-4.68.0-cp313-cp313-win_arm64.whl", hash = "sha256:cd4b0d00523cae1e5e1eaed1d2b85ef342cec000f58d0738e12b064d72a7bbc2", size = 2499695, upload-time = "2026-10-27T16:29:01.511Z" }, + { url = "https://files.pythonhosted.org/packages/35/74/4ea331ecc65ba05a58b1e4e8ccd604c8a15565f876dfbf93fc2a2ea2e22b/fonttools-4.68.0-py3-none-any.whl", hash = "sha256:d76f8fdcb6936f5e1045a0c9dd721a4bf11112e60d1e243bfa1d39f06a8b3104", size = 1248357, upload-time = "2026-10-27T16:30:24.389Z" }, +] + +[[package]] +name = "frozenlist" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2d/f5/c831fac6cc817d26fd54c7eaccd04ef7e0288806943f7cc5bbf69f3ac1f0/frozenlist-1.8.0.tar.gz", hash = "sha256:3ede829ed8d842f6cd48fc7081d7a41001a56f1f38603f9d49bf3020d59a31ad", size = 45875, upload-time = "2025-10-06T05:38:17.865Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2d/40/0832c31a37d60f60ed79e9dfb5a92e1e2af4f40a16a29abcc7992af9edff/frozenlist-1.8.0-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:8d92f1a84bb12d9e56f818b3a746f3efba93c1b63c8387a73dde655e1e42282a", size = 85717, upload-time = "2025-10-06T05:36:27.341Z" }, + { url = "https://files.pythonhosted.org/packages/30/ba/b0b3de23f40bc55a7057bd38434e25c34fa48e17f20ee273bbde5e0650f3/frozenlist-1.8.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:96153e77a591c8adc2ee805756c61f59fef4cf4073a9275ee86fe8cba41241f7", size = 49651, upload-time = "2025-10-06T05:36:28.855Z" }, + { url = "https://files.pythonhosted.org/packages/0c/ab/6e5080ee374f875296c4243c381bbdef97a9ac39c6e3ce1d5f7d42cb78d6/frozenlist-1.8.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f21f00a91358803399890ab167098c131ec2ddd5f8f5fd5fe9c9f2c6fcd91e40", size = 49417, upload-time = "2025-10-06T05:36:29.877Z" }, + { url = "https://files.pythonhosted.org/packages/d5/4e/e4691508f9477ce67da2015d8c00acd751e6287739123113a9fca6f1604e/frozenlist-1.8.0-cp313-cp313-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:fb30f9626572a76dfe4293c7194a09fb1fe93ba94c7d4f720dfae3b646b45027", size = 234391, upload-time = "2025-10-06T05:36:31.301Z" }, + { url = "https://files.pythonhosted.org/packages/40/76/c202df58e3acdf12969a7895fd6f3bc016c642e6726aa63bd3025e0fc71c/frozenlist-1.8.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:eaa352d7047a31d87dafcacbabe89df0aa506abb5b1b85a2fb91bc3faa02d822", size = 233048, upload-time = "2025-10-06T05:36:32.531Z" }, + { url = "https://files.pythonhosted.org/packages/f9/c0/8746afb90f17b73ca5979c7a3958116e105ff796e718575175319b5bb4ce/frozenlist-1.8.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:03ae967b4e297f58f8c774c7eabcce57fe3c2434817d4385c50661845a058121", size = 226549, upload-time = "2025-10-06T05:36:33.706Z" }, + { url = "https://files.pythonhosted.org/packages/7e/eb/4c7eefc718ff72f9b6c4893291abaae5fbc0c82226a32dcd8ef4f7a5dbef/frozenlist-1.8.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f6292f1de555ffcc675941d65fffffb0a5bcd992905015f85d0592201793e0e5", size = 239833, upload-time = "2025-10-06T05:36:34.947Z" }, + { url = "https://files.pythonhosted.org/packages/c2/4e/e5c02187cf704224f8b21bee886f3d713ca379535f16893233b9d672ea71/frozenlist-1.8.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:29548f9b5b5e3460ce7378144c3010363d8035cea44bc0bf02d57f5a685e084e", size = 245363, upload-time = "2025-10-06T05:36:36.534Z" }, + { url = "https://files.pythonhosted.org/packages/1f/96/cb85ec608464472e82ad37a17f844889c36100eed57bea094518bf270692/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ec3cc8c5d4084591b4237c0a272cc4f50a5b03396a47d9caaf76f5d7b38a4f11", size = 229314, upload-time = "2025-10-06T05:36:38.582Z" }, + { url = "https://files.pythonhosted.org/packages/5d/6f/4ae69c550e4cee66b57887daeebe006fe985917c01d0fff9caab9883f6d0/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:517279f58009d0b1f2e7c1b130b377a349405da3f7621ed6bfae50b10adf20c1", size = 243365, upload-time = "2025-10-06T05:36:40.152Z" }, + { url = "https://files.pythonhosted.org/packages/7a/58/afd56de246cf11780a40a2c28dc7cbabbf06337cc8ddb1c780a2d97e88d8/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:db1e72ede2d0d7ccb213f218df6a078a9c09a7de257c2fe8fcef16d5925230b1", size = 237763, upload-time = "2025-10-06T05:36:41.355Z" }, + { url = "https://files.pythonhosted.org/packages/cb/36/cdfaf6ed42e2644740d4a10452d8e97fa1c062e2a8006e4b09f1b5fd7d63/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:b4dec9482a65c54a5044486847b8a66bf10c9cb4926d42927ec4e8fd5db7fed8", size = 240110, upload-time = "2025-10-06T05:36:42.716Z" }, + { url = "https://files.pythonhosted.org/packages/03/a8/9ea226fbefad669f11b52e864c55f0bd57d3c8d7eb07e9f2e9a0b39502e1/frozenlist-1.8.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:21900c48ae04d13d416f0e1e0c4d81f7931f73a9dfa0b7a8746fb2fe7dd970ed", size = 233717, upload-time = "2025-10-06T05:36:44.251Z" }, + { url = "https://files.pythonhosted.org/packages/1e/0b/1b5531611e83ba7d13ccc9988967ea1b51186af64c42b7a7af465dcc9568/frozenlist-1.8.0-cp313-cp313-win32.whl", hash = "sha256:8b7b94a067d1c504ee0b16def57ad5738701e4ba10cec90529f13fa03c833496", size = 39628, upload-time = "2025-10-06T05:36:45.423Z" }, + { url = "https://files.pythonhosted.org/packages/d8/cf/174c91dbc9cc49bc7b7aab74d8b734e974d1faa8f191c74af9b7e80848e6/frozenlist-1.8.0-cp313-cp313-win_amd64.whl", hash = "sha256:878be833caa6a3821caf85eb39c5ba92d28e85df26d57afb06b35b2efd937231", size = 43882, upload-time = "2025-10-06T05:36:46.796Z" }, + { url = "https://files.pythonhosted.org/packages/c1/17/502cd212cbfa96eb1388614fe39a3fc9ab87dbbe042b66f97acb57474834/frozenlist-1.8.0-cp313-cp313-win_arm64.whl", hash = "sha256:44389d135b3ff43ba8cc89ff7f51f5a0bb6b63d829c8300f79a2fe4fe61bcc62", size = 39676, upload-time = "2025-10-06T05:36:47.8Z" }, + { url = "https://files.pythonhosted.org/packages/d2/5c/3bbfaa920dfab09e76946a5d2833a7cbdf7b9b4a91c714666ac4855b88b4/frozenlist-1.8.0-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:e25ac20a2ef37e91c1b39938b591457666a0fa835c7783c3a8f33ea42870db94", size = 89235, upload-time = "2025-10-06T05:36:48.78Z" }, + { url = "https://files.pythonhosted.org/packages/d2/d6/f03961ef72166cec1687e84e8925838442b615bd0b8854b54923ce5b7b8a/frozenlist-1.8.0-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:07cdca25a91a4386d2e76ad992916a85038a9b97561bf7a3fd12d5d9ce31870c", size = 50742, upload-time = "2025-10-06T05:36:49.837Z" }, + { url = "https://files.pythonhosted.org/packages/1e/bb/a6d12b7ba4c3337667d0e421f7181c82dda448ce4e7ad7ecd249a16fa806/frozenlist-1.8.0-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:4e0c11f2cc6717e0a741f84a527c52616140741cd812a50422f83dc31749fb52", size = 51725, upload-time = "2025-10-06T05:36:50.851Z" }, + { url = "https://files.pythonhosted.org/packages/bc/71/d1fed0ffe2c2ccd70b43714c6cab0f4188f09f8a67a7914a6b46ee30f274/frozenlist-1.8.0-cp313-cp313t-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:b3210649ee28062ea6099cfda39e147fa1bc039583c8ee4481cb7811e2448c51", size = 284533, upload-time = "2025-10-06T05:36:51.898Z" }, + { url = "https://files.pythonhosted.org/packages/c9/1f/fb1685a7b009d89f9bf78a42d94461bc06581f6e718c39344754a5d9bada/frozenlist-1.8.0-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:581ef5194c48035a7de2aefc72ac6539823bb71508189e5de01d60c9dcd5fa65", size = 292506, upload-time = "2025-10-06T05:36:53.101Z" }, + { url = "https://files.pythonhosted.org/packages/e6/3b/b991fe1612703f7e0d05c0cf734c1b77aaf7c7d321df4572e8d36e7048c8/frozenlist-1.8.0-cp313-cp313t-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:3ef2d026f16a2b1866e1d86fc4e1291e1ed8a387b2c333809419a2f8b3a77b82", size = 274161, upload-time = "2025-10-06T05:36:54.309Z" }, + { url = "https://files.pythonhosted.org/packages/ca/ec/c5c618767bcdf66e88945ec0157d7f6c4a1322f1473392319b7a2501ded7/frozenlist-1.8.0-cp313-cp313t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:5500ef82073f599ac84d888e3a8c1f77ac831183244bfd7f11eaa0289fb30714", size = 294676, upload-time = "2025-10-06T05:36:55.566Z" }, + { url = "https://files.pythonhosted.org/packages/7c/ce/3934758637d8f8a88d11f0585d6495ef54b2044ed6ec84492a91fa3b27aa/frozenlist-1.8.0-cp313-cp313t-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:50066c3997d0091c411a66e710f4e11752251e6d2d73d70d8d5d4c76442a199d", size = 300638, upload-time = "2025-10-06T05:36:56.758Z" }, + { url = "https://files.pythonhosted.org/packages/fc/4f/a7e4d0d467298f42de4b41cbc7ddaf19d3cfeabaf9ff97c20c6c7ee409f9/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:5c1c8e78426e59b3f8005e9b19f6ff46e5845895adbde20ece9218319eca6506", size = 283067, upload-time = "2025-10-06T05:36:57.965Z" }, + { url = "https://files.pythonhosted.org/packages/dc/48/c7b163063d55a83772b268e6d1affb960771b0e203b632cfe09522d67ea5/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_armv7l.whl", hash = "sha256:eefdba20de0d938cec6a89bd4d70f346a03108a19b9df4248d3cf0d88f1b0f51", size = 292101, upload-time = "2025-10-06T05:36:59.237Z" }, + { url = "https://files.pythonhosted.org/packages/9f/d0/2366d3c4ecdc2fd391e0afa6e11500bfba0ea772764d631bbf82f0136c9d/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_ppc64le.whl", hash = "sha256:cf253e0e1c3ceb4aaff6df637ce033ff6535fb8c70a764a8f46aafd3d6ab798e", size = 289901, upload-time = "2025-10-06T05:37:00.811Z" }, + { url = "https://files.pythonhosted.org/packages/b8/94/daff920e82c1b70e3618a2ac39fbc01ae3e2ff6124e80739ce5d71c9b920/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_s390x.whl", hash = "sha256:032efa2674356903cd0261c4317a561a6850f3ac864a63fc1583147fb05a79b0", size = 289395, upload-time = "2025-10-06T05:37:02.115Z" }, + { url = "https://files.pythonhosted.org/packages/e3/20/bba307ab4235a09fdcd3cc5508dbabd17c4634a1af4b96e0f69bfe551ebd/frozenlist-1.8.0-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:6da155091429aeba16851ecb10a9104a108bcd32f6c1642867eadaee401c1c41", size = 283659, upload-time = "2025-10-06T05:37:03.711Z" }, + { url = "https://files.pythonhosted.org/packages/fd/00/04ca1c3a7a124b6de4f8a9a17cc2fcad138b4608e7a3fc5877804b8715d7/frozenlist-1.8.0-cp313-cp313t-win32.whl", hash = "sha256:0f96534f8bfebc1a394209427d0f8a63d343c9779cda6fc25e8e121b5fd8555b", size = 43492, upload-time = "2025-10-06T05:37:04.915Z" }, + { url = "https://files.pythonhosted.org/packages/59/5e/c69f733a86a94ab10f68e496dc6b7e8bc078ebb415281d5698313e3af3a1/frozenlist-1.8.0-cp313-cp313t-win_amd64.whl", hash = "sha256:5d63a068f978fc69421fb0e6eb91a9603187527c86b7cd3f534a5b77a592b888", size = 48034, upload-time = "2025-10-06T05:37:06.343Z" }, + { url = "https://files.pythonhosted.org/packages/16/6c/be9d79775d8abe79b05fa6d23da99ad6e7763a1d080fbae7290b286093fd/frozenlist-1.8.0-cp313-cp313t-win_arm64.whl", hash = "sha256:bf0a7e10b077bf5fb9380ad3ae8ce20ef919a6ad93b4552896419ac7e1d8e042", size = 41749, upload-time = "2025-10-06T05:37:07.431Z" }, + { url = "https://files.pythonhosted.org/packages/9a/9a/e35b4a917281c0b8419d4207f4334c8e8c5dbf4f3f5f9ada73958d937dcc/frozenlist-1.8.0-py3-none-any.whl", hash = "sha256:0c18a16eab41e82c295618a77502e17b195883241c563b00f0aa5106fc4eaa0d", size = 13409, upload-time = "2025-10-06T05:38:16.721Z" }, +] + +[[package]] +name = "fsspec" +version = "2025.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/34/f4/5721faf47b8c499e776bc34c6a8fc17efdf7fdef0b00f398128bc5dcb4ac/fsspec-2025.3.0.tar.gz", hash = "sha256:a935fd1ea872591f2b5148907d103488fc523295e6c64b835cfad8c3eca44972", size = 298491, upload-time = "2025-03-07T21:47:56.461Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/53/eb690efa8513166adef3e0669afd31e95ffde69fb3c52ec2ac7223ed6018/fsspec-2025.3.0-py3-none-any.whl", hash = "sha256:efb87af3efa9103f94ca91a7f8cb7a4df91af9f74fc106c9c7ea0efd7277c1b3", size = 193615, upload-time = "2025-03-07T21:47:54.809Z" }, +] + +[package.optional-dependencies] +http = [ + { name = "aiohttp" }, +] + +[[package]] +name = "hf-xet" +version = "1.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/18/d91c20f815df6cc496a5d0ad8db6d274dad5c0cfcd59babfa2440a9aba44/hf_xet-1.8.0.tar.gz", hash = "sha256:10ed23b51dacf7917d64f335c25048deb470efa755e9989b218fc0531386138e", size = 1013014, upload-time = "2026-10-30T10:04:33.741Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/97/74/d89d5235524bc14d8519e12ca8bc5204f45009ae83d63a410f52c29eb4a8/hf_xet-1.8.0-cp38-abi3-macosx_10_12_x86_64.whl", hash = "sha256:e00d8f60170cd3dd55d98306e41dbaf28b27ff1bcfefbfa84279d197221be83e", size = 3875002, upload-time = "2026-10-30T10:04:18.958Z" }, + { url = "https://files.pythonhosted.org/packages/d4/f2/ef25e2085e92dcaeaa675331e443923aed2006f6fe2d984e15d8b8d40766/hf_xet-1.8.0-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:3e8934784425781f0f779b91044df441f3a7af4dab47375d7e3aeaecbb8eecb4", size = 3600947, upload-time = "2026-10-30T10:04:20.906Z" }, + { url = "https://files.pythonhosted.org/packages/f8/1e/1e8ecc05ef034e9a95c18ed32d2ec07905a7cd2ca611a9d88e25ee1f4850/hf_xet-1.8.0-cp38-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:29dab7c904cd1914a0439c6e1306c12c7497c8bd32290fbe563ebf51ca4b6d6d", size = 4292483, upload-time = "2026-10-30T10:04:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/35/c4/127a1548df019ea4c80f06e685f263e146075143335a02e78a3c41dbc4eb/hf_xet-1.8.0-cp38-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:8800e3444770f2c630b361bc6d5c6ebb770b7830646cf632fbb79d0e5bbc9e7f", size = 4069340, upload-time = "2026-10-30T10:04:24.664Z" }, + { url = "https://files.pythonhosted.org/packages/a5/d5/281cd82736c3e181e597588589d2204d3a5c388a464d4a2a8c546995bae9/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:a584a7b3268da62f23c3187cc7201ca01f7b610985a36b1b6119c66bccb0383c", size = 4272344, upload-time = "2026-10-30T10:04:26.519Z" }, + { url = "https://files.pythonhosted.org/packages/48/77/886f09e91a5eadb054ce03b8855323cd2a72f20db76ab4119e0ecda65eef/hf_xet-1.8.0-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:1ebaf248c9bef8bb0c9d1d8d71db1fdf0cac14f922cc7a936a81adbf12eb5f01", size = 4500689, upload-time = "2026-10-30T10:04:28.394Z" }, + { url = "https://files.pythonhosted.org/packages/97/4d/2c76a992b370ff77d0b5219275779f8c9a7dabb8ee649deb265dfed84d0f/hf_xet-1.8.0-cp38-abi3-win_amd64.whl", hash = "sha256:92188598dedc1e1f5609bd718d4db8687a6c89915553912571e2f587892eecec", size = 3911559, upload-time = "2026-10-30T10:04:30.165Z" }, + { url = "https://files.pythonhosted.org/packages/87/91/fdb1454a43eff8011047d176ada2f0fb4926cf3d74b87357ff35793f6d98/hf_xet-1.8.0-cp38-abi3-win_arm64.whl", hash = "sha256:42b66fdc688eaa4ff3eb77dc9275e5a0f1258ecc9fdd083ddaf43bb49bec925b", size = 3738458, upload-time = "2026-10-30T10:04:31.882Z" }, +] + +[[package]] +name = "huggingface-hub" +version = "0.36.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "filelock" }, + { name = "fsspec" }, + { name = "hf-xet", marker = "platform_machine == 'aarch64' or platform_machine == 'amd64' or platform_machine == 'arm64' or platform_machine == 'x86_64'" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "requests" }, + { name = "tqdm" }, + { name = "typing-extensions" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/63/4910c5fa9128fdadf6a9c5ac138e8b1b6cee4ca44bf7915bbfbce4e355ee/huggingface_hub-0.36.0.tar.gz", hash = "sha256:47b3f0e2539c39bf5cde015d63b72ec49baff67b6931c3d97f3f84532e2b8d25", size = 463358, upload-time = "2025-10-23T12:12:01.413Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/bd/1a875e0d592d447cbc02805fd3fe0f497714d6a2583f59d14fa9ebad96eb/huggingface_hub-0.36.0-py3-none-any.whl", hash = "sha256:7bcc9ad17d5b3f07b57c78e79d527102d08313caa278a641993acddcb894548d", size = 566094, upload-time = "2025-10-23T12:11:59.557Z" }, +] + +[[package]] +name = "idna" +version = "3.20" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f5/08/8eea9d4b8302028f3abb2c0813953f7aec26d33b7a8960ed760e65ff29fa/idna-3.20.tar.gz", hash = "sha256:a7db850025b95ded1eae8a46181a1a6c56c92c96f0e2b005d9ff8dc0210cab44", size = 216463, upload-time = "2026-09-17T14:11:04.752Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/58/a2/bb081bab032533a855d44de1d56f8e8426114ff1ba5d1f07a438a0a654f8/idna-3.20-py3-none-any.whl", hash = "sha256:ab7ae7122974553370f0bdb919e1a960b2cd1bc1ef0276416d896db81c14582c", size = 69583, upload-time = "2026-09-17T14:11:03.168Z" }, +] + +[[package]] +name = "iniconfig" +version = "2.3.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/01/e1/2069291243c926a2ff1cd706c7f3eeb9b62144bf60f77c9fb9ff2fb26bd3/iniconfig-2.3.1.tar.gz", hash = "sha256:67f4b9c50da0dedf52af349e7749a80a9057a5031199791b906c3bb3ae878960", size = 21209, upload-time = "2026-10-06T22:48:38.076Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, +] + +[[package]] +name = "jinja2" +version = "3.1.6" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "markupsafe" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/df/bf/f7da0350254c0ed7c72f3e33cef02e048281fec7ecec5f032d4aac52226b/jinja2-3.1.6.tar.gz", hash = "sha256:0137fb05990d35f1275a587e9aee6d56da821fc83491a0fb838183be43f66d6d", size = 245115, upload-time = "2025-03-05T20:05:02.478Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, +] + +[[package]] +name = "joblib" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cloudpickle" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d5/1d/537ab090f302b838943a1b56497dd53059b9a9b46a074936470173a2e207/joblib-1.6.0.tar.gz", hash = "sha256:2ccc96785b12046c08fd6d55839c12857831b54a3c1673ffadd2f04bfc4eda03", size = 327903, upload-time = "2026-08-31T09:39:04.122Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/18/53/84099323c2ec4be98d935f63c033ac4151ee83836ca1050ede3b3aadf155/joblib-1.6.0-py3-none-any.whl", hash = "sha256:3dbbf9f6e4b592a2357b854608e980fe6390d131d7a82f011a377ef2ebef7aba", size = 306115, upload-time = "2026-08-31T09:39:02.298Z" }, +] + +[[package]] +name = "kiwisolver" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea041ef5bba3ed21a003522fa088834b069b1909981f30/kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a", size = 104395, upload-time = "2026-08-28T10:28:27.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/08/c1/88018321d976f53c421e379c43bc6993e70ce0c8a3ec5edc4bfe102257f6/kiwisolver-1.5.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b6ae6a0328f0bc035741820fdeecdcd67bf4694eee03972e843663107122f450", size = 62272, upload-time = "2026-08-28T10:25:51.02Z" }, + { url = "https://files.pythonhosted.org/packages/85/d2/712bc17ea4f1d216034928069d612defbc6c95a471c55a7203a39faecb1a/kiwisolver-1.5.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:886fc26012f0e8b5f69d1cfe6d711f6b11f194621539bf8e6bb1c25c5dc82724", size = 64481, upload-time = "2026-08-28T10:25:52.22Z" }, + { url = "https://files.pythonhosted.org/packages/1b/e6/6c5380d676f43b6d918033962ea5e72360ca69e5a404154bc496b598ffdb/kiwisolver-1.5.1-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aefe930d113798330e9462f7874542977869c0613cba3262e2de3a8d5dee8f3a", size = 66260, upload-time = "2026-08-28T10:25:53.387Z" }, + { url = "https://files.pythonhosted.org/packages/92/6a/7087f5822cc8bb272679641404b1966a42504dac9ee74e2b33840475a0aa/kiwisolver-1.5.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:a5ca5aebae78a0bc13c1943af4af615d4966c5b650b05d5aa83b50e427196fee", size = 123876, upload-time = "2026-08-28T10:25:54.644Z" }, + { url = "https://files.pythonhosted.org/packages/5c/4b/9f385087ca09ee5ab9c09c6832561a7d2f7c78d3e5661d511e669f70e439/kiwisolver-1.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1ed0f5e49d0ceff8b72190824d9e59c062fbbc02c231b853112c78474b3f5ec2", size = 66487, upload-time = "2026-08-28T10:25:55.899Z" }, + { url = "https://files.pythonhosted.org/packages/47/8b/40d33ffd2f378094ed462e9a9a0907e59d4de9845e65a59561272da350d4/kiwisolver-1.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:77a4c8187a5948d7f8795adb765a3c7b553d07d86d88e43038fc32fc1fb9a3f3", size = 64673, upload-time = "2026-08-28T10:25:57.048Z" }, + { url = "https://files.pythonhosted.org/packages/ab/43/86aacc027959108b4c66eeae8b73cedb057dfa6eb3a335d05ad65197081c/kiwisolver-1.5.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:74ad5c3dad54a4641b4c28cd15ded70899d04459c6c7aeacafea716be97cce6d", size = 1477992, upload-time = "2026-08-28T10:25:58.479Z" }, + { url = "https://files.pythonhosted.org/packages/ed/40/b1d0369048c79733a32c8abb0f2718532e6630641368e33a81384246e844/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:21e46b23a2da695c364124817bc01d970effd5483147f8d66a6a7167e3f6b851", size = 1278821, upload-time = "2026-08-28T10:26:00.121Z" }, + { url = "https://files.pythonhosted.org/packages/61/a1/fa71c1792272ff9461432715ae60ffb7e11a4d7ac3bf68961b9cab6c60cf/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:75d9b1cf8258462dbdc1eeda718c96ea7f079324c09067f6daabfcf37712b7fe", size = 1296805, upload-time = "2026-08-28T10:26:01.868Z" }, + { url = "https://files.pythonhosted.org/packages/a3/49/3f0bd94af8e06ecc47eb834b195a06f05d48711ceb2352c56d6835160f0e/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8fca690b00c4c48f6c2a547b0160ed511357093a4e4c9b47e0fadf3128066d89", size = 1346109, upload-time = "2026-08-28T10:26:03.59Z" }, + { url = "https://files.pythonhosted.org/packages/a4/44/3afe6ef9cf06d61220953a8963e94eca978491be1d9547cb01d82a1efa08/kiwisolver-1.5.1-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:876bbfd276473d3daffe30e8c975df4ed9429967b41a6cb362dbb5155b6f13ad", size = 988252, upload-time = "2026-08-28T10:26:05.306Z" }, + { url = "https://files.pythonhosted.org/packages/e4/30/a12bd7a7285a211e1747c3eec77b8c614dbfcc1dad942f7611a1a6921ae5/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f942903fde7363d1d879057ec5de01310efda2597161784d752fa9953a01a71a", size = 2228846, upload-time = "2026-08-28T10:26:07.312Z" }, + { url = "https://files.pythonhosted.org/packages/a1/6b/233e2958abf0dab7b18d07e52f286e02e519d7651bfbbe97af9347564109/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c90d3022d8a94778939cda8638c6c8da8fa757b8958dad7ec868ce29c87681b8", size = 2325583, upload-time = "2026-08-28T10:26:09.093Z" }, + { url = "https://files.pythonhosted.org/packages/42/8e/7673060a27b01405b580058510adef34687069d229800239f5e44682d4d0/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:8a34616dc2521cc8dc1d7d081734da63539f021ac0450ce950908340c6e7aa2f", size = 1978221, upload-time = "2026-08-28T10:26:11.127Z" }, + { url = "https://files.pythonhosted.org/packages/3f/7b/1b882fc1a8b4a0bb8084e7d1d85004116d08c92c0705d31f2928dec607f2/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:8bf4df63592c2a66b4f8edc5df2544998c288aa02f96ce0acd880cd1de8c8127", size = 2491819, upload-time = "2026-08-28T10:26:13.348Z" }, + { url = "https://files.pythonhosted.org/packages/39/9c/426deb49e62c5f69464b64bbeca064d3b758a7506b8913d986ef34f4619c/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d09037ca068d784ebc4aec290ef952ca27ac15dd9c0b5801a88c6e1096b83e6b", size = 2295520, upload-time = "2026-08-28T10:26:15.042Z" }, + { url = "https://files.pythonhosted.org/packages/f5/22/deabbb3ad6d918d74b7831b2d8ae7151b09d21c87974e5ee8a456f58c94c/kiwisolver-1.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:dc23390afe9f4ef9ac3bcc72a03a56eebbde03f4c571a32cb38f859cff9a6524", size = 70758, upload-time = "2026-08-28T10:26:16.504Z" }, + { url = "https://files.pythonhosted.org/packages/b9/71/02fa5c2fd92068bb8952847e70ee6c5cb280e7febe11653d17812acc53dd/kiwisolver-1.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:186884a58486651e3c217b6acea0a53eaa9498fdd472057c46f2f0fb5c25aad5", size = 68329, upload-time = "2026-08-28T10:26:17.658Z" }, +] + +[[package]] +name = "markupsafe" +version = "3.0.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/38/9b/e422a865e1d5d57d0e509b4e0bf1c1a70a7f6382c29a5aa428df994c8bc8/markupsafe-3.0.4.tar.gz", hash = "sha256:2e9ad7dd851bf45fab9f75cbff4cb493fee9979e8d8c7c9c3ee119022518edd6", size = 153777, upload-time = "2026-10-02T23:07:22.29Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/18/4bc5ba32499e87bb2b0ef5b3a9bb9c00a131fa961ddf0be548cb550f548b/markupsafe-3.0.4-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:de8b364c423ef0a4bad9069657d617f9a5d2b2062457a89b1fa16ee199c399c1", size = 12786, upload-time = "2026-10-02T23:05:08.709Z" }, + { url = "https://files.pythonhosted.org/packages/4e/6f/17f0c099bf25f3e31e63cc19244d9f6af861a9a4ab778c203997903cfdd0/markupsafe-3.0.4-cp313-cp313-android_24_x86_64.whl", hash = "sha256:34bdde374c5932765d7dc685c4a1d191a3207852d67e8e0a9eb6ea85156181f1", size = 12510, upload-time = "2026-10-02T23:05:09.93Z" }, + { url = "https://files.pythonhosted.org/packages/11/af/1a141081b905036ee904ec4bd945e1f70b4e1b32d33c4e59e8cf1d58b247/markupsafe-3.0.4-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:6bd9e1788e15bfcf6a9082de42e30387e7b85d211ab21e57a939bb8cfaaf8d96", size = 11583, upload-time = "2026-10-02T23:05:10.884Z" }, + { url = "https://files.pythonhosted.org/packages/e7/0a/a89385ae590232622a03e091805cff12f24fabe6c11e0e8bae096cece81c/markupsafe-3.0.4-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:5066b244f576f91afc8ee3ba029a89f99d39c79b1853fe9d39bea9f0afbec148", size = 11801, upload-time = "2026-10-02T23:05:11.913Z" }, + { url = "https://files.pythonhosted.org/packages/ed/85/ea548dc013962eb73653124bc595635fbf9e0fa41d1f181a967ccb784dfb/markupsafe-3.0.4-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:7a83aa6e4805df46fed18e989d3d16f86ef60cb50bbc8d9ce3a6be89165fbf6e", size = 11443, upload-time = "2026-10-02T23:05:12.887Z" }, + { url = "https://files.pythonhosted.org/packages/cc/72/15f2e5ec9cf2eb00d5cdfe968d94e4156a7bd7303832c3f3b2c403a36839/markupsafe-3.0.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:2d1b7d9308288661f56672b1b157d75fc536714d3638487bbea17b6318a78248", size = 11665, upload-time = "2026-10-02T23:05:13.829Z" }, + { url = "https://files.pythonhosted.org/packages/ca/e0/4030bea613677e333c8a2c901fd405055f657f9d06acba5b7357984b6ef7/markupsafe-3.0.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:73e77980c7207854f00fc4e71fb1626868d5740ab4012623d55c7a99ad122a72", size = 12061, upload-time = "2026-10-02T23:05:14.807Z" }, + { url = "https://files.pythonhosted.org/packages/f3/a5/28b76a7449eb702966b88bef599e2360b411fbb3afeee8fe560939be06ec/markupsafe-3.0.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7018d4af1cd272e847aa5917983ab5e83e4f6579f9dbfecd4a79c0ca80b144c2", size = 24395, upload-time = "2026-10-02T23:05:15.909Z" }, + { url = "https://files.pythonhosted.org/packages/07/6c/21232811afc3a063b5e934b1ae2efda52f46154ec382f585149c020e61fe/markupsafe-3.0.4-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:c90d5b3d4e944e065a301d741b3c1d784f6bd1f503aa68b4967e32b2ba313d85", size = 27183, upload-time = "2026-10-02T23:05:16.976Z" }, + { url = "https://files.pythonhosted.org/packages/14/38/6ccdfa5b59049cb36fb80cbc80aee9cf1fc9bb77d1335ad435f2070b08cf/markupsafe-3.0.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:18a801868a884f216e784d7d14db2a4077143ce7610440aee2ce8f734e7cfcde", size = 24772, upload-time = "2026-10-02T23:05:18.209Z" }, + { url = "https://files.pythonhosted.org/packages/63/e0/cec6865dfe88cb48fedd4b20aed6af5158e41092adcbf3e028bcc6ec2108/markupsafe-3.0.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:434139499bb20b502ed3baa1f169e618f924a97e7a777fea1a49446d80106cf6", size = 23017, upload-time = "2026-10-02T23:05:19.286Z" }, + { url = "https://files.pythonhosted.org/packages/ee/76/6ed4940bb7648a9aac457c14f870cfdd5105f139a0fb1f29cd61fafa47d1/markupsafe-3.0.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:9e227f3dbe6bde7491cf0a9965d00b88c6b1a4a95d11480ddf88bb96d397c19f", size = 22036, upload-time = "2026-10-02T23:05:20.352Z" }, + { url = "https://files.pythonhosted.org/packages/a1/4f/ed476226d4fe46a09090a36025bf319296810028df55eb12f1253b540f3a/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:b8cd1f918b26fd7b1832ece557cc18f2d8747309ff8b3f0ef9d4250c5ad67a39", size = 23786, upload-time = "2026-10-02T23:05:21.576Z" }, + { url = "https://files.pythonhosted.org/packages/9a/35/66ff30450e35ef5fba9ebc930c9411747e537fd9447b65e44f5007e2b84d/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:a5fcffb37e602b0b3c1638a97746b9b96125caa9bcf6fa41d337a9261de231ee", size = 22672, upload-time = "2026-10-02T23:05:22.922Z" }, + { url = "https://files.pythonhosted.org/packages/32/0b/72f45ce4b4efcbca4b80cf1b06703eff0be8d37e82abb78f66c85a7ead1e/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:5989cb26b2e1efc6a42216a9f6b5ee495ce5ace2e5b352a9af489976b32d1ee2", size = 24107, upload-time = "2026-10-02T23:05:24.175Z" }, + { url = "https://files.pythonhosted.org/packages/d2/03/71776e5fdcba04614b384cc102e8a4198208579d896fd1394cb7cb9aa900/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:add96447a86d205ab616665d53b2950ee81083757f56e6ea833c8b2917646b46", size = 21615, upload-time = "2026-10-02T23:05:25.215Z" }, + { url = "https://files.pythonhosted.org/packages/ab/5f/801ce02a02e7aee0f784b1ec7843026178f6adeb9c93ac67eb1992a9a84d/markupsafe-3.0.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:2628d3a8cb648ecebb3c5d6b0a1052d400e4d8b7ac0fb786be8d285b50040d17", size = 23076, upload-time = "2026-10-02T23:05:26.423Z" }, + { url = "https://files.pythonhosted.org/packages/4a/85/c43776625428f3bb4a61e8633940400e3efe6409e3c6f5bff26de5e45618/markupsafe-3.0.4-cp313-cp313-win32.whl", hash = "sha256:672d207103e6b16ca098611b0f9efad6bc00afd47c03d6ef62186495ca677dc0", size = 14118, upload-time = "2026-10-02T23:05:27.716Z" }, + { url = "https://files.pythonhosted.org/packages/6f/36/163da64de88a13db79214ef75fa041be7fa13bdb42261cf5b7484de14bfb/markupsafe-3.0.4-cp313-cp313-win_amd64.whl", hash = "sha256:1f1f9477e174582b0a1b583d60b66e1f2cf5d3fe12cee985e4aedf44766600e5", size = 14313, upload-time = "2026-10-02T23:05:28.749Z" }, + { url = "https://files.pythonhosted.org/packages/9f/a8/9b662783ffaa1149221432a923cee562f78b9cbbb8baa3df9b3753e63e1e/markupsafe-3.0.4-cp313-cp313-win_arm64.whl", hash = "sha256:06de8ef6331f6e822c28d577dc8bf43fe398800477c49498f38fc38b67ff33fc", size = 14189, upload-time = "2026-10-02T23:05:29.917Z" }, +] + +[[package]] +name = "matplotlib" +version = "3.10.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "contourpy" }, + { name = "cycler" }, + { name = "fonttools" }, + { name = "kiwisolver" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "pyparsing" }, + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ae/e2/d2d5295be2f44c678ebaf3544ba32d20c1f9ef08c49fe47f496180e1db15/matplotlib-3.10.7.tar.gz", hash = "sha256:a06ba7e2a2ef9131c79c49e63dad355d2d878413a0376c1727c8b9335ff731c7", size = 34804865, upload-time = "2025-10-09T00:28:00.669Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/02/9c/207547916a02c78f6bdd83448d9b21afbc42f6379ed887ecf610984f3b4e/matplotlib-3.10.7-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1d9d3713a237970569156cfb4de7533b7c4eacdd61789726f444f96a0d28f57f", size = 8273212, upload-time = "2025-10-09T00:26:56.752Z" }, + { url = "https://files.pythonhosted.org/packages/bc/d0/b3d3338d467d3fc937f0bb7f256711395cae6f78e22cef0656159950adf0/matplotlib-3.10.7-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:37a1fea41153dd6ee061d21ab69c9cf2cf543160b1b85d89cd3d2e2a7902ca4c", size = 8128713, upload-time = "2025-10-09T00:26:59.001Z" }, + { url = "https://files.pythonhosted.org/packages/22/ff/6425bf5c20d79aa5b959d1ce9e65f599632345391381c9a104133fe0b171/matplotlib-3.10.7-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b3c4ea4948d93c9c29dc01c0c23eef66f2101bf75158c291b88de6525c55c3d1", size = 8698527, upload-time = "2025-10-09T00:27:00.69Z" }, + { url = "https://files.pythonhosted.org/packages/d0/7f/ccdca06f4c2e6c7989270ed7829b8679466682f4cfc0f8c9986241c023b6/matplotlib-3.10.7-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22df30ffaa89f6643206cf13877191c63a50e8f800b038bc39bee9d2d4957632", size = 9529690, upload-time = "2025-10-09T00:27:02.664Z" }, + { url = "https://files.pythonhosted.org/packages/b8/95/b80fc2c1f269f21ff3d193ca697358e24408c33ce2b106a7438a45407b63/matplotlib-3.10.7-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b69676845a0a66f9da30e87f48be36734d6748024b525ec4710be40194282c84", size = 9593732, upload-time = "2025-10-09T00:27:04.653Z" }, + { url = "https://files.pythonhosted.org/packages/e1/b6/23064a96308b9aeceeffa65e96bcde459a2ea4934d311dee20afde7407a0/matplotlib-3.10.7-cp313-cp313-win_amd64.whl", hash = "sha256:744991e0cc863dd669c8dc9136ca4e6e0082be2070b9d793cbd64bec872a6815", size = 8122727, upload-time = "2025-10-09T00:27:06.814Z" }, + { url = "https://files.pythonhosted.org/packages/b3/a6/2faaf48133b82cf3607759027f82b5c702aa99cdfcefb7f93d6ccf26a424/matplotlib-3.10.7-cp313-cp313-win_arm64.whl", hash = "sha256:fba2974df0bf8ce3c995fa84b79cde38326e0f7b5409e7a3a481c1141340bcf7", size = 7992958, upload-time = "2025-10-09T00:27:08.567Z" }, + { url = "https://files.pythonhosted.org/packages/4a/f0/b018fed0b599bd48d84c08794cb242227fe3341952da102ee9d9682db574/matplotlib-3.10.7-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:932c55d1fa7af4423422cb6a492a31cbcbdbe68fd1a9a3f545aa5e7a143b5355", size = 8316849, upload-time = "2025-10-09T00:27:10.254Z" }, + { url = "https://files.pythonhosted.org/packages/b0/b7/bb4f23856197659f275e11a2a164e36e65e9b48ea3e93c4ec25b4f163198/matplotlib-3.10.7-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:5e38c2d581d62ee729a6e144c47a71b3f42fb4187508dbbf4fe71d5612c3433b", size = 8178225, upload-time = "2025-10-09T00:27:12.241Z" }, + { url = "https://files.pythonhosted.org/packages/62/56/0600609893ff277e6f3ab3c0cef4eafa6e61006c058e84286c467223d4d5/matplotlib-3.10.7-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:786656bb13c237bbcebcd402f65f44dd61ead60ee3deb045af429d889c8dbc67", size = 8711708, upload-time = "2025-10-09T00:27:13.879Z" }, + { url = "https://files.pythonhosted.org/packages/d8/1a/6bfecb0cafe94d6658f2f1af22c43b76cf7a1c2f0dc34ef84cbb6809617e/matplotlib-3.10.7-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:09d7945a70ea43bf9248f4b6582734c2fe726723204a76eca233f24cffc7ef67", size = 9541409, upload-time = "2025-10-09T00:27:15.684Z" }, + { url = "https://files.pythonhosted.org/packages/08/50/95122a407d7f2e446fd865e2388a232a23f2b81934960ea802f3171518e4/matplotlib-3.10.7-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:d0b181e9fa8daf1d9f2d4c547527b167cb8838fc587deabca7b5c01f97199e84", size = 9594054, upload-time = "2025-10-09T00:27:17.547Z" }, + { url = "https://files.pythonhosted.org/packages/13/76/75b194a43b81583478a81e78a07da8d9ca6ddf50dd0a2ccabf258059481d/matplotlib-3.10.7-cp313-cp313t-win_amd64.whl", hash = "sha256:31963603041634ce1a96053047b40961f7a29eb8f9a62e80cc2c0427aa1d22a2", size = 8200100, upload-time = "2025-10-09T00:27:20.039Z" }, + { url = "https://files.pythonhosted.org/packages/f5/9e/6aefebdc9f8235c12bdeeda44cc0383d89c1e41da2c400caf3ee2073a3ce/matplotlib-3.10.7-cp313-cp313t-win_arm64.whl", hash = "sha256:aebed7b50aa6ac698c90f60f854b47e48cd2252b30510e7a1feddaf5a3f72cbf", size = 8042131, upload-time = "2025-10-09T00:27:21.608Z" }, +] + +[[package]] +name = "mpmath" +version = "1.3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e0/47/dd32fa426cc72114383ac549964eecb20ecfd886d1e5ccf5340b55b02f57/mpmath-1.3.0.tar.gz", hash = "sha256:7a28eb2a9774d00c7bc92411c19a89209d5da7c4c9a9e227be8330a23a25b91f", size = 508106, upload-time = "2023-03-07T16:47:11.061Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/43/e3/7d92a15f894aa0c9c4b49b8ee9ac9850d6e63b03c9c32c0367a13ae62209/mpmath-1.3.0-py3-none-any.whl", hash = "sha256:a0b2b9fe80bbcd81a6647ff13108738cfb482d481d826cc0e02f5b35e5c88d2c", size = 536198, upload-time = "2023-03-07T16:47:09.197Z" }, +] + +[[package]] +name = "multidict" +version = "7.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7b/6b/29ef8e752f5854dcc267ded0652c475bec99b86f255957a0d4fcad657b18/multidict-7.2.1.tar.gz", hash = "sha256:e8af3e6f1bdbc31fd762b094133b478b89988eaebc63cbe82b1d9e3bbd15cede", size = 369994, upload-time = "2026-10-24T20:41:35.457Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/33/f7/453ab156d423def05ac3a4a268f52975378520bf919ded61c9a8bb432b7d/multidict-7.2.1-cp313-cp313-android_24_x86_64.whl", hash = "sha256:fba33e264cdd2ec43b762b9960d1648478eecfc1ce6e8159e7573510f0412c0a", size = 103189, upload-time = "2026-10-24T20:40:18.599Z" }, + { url = "https://files.pythonhosted.org/packages/dc/f1/db4171d67615081b007ceab10af476cf7d66a09291fe43c11f1608f08d4a/multidict-7.2.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:f2087ee23a18d1d618a135eedcafba7dfc40c6be4e8e52d7f29a1c8a2344cfcc", size = 101149, upload-time = "2026-10-24T20:40:20.693Z" }, + { url = "https://files.pythonhosted.org/packages/be/7f/adae49eae252c26f2b7a2fe89984533e0bdb0072f29023c1f2ad7588886e/multidict-7.2.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f5812cfcf7daf3ace5fedf6e2ef8d4b342c92fb8ea3a87c1aed2b50453271093", size = 103294, upload-time = "2026-10-24T20:40:21.094Z" }, + { url = "https://files.pythonhosted.org/packages/48/45/9fac67be204fc5570593f4dfa2395c542bd1643ffd090c8566de0d1d7f8e/multidict-7.2.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:57ac987ec5d26d89bbc48c03e486f659e1367d425c465552ac2e4c4af8219def", size = 171995, upload-time = "2026-10-24T20:40:57.102Z" }, + { url = "https://files.pythonhosted.org/packages/91/5f/7912bfb95ab00ed6bd588884ca44adf29f7f56de871247a535135af5a2b4/multidict-7.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:714fe5f3eabd153b1b6911d0b5d31cfc2b808ae6b9e59a32fab17a4e6cdad5a6", size = 97470, upload-time = "2026-10-24T20:40:19.915Z" }, + { url = "https://files.pythonhosted.org/packages/06/18/29874e132d78ce182305e818a1553c4ddae238471ba55903a1ea38b5c4ee/multidict-7.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:4bebc9587cc29359e3b045518a7a09264fa882a7d165b0d143fdac8eeb7ea948", size = 103438, upload-time = "2026-10-24T20:40:21.892Z" }, + { url = "https://files.pythonhosted.org/packages/20/9c/0b181fac73aa9d0f24bc38ce24f56a9cb08c96109c3703d2f79ef15c2c2b/multidict-7.2.1-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:12bbab225ce7f69df75409ab8005b11b4e9309fae863821e019e81b32e53a2a8", size = 493852, upload-time = "2026-10-24T20:40:22.383Z" }, + { url = "https://files.pythonhosted.org/packages/4f/2e/d9ee8ccc91fcde4ad9a6e8275b1df67c0e079349fe33fd30530706dc2707/multidict-7.2.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:335f715f8c111654f29e4bf19086bdf0245579d2b4f4f59ca8dd9b3003b859c1", size = 506390, upload-time = "2026-10-24T20:40:58.494Z" }, + { url = "https://files.pythonhosted.org/packages/3c/f6/eca9192c0e598655258b2a3d14120894aecc338982670ca7ff4d4168b226/multidict-7.2.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:9df532dd12c59a7a4d381646fc1bf5ccb4bcdbd01c0887d07ec769fae965ea9a", size = 469470, upload-time = "2026-10-24T20:40:21.363Z" }, + { url = "https://files.pythonhosted.org/packages/cf/1b/a4cc6da2651966c725298812d965b9d70918544214a5638c670837034f24/multidict-7.2.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:9c9f285f788acf2448a57c9b93d31103ac69bd03f92907e2ffbb23c4e2b42eb6", size = 523167, upload-time = "2026-10-24T20:40:23.155Z" }, + { url = "https://files.pythonhosted.org/packages/20/64/f3df5b32600c6dfcc1a949f15c8de2b89e44053f5c78bea05c6240e10af8/multidict-7.2.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:21d86f2aa58aa428fb9909d6b8587b75eea827287e3515b8506dca86b55e2c7d", size = 547031, upload-time = "2026-10-24T20:40:23.769Z" }, + { url = "https://files.pythonhosted.org/packages/8f/85/15918b8f73aeb770c534f22b7dac256dc70b6fc7aa0571856c82b17bf3c5/multidict-7.2.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cd69c99affd1b4debc1f9a53058ea6e3a9b34f2e733840bb45891666cd8ede0a", size = 516056, upload-time = "2026-10-24T20:40:59.951Z" }, + { url = "https://files.pythonhosted.org/packages/d6/eb/b74b3441b572218dd24068b67bf4f1f71934cfa5938f55c299425b1c41c0/multidict-7.2.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:fc45ff19520bc5321dcd9c6dd7df6f35ddd894eed35e5be65d1828a9c3f5e7fb", size = 449703, upload-time = "2026-10-24T20:40:22.96Z" }, + { url = "https://files.pythonhosted.org/packages/47/81/ac9bb12377260913c0384bdb60b2f9097b1ba580579a2f9697b9e21709f3/multidict-7.2.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:cba29f12cd717f1cbbe220edf005666f8df0453347217748331a0c2f7522eca4", size = 492340, upload-time = "2026-10-24T20:40:24.498Z" }, + { url = "https://files.pythonhosted.org/packages/b1/e9/bac55e20457d3e23879b65e8c46dca5ea90675eee73ca70e3fdc4984d53c/multidict-7.2.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:4f31ddf9c00e0e7db848b0236c717acbe8a51954d0d31b4d908c538ab3f0f5bc", size = 468205, upload-time = "2026-10-24T20:40:25.143Z" }, + { url = "https://files.pythonhosted.org/packages/ff/ce/1dc1e0f8bc28f41edee6fd0e2116f1d7b077e8fc04f50617e65f3938cbaa/multidict-7.2.1-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:7cb1a6bb70edcc06ea65cb9a35654f268ee39d9fc3a52240e6ba074db4d9c99e", size = 493634, upload-time = "2026-10-24T20:41:01.377Z" }, + { url = "https://files.pythonhosted.org/packages/70/e2/7a4e9f4e35d522715f8987a17d3a098582d0e879cfde621defa586330310/multidict-7.2.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:a2a322c8a6ca82a5a67ae6542e9c6a13ded9045cfd171dcccc5c213ac4fe0eab", size = 509128, upload-time = "2026-10-24T20:40:24.735Z" }, + { url = "https://files.pythonhosted.org/packages/60/cd/d142dc374de3585c57e2635659d45c3179cf47ded415794b2e7ead663373/multidict-7.2.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:678ac791b5820d9346eb13c8515fe0c9383659335e5cfc544bf6f54714ca1939", size = 444795, upload-time = "2026-10-24T20:40:25.846Z" }, + { url = "https://files.pythonhosted.org/packages/6d/41/7121157290d436282cf2405cda15d4448921231f7291679f5a3f47669bbe/multidict-7.2.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:0c454b677214fa604e9c4a38952c685dc88a62c96f5576a7ce550f213d1dc318", size = 526200, upload-time = "2026-10-24T20:40:26.763Z" }, + { url = "https://files.pythonhosted.org/packages/6f/fd/05e6e78a34023574db41c057676aa1c26925533fe0b60de9fb5ed5e1a101/multidict-7.2.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:3ca60708f0ca9d994f46790c5a5c774771e2f1dcb75b12c70a5582f915d0e721", size = 507752, upload-time = "2026-10-24T20:41:02.846Z" }, + { url = "https://files.pythonhosted.org/packages/41/50/3bccfa9f3003303fda37a1f7131ab90dcf36ef7fa9af6611151f4b2e316c/multidict-7.2.1-cp313-cp313-win32.whl", hash = "sha256:fa949c81e3865c10f981dea72fd8d418b59edd13a047a0aee89ae64790113d53", size = 84246, upload-time = "2026-10-24T20:40:26.077Z" }, + { url = "https://files.pythonhosted.org/packages/74/6b/3f90a565e6eb94266d197d91cca5833b34ab89768a24f7f07b29bc186e09/multidict-7.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:ce0f884408938fbd72e764031d0e23a8f5e438a7bf73641089c7a6465cb84456", size = 95078, upload-time = "2026-10-24T20:40:27.34Z" }, + { url = "https://files.pythonhosted.org/packages/09/29/3acaf67a5d0f0ecce997f1f57cd14c8c634d05e1672df23b29d4f072262e/multidict-7.2.1-cp313-cp313-win_arm64.whl", hash = "sha256:554ee1d2e71fb5b4059c0c4ee35d8cbc8af2a3147036d65a454c53fea07ff4eb", size = 92390, upload-time = "2026-10-24T20:40:28.055Z" }, + { url = "https://files.pythonhosted.org/packages/9d/96/1aaad0e5df33f1f5af21775c411349c0234a6edd581ea403bc81919a6eab/multidict-7.2.1-py3-none-any.whl", hash = "sha256:08ea94663d9e7c25d14d78222f7aee906c472d4837766bec62477c38f6e419dc", size = 28145, upload-time = "2026-10-24T20:40:59.159Z" }, +] + +[[package]] +name = "multiprocess" +version = "0.70.16" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "dill" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b5/ae/04f39c5d0d0def03247c2893d6f2b83c136bf3320a2154d7b8858f2ba72d/multiprocess-0.70.16.tar.gz", hash = "sha256:161af703d4652a0e1410be6abccecde4a7ddffd19341be0a7011b94aeb171ac1", size = 1772603, upload-time = "2024-01-28T18:52:34.85Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bc/f7/7ec7fddc92e50714ea3745631f79bd9c96424cb2702632521028e57d3a36/multiprocess-0.70.16-py310-none-any.whl", hash = "sha256:c4a9944c67bd49f823687463660a2d6daae94c289adff97e0f9d696ba6371d02", size = 134824, upload-time = "2024-01-28T18:52:26.062Z" }, + { url = "https://files.pythonhosted.org/packages/50/15/b56e50e8debaf439f44befec5b2af11db85f6e0f344c3113ae0be0593a91/multiprocess-0.70.16-py311-none-any.whl", hash = "sha256:af4cabb0dac72abfb1e794fa7855c325fd2b55a10a44628a3c1ad3311c04127a", size = 143519, upload-time = "2024-01-28T18:52:28.115Z" }, + { url = "https://files.pythonhosted.org/packages/0a/7d/a988f258104dcd2ccf1ed40fdc97e26c4ac351eeaf81d76e266c52d84e2f/multiprocess-0.70.16-py312-none-any.whl", hash = "sha256:fc0544c531920dde3b00c29863377f87e1632601092ea2daca74e4beb40faa2e", size = 146741, upload-time = "2024-01-28T18:52:29.395Z" }, + { url = "https://files.pythonhosted.org/packages/ea/89/38df130f2c799090c978b366cfdf5b96d08de5b29a4a293df7f7429fa50b/multiprocess-0.70.16-py38-none-any.whl", hash = "sha256:a71d82033454891091a226dfc319d0cfa8019a4e888ef9ca910372a446de4435", size = 132628, upload-time = "2024-01-28T18:52:30.853Z" }, + { url = "https://files.pythonhosted.org/packages/da/d9/f7f9379981e39b8c2511c9e0326d212accacb82f12fbfdc1aa2ce2a7b2b6/multiprocess-0.70.16-py39-none-any.whl", hash = "sha256:a0bafd3ae1b732eac64be2e72038231c1ba97724b60b09400d68f229fcc2fbf3", size = 133351, upload-time = "2024-01-28T18:52:31.981Z" }, +] + +[[package]] +name = "networkx" +version = "3.7" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/dc/76/3af777226b63a5e64a6b36b1ec5855c14e2b94a37096d4760e595fc43511/networkx-3.7.tar.gz", hash = "sha256:fd77a511bd90f39f3d016351345b52cf5319b813bdca01de3f755d3cca62e96a", size = 1866482, upload-time = "2026-09-21T16:45:16.974Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/cd/fe58041e9011f307c490e3e17dd48cc516448f7c698a3f2d9d9d65d7e6a8/networkx-3.7-py3-none-any.whl", hash = "sha256:e3fd2c13a7814cee3746340d8d7f8598a67f16a58bf47fb7f8793fab6efca1b0", size = 2142205, upload-time = "2026-09-21T16:45:14.609Z" }, +] + +[[package]] +name = "numpy" +version = "2.2.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/76/21/7d2a95e4bba9dc13d043ee156a356c0a8f0c6309dff6b21b4d71a073b8a8/numpy-2.2.6.tar.gz", hash = "sha256:e29554e2bef54a90aa5cc07da6ce955accb83f21ab5de01a62c8478897b264fd", size = 20276440, upload-time = "2025-05-17T22:38:04.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/5c/6657823f4f594f72b5471f1db1ab12e26e890bb2e41897522d134d2a3e81/numpy-2.2.6-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0811bb762109d9708cca4d0b13c4f67146e3c3b7cf8d34018c722adb2d957c84", size = 20867828, upload-time = "2025-05-17T21:37:56.699Z" }, + { url = "https://files.pythonhosted.org/packages/dc/9e/14520dc3dadf3c803473bd07e9b2bd1b69bc583cb2497b47000fed2fa92f/numpy-2.2.6-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:287cc3162b6f01463ccd86be154f284d0893d2b3ed7292439ea97eafa8170e0b", size = 14143006, upload-time = "2025-05-17T21:38:18.291Z" }, + { url = "https://files.pythonhosted.org/packages/4f/06/7e96c57d90bebdce9918412087fc22ca9851cceaf5567a45c1f404480e9e/numpy-2.2.6-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:f1372f041402e37e5e633e586f62aa53de2eac8d98cbfb822806ce4bbefcb74d", size = 5076765, upload-time = "2025-05-17T21:38:27.319Z" }, + { url = "https://files.pythonhosted.org/packages/73/ed/63d920c23b4289fdac96ddbdd6132e9427790977d5457cd132f18e76eae0/numpy-2.2.6-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:55a4d33fa519660d69614a9fad433be87e5252f4b03850642f88993f7b2ca566", size = 6617736, upload-time = "2025-05-17T21:38:38.141Z" }, + { url = "https://files.pythonhosted.org/packages/85/c5/e19c8f99d83fd377ec8c7e0cf627a8049746da54afc24ef0a0cb73d5dfb5/numpy-2.2.6-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f92729c95468a2f4f15e9bb94c432a9229d0d50de67304399627a943201baa2f", size = 14010719, upload-time = "2025-05-17T21:38:58.433Z" }, + { url = "https://files.pythonhosted.org/packages/19/49/4df9123aafa7b539317bf6d342cb6d227e49f7a35b99c287a6109b13dd93/numpy-2.2.6-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1bc23a79bfabc5d056d106f9befb8d50c31ced2fbc70eedb8155aec74a45798f", size = 16526072, upload-time = "2025-05-17T21:39:22.638Z" }, + { url = "https://files.pythonhosted.org/packages/b2/6c/04b5f47f4f32f7c2b0e7260442a8cbcf8168b0e1a41ff1495da42f42a14f/numpy-2.2.6-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:e3143e4451880bed956e706a3220b4e5cf6172ef05fcc397f6f36a550b1dd868", size = 15503213, upload-time = "2025-05-17T21:39:45.865Z" }, + { url = "https://files.pythonhosted.org/packages/17/0a/5cd92e352c1307640d5b6fec1b2ffb06cd0dabe7d7b8227f97933d378422/numpy-2.2.6-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:b4f13750ce79751586ae2eb824ba7e1e8dba64784086c98cdbbcc6a42112ce0d", size = 18316632, upload-time = "2025-05-17T21:40:13.331Z" }, + { url = "https://files.pythonhosted.org/packages/f0/3b/5cba2b1d88760ef86596ad0f3d484b1cbff7c115ae2429678465057c5155/numpy-2.2.6-cp313-cp313-win32.whl", hash = "sha256:5beb72339d9d4fa36522fc63802f469b13cdbe4fdab4a288f0c441b74272ebfd", size = 6244532, upload-time = "2025-05-17T21:43:46.099Z" }, + { url = "https://files.pythonhosted.org/packages/cb/3b/d58c12eafcb298d4e6d0d40216866ab15f59e55d148a5658bb3132311fcf/numpy-2.2.6-cp313-cp313-win_amd64.whl", hash = "sha256:b0544343a702fa80c95ad5d3d608ea3599dd54d4632df855e4c8d24eb6ecfa1c", size = 12610885, upload-time = "2025-05-17T21:44:05.145Z" }, + { url = "https://files.pythonhosted.org/packages/6b/9e/4bf918b818e516322db999ac25d00c75788ddfd2d2ade4fa66f1f38097e1/numpy-2.2.6-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0bca768cd85ae743b2affdc762d617eddf3bcf8724435498a1e80132d04879e6", size = 20963467, upload-time = "2025-05-17T21:40:44Z" }, + { url = "https://files.pythonhosted.org/packages/61/66/d2de6b291507517ff2e438e13ff7b1e2cdbdb7cb40b3ed475377aece69f9/numpy-2.2.6-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:fc0c5673685c508a142ca65209b4e79ed6740a4ed6b2267dbba90f34b0b3cfda", size = 14225144, upload-time = "2025-05-17T21:41:05.695Z" }, + { url = "https://files.pythonhosted.org/packages/e4/25/480387655407ead912e28ba3a820bc69af9adf13bcbe40b299d454ec011f/numpy-2.2.6-cp313-cp313t-macosx_14_0_arm64.whl", hash = "sha256:5bd4fc3ac8926b3819797a7c0e2631eb889b4118a9898c84f585a54d475b7e40", size = 5200217, upload-time = "2025-05-17T21:41:15.903Z" }, + { url = "https://files.pythonhosted.org/packages/aa/4a/6e313b5108f53dcbf3aca0c0f3e9c92f4c10ce57a0a721851f9785872895/numpy-2.2.6-cp313-cp313t-macosx_14_0_x86_64.whl", hash = "sha256:fee4236c876c4e8369388054d02d0e9bb84821feb1a64dd59e137e6511a551f8", size = 6712014, upload-time = "2025-05-17T21:41:27.321Z" }, + { url = "https://files.pythonhosted.org/packages/b7/30/172c2d5c4be71fdf476e9de553443cf8e25feddbe185e0bd88b096915bcc/numpy-2.2.6-cp313-cp313t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e1dda9c7e08dc141e0247a5b8f49cf05984955246a327d4c48bda16821947b2f", size = 14077935, upload-time = "2025-05-17T21:41:49.738Z" }, + { url = "https://files.pythonhosted.org/packages/12/fb/9e743f8d4e4d3c710902cf87af3512082ae3d43b945d5d16563f26ec251d/numpy-2.2.6-cp313-cp313t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f447e6acb680fd307f40d3da4852208af94afdfab89cf850986c3ca00562f4fa", size = 16600122, upload-time = "2025-05-17T21:42:14.046Z" }, + { url = "https://files.pythonhosted.org/packages/12/75/ee20da0e58d3a66f204f38916757e01e33a9737d0b22373b3eb5a27358f9/numpy-2.2.6-cp313-cp313t-musllinux_1_2_aarch64.whl", hash = "sha256:389d771b1623ec92636b0786bc4ae56abafad4a4c513d36a55dce14bd9ce8571", size = 15586143, upload-time = "2025-05-17T21:42:37.464Z" }, + { url = "https://files.pythonhosted.org/packages/76/95/bef5b37f29fc5e739947e9ce5179ad402875633308504a52d188302319c8/numpy-2.2.6-cp313-cp313t-musllinux_1_2_x86_64.whl", hash = "sha256:8e9ace4a37db23421249ed236fdcdd457d671e25146786dfc96835cd951aa7c1", size = 18385260, upload-time = "2025-05-17T21:43:05.189Z" }, + { url = "https://files.pythonhosted.org/packages/09/04/f2f83279d287407cf36a7a8053a5abe7be3622a4363337338f2585e4afda/numpy-2.2.6-cp313-cp313t-win32.whl", hash = "sha256:038613e9fb8c72b0a41f025a7e4c3f0b7a1b5d768ece4796b674c8f3fe13efff", size = 6377225, upload-time = "2025-05-17T21:43:16.254Z" }, + { url = "https://files.pythonhosted.org/packages/67/0e/35082d13c09c02c011cf21570543d202ad929d961c02a147493cb0c2bdf5/numpy-2.2.6-cp313-cp313t-win_amd64.whl", hash = "sha256:6031dd6dfecc0cf9f668681a37648373bddd6421fff6c66ec1624eed0180ee06", size = 12771374, upload-time = "2025-05-17T21:43:35.479Z" }, +] + +[[package]] +name = "nvidia-cublas" +version = "13.1.1.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cuda-nvrtc" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/a1/0bd24ee8c8d03adac032fd2909426a00c88f8c57961b1277ded97f91119f/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:b7a210458267ac818974c53038fbec2e969d5c99f305ab15c72522fa9f001dd5", size = 542848918, upload-time = "2026-04-08T18:46:22.985Z" }, + { url = "https://files.pythonhosted.org/packages/3b/cd/154ca20c38269e05eff77c1464e6c1da89f50a6390b565e9d82e06bc11e1/nvidia_cublas-13.1.1.3-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:37936a16db8fe4ac1f065c2139360608a543a09275cb1a1af612e08cfa065436", size = 423138758, upload-time = "2026-04-08T18:46:58.655Z" }, +] + +[[package]] +name = "nvidia-cuda-cupti" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2a/2a/80353b103fc20ce05ef51e928daed4b6015db4aaa9162ed0997090fe2250/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_aarch64.whl", hash = "sha256:796bd679890ee55fb14a94629b698b6db54bcfd833d391d5e94017dd9d7d3151", size = 10310827, upload-time = "2025-09-04T08:26:42.012Z" }, + { url = "https://files.pythonhosted.org/packages/33/6d/737d164b4837a9bbd202f5ae3078975f0525a55730fe871d8ed4e3b952b0/nvidia_cuda_cupti-13.0.85-py3-none-manylinux_2_25_x86_64.whl", hash = "sha256:4eb01c08e859bf924d222250d2e8f8b8ff6d3db4721288cf35d14252a4d933c8", size = 10715597, upload-time = "2025-09-04T08:26:51.312Z" }, +] + +[[package]] +name = "nvidia-cuda-nvrtc" +version = "13.0.88" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c3/68/483a78f5e8f31b08fb1bb671559968c0ca3a065ac7acabfc7cee55214fd6/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:ad9b6d2ead2435f11cbb6868809d2adeeee302e9bb94bcf0539c7a40d80e8575", size = 90215200, upload-time = "2025-09-04T08:28:44.204Z" }, + { url = "https://files.pythonhosted.org/packages/b7/dc/6bb80850e0b7edd6588d560758f17e0550893a1feaf436807d64d2da040f/nvidia_cuda_nvrtc-13.0.88-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:d27f20a0ca67a4bb34268a5e951033496c5b74870b868bacd046b1b8e0c3267b", size = 43015449, upload-time = "2025-09-04T08:28:20.239Z" }, +] + +[[package]] +name = "nvidia-cuda-runtime" +version = "13.0.96" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/87/4f/17d7b9b8e285199c58ce28e31b5c5bbaa4d8271af06a89b6405258245de2/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:ef9bcbe90493a2b9d810e43d249adb3d02e98dd30200d86607d8d02687c43f55", size = 2261060, upload-time = "2025-10-09T08:55:15.78Z" }, + { url = "https://files.pythonhosted.org/packages/2e/24/d1558f3b68b1d26e706813b1d10aa1d785e4698c425af8db8edc3dced472/nvidia_cuda_runtime-13.0.96-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7f82250d7782aa23b6cfe765ecc7db554bd3c2870c43f3d1821f1d18aebf0548", size = 2243632, upload-time = "2025-10-09T08:55:36.117Z" }, +] + +[[package]] +name = "nvidia-cudnn-cu13" +version = "9.20.0.48" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cublas" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/56/c5/83384d846b2fd17c44bd499b36c75a45ed4f095fbbb2252294e89cea5c5c/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:e31454ae00094b0c55319d9d15b6fa2fc50a9e1c0f5c8c80fb75258234e731e1", size = 444574296, upload-time = "2026-03-09T19:28:27.751Z" }, + { url = "https://files.pythonhosted.org/packages/6e/5e/edb9c0ae051602c3ccaffe424256463636d639e27d7f302dde9975ef9e7a/nvidia_cudnn_cu13-9.20.0.48-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0c45dd8eeb50b603f07995b1b300c62ffe6a1980482b82b3bcf94a4ca9d49304", size = 366173588, upload-time = "2026-03-09T19:29:34.474Z" }, +] + +[[package]] +name = "nvidia-cufft" +version = "12.0.0.61" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-nvjitlink" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/8b/ae/f417a75c0259e85c1d2f83ca4e960289a5f814ed0cea74d18c353d3e989d/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:2708c852ef8cd89d1d2068bdbece0aa188813a0c934db3779b9b1faa8442e5f5", size = 214053554, upload-time = "2025-09-04T08:31:38.196Z" }, + { url = "https://files.pythonhosted.org/packages/a8/2f/7b57e29836ea8714f81e9898409196f47d772d5ddedddf1592eadb8ab743/nvidia_cufft-12.0.0.61-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:6c44f692dce8fd5ffd3e3df134b6cdb9c2f72d99cf40b62c32dde45eea9ddad3", size = 214085489, upload-time = "2025-09-04T08:31:56.044Z" }, +] + +[[package]] +name = "nvidia-cufile" +version = "1.15.1.6" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/3f/70/4f193de89a48b71714e74602ee14d04e4019ad36a5a9f20c425776e72cd6/nvidia_cufile-1.15.1.6-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:08a3ecefae5a01c7f5117351c64f17c7c62efa5fffdbe24fc7d298da19cd0b44", size = 1223672, upload-time = "2025-09-04T08:32:22.779Z" }, + { url = "https://files.pythonhosted.org/packages/ab/73/cc4a14c9813a8a0d509417cf5f4bdaba76e924d58beb9864f5a7baceefbf/nvidia_cufile-1.15.1.6-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:bdc0deedc61f548bddf7733bdc216456c2fdb101d020e1ab4b88d232d5e2f6d1", size = 1136992, upload-time = "2025-09-04T08:32:14.119Z" }, +] + +[[package]] +name = "nvidia-curand" +version = "10.4.0.35" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/1e/72/7c2ae24fb6b63a32e6ae5d241cc65263ea18d08802aaae087d9f013335a2/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:133df5a7509c3e292aaa2b477afd0194f06ce4ea24d714d616ff36439cee349a", size = 61962106, upload-time = "2025-08-04T10:21:41.128Z" }, + { url = "https://files.pythonhosted.org/packages/a5/9f/be0a41ca4a4917abf5cb9ae0daff1a6060cc5de950aec0396de9f3b52bc5/nvidia_curand-10.4.0.35-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:1aee33a5da6e1db083fe2b90082def8915f30f3248d5896bcec36a579d941bfc", size = 59544258, upload-time = "2025-08-04T10:22:03.992Z" }, +] + +[[package]] +name = "nvidia-cusolver" +version = "12.0.4.66" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-cublas" }, + { name = "nvidia-cusparse" }, + { name = "nvidia-nvjitlink" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/c8/c3/b30c9e935fc01e3da443ec0116ed1b2a009bb867f5324d3f2d7e533e776b/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_aarch64.whl", hash = "sha256:02c2457eaa9e39de20f880f4bd8820e6a1cfb9f9a34f820eb12a155aa5bc92d2", size = 223467760, upload-time = "2025-09-04T08:33:04.222Z" }, + { url = "https://files.pythonhosted.org/packages/5f/67/cba3777620cdacb99102da4042883709c41c709f4b6323c10781a9c3aa34/nvidia_cusolver-12.0.4.66-py3-none-manylinux_2_27_x86_64.whl", hash = "sha256:0a759da5dea5c0ea10fd307de75cdeb59e7ea4fcb8add0924859b944babf1112", size = 200941980, upload-time = "2025-09-04T08:33:22.767Z" }, +] + +[[package]] +name = "nvidia-cusparse" +version = "12.6.3.3" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "nvidia-nvjitlink" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/f8/94/5c26f33738ae35276672f12615a64bd008ed5be6d1ebcb23579285d960a9/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:80bcc4662f23f1054ee334a15c72b8940402975e0eab63178fc7e670aa59472c", size = 162155568, upload-time = "2025-09-04T08:33:42.864Z" }, + { url = "https://files.pythonhosted.org/packages/fa/18/623c77619c31d62efd55302939756966f3ecc8d724a14dab2b75f1508850/nvidia_cusparse-12.6.3.3-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:2b3c89c88d01ee0e477cb7f82ef60a11a4bcd57b6b87c33f789350b59759360b", size = 145942937, upload-time = "2025-09-04T08:33:58.029Z" }, +] + +[[package]] +name = "nvidia-cusparselt-cu13" +version = "0.8.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/46/e1/cdc1797eadf82d3a9a575a19b33fdc871a97edbec42c00b5b5e914f4aff4/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_aarch64.whl", hash = "sha256:4dca476c50bf4780d46cd0bfbd82e2bc10a08e4fef7950917ce8d7578d22a23f", size = 221051344, upload-time = "2025-09-05T18:49:51.289Z" }, + { url = "https://files.pythonhosted.org/packages/34/7d/2661f2fb3ac4302f3a246f5fc030213ac60c1fe0bce84f9783dbd831dbb7/nvidia_cusparselt_cu13-0.8.1-py3-none-manylinux2014_x86_64.whl", hash = "sha256:786ce87568c303fadb5afcc7102d454cd3040d75f6f8626f5db460d1871f4dd0", size = 170148586, upload-time = "2025-09-05T18:50:50.248Z" }, +] + +[[package]] +name = "nvidia-nccl-cu13" +version = "2.29.7" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/72/0d/daf50d44177ee0cbc7ff0a0c91eb5ff676c82be42f9a970bc7597f440c3a/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_aarch64.whl", hash = "sha256:674a12383e3c38a1bcccae7d4f3633b37852230b6047883cb2f4c2d1b36d9bf5", size = 206014712, upload-time = "2026-03-03T05:34:20.843Z" }, + { url = "https://files.pythonhosted.org/packages/67/f4/58e4e91b6919367c7aafb8e36fce9aad1a3047e536bf7e2fd560927d3a4c/nvidia_nccl_cu13-2.29.7-py3-none-manylinux_2_18_x86_64.whl", hash = "sha256:edd81538446786ec3b73972543e53bb43bcaf0bfc8ef76cb679fcc390ffe136d", size = 205976000, upload-time = "2026-03-03T05:36:24.472Z" }, +] + +[[package]] +name = "nvidia-nvjitlink" +version = "13.5.37" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cc/1f/2321702b8d60b4b4dd18b957f61612dbac9cb1c07e940cf6582106b7c8b8/nvidia_nvjitlink-13.5.37-py3-none-manylinux2010_x86_64.manylinux_2_12_x86_64.whl", hash = "sha256:280d7cb9649704145f074b8dbde500de04ce02d0872e066e20a83c17bcaa93eb", size = 46642491, upload-time = "2026-11-04T23:33:31.696Z" }, + { url = "https://files.pythonhosted.org/packages/24/15/dd228f798cd01d7aeaf19d872b2b20f9aeafc1a7d8b6bfaa878b30b8d6f7/nvidia_nvjitlink-13.5.37-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:893f6f9a55b2720ed94913b5ba3332e972da8c78dfa2863d0244403dbd528ffc", size = 45253761, upload-time = "2026-11-04T23:33:22.854Z" }, +] + +[[package]] +name = "nvidia-nvshmem-cu13" +version = "3.4.5" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/dc/0f/05cc9c720236dcd2db9c1ab97fff629e96821be2e63103569da0c9b72f19/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:6dc2a197f38e5d0376ad52cd1a2a3617d3cdc150fd5966f4aee9bcebb1d68fe9", size = 60215947, upload-time = "2025-09-06T00:32:20.022Z" }, + { url = "https://files.pythonhosted.org/packages/3c/35/a9bf80a609e74e3b000fef598933235c908fcefcef9026042b8e6dfde2a9/nvidia_nvshmem_cu13-3.4.5-py3-none-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:290f0a2ee94c9f3687a02502f3b9299a9f9fe826e6d0287ee18482e78d495b80", size = 60412546, upload-time = "2025-09-06T00:32:41.564Z" }, +] + +[[package]] +name = "nvidia-nvtx" +version = "13.0.85" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c2/f3/d86c845465a2723ad7e1e5c36dcd75ddb82898b3f53be47ebd429fb2fa5d/nvidia_nvtx-13.0.85-py3-none-manylinux1_x86_64.manylinux_2_5_x86_64.whl", hash = "sha256:4936d1d6780fbe68db454f5e72a42ff64d1fd6397df9f363ae786930fd5c1cd4", size = 148047, upload-time = "2025-09-04T08:29:01.761Z" }, + { url = "https://files.pythonhosted.org/packages/a8/64/3708a90d1ebe202ffdeb7185f878a3c84d15c2b2c31858da2ce0583e2def/nvidia_nvtx-13.0.85-py3-none-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:cb7780edb6b14107373c835bf8b72e7a178bac7367e23da7acb108f973f157a6", size = 148878, upload-time = "2025-09-04T08:28:53.627Z" }, +] + +[[package]] +name = "packaging" +version = "26.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7d/fa/3944b40b07da9ce895c0e6303a5ab7d53da063554f534556b134a54d6093/packaging-26.3.tar.gz", hash = "sha256:94edc256424af38762eb31306eed28beb9f0efc50a8837492c9d6fd6004aed79", size = 313412, upload-time = "2026-08-04T18:15:28.737Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/63/34/ba1c580383c9eada3711951fef0795c80b829a078d72188184bcab9dd527/packaging-26.3-py3-none-any.whl", hash = "sha256:d7193f7c8e4e93f444fde0262bf90af30e16fa0ad0ad44cb553c87339b23cd1c", size = 129956, upload-time = "2026-08-04T18:15:27.159Z" }, +] + +[[package]] +name = "pandas" +version = "3.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, + { name = "python-dateutil" }, + { name = "tzdata", marker = "sys_platform == 'emscripten' or sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/17/ca/24c6bc92aca3d366146358e47f1d374c0e1a50763ef226fc71eff20a63fb/pandas-3.1.1.tar.gz", hash = "sha256:05fed3e3b7c99b226f160e29d7d6cb7ef39638c758cbfe42b3f24ba34f04b859", size = 5936163, upload-time = "2026-11-04T15:08:01.994Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f6/ee/2f6c4419fa2bf476ba2776c0fbae91e8bf6ab15c6b3e038d66da4d7824da/pandas-3.1.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:01bd1d4c5fc999324382d55499cef0f9cc7c1b09d91ae6dabe82f0237e43b3a0", size = 11612513, upload-time = "2026-11-04T15:06:14.21Z" }, + { url = "https://files.pythonhosted.org/packages/95/c0/6f818fd16987eba5ad77fcf8ba8a19e9cf19fad7df7f38ed61b933196d97/pandas-3.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:269716b079899a92953837d13ed215ef2d36dbf8dd3787faf617f1160a2f5062", size = 11189204, upload-time = "2026-11-04T15:06:17.012Z" }, + { url = "https://files.pythonhosted.org/packages/49/f7/5c2c9b7b3e3d08a8bc7f40e4e066d395d388c7b08b3788e6149a32e2f37a/pandas-3.1.1-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:57112bab44e336758121435cd01ccebc1e4fca56c28d95d7c03bf2418dedea6a", size = 11426801, upload-time = "2026-11-04T15:06:19.468Z" }, + { url = "https://files.pythonhosted.org/packages/79/c2/c8bc972d6dcba13910fc92b622420704a2f655dd6b01ed54269a1bf7c2d2/pandas-3.1.1-cp313-cp313-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:645fa00fd85cfced2d2c09dc116d3694f578501b1ce4899153fbe64788ecda98", size = 11978871, upload-time = "2026-11-04T15:06:21.974Z" }, + { url = "https://files.pythonhosted.org/packages/ac/35/69a3466b849afcf4d2b9a491e2e33264a34f5b201d74fcc3194c14c1c672/pandas-3.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:aafbba6ea1fb58f4e254823bf390f4efeced3b15ad4d06e86493ee0c22b35e7f", size = 12458201, upload-time = "2026-11-04T15:06:24.573Z" }, + { url = "https://files.pythonhosted.org/packages/d2/14/00f118829158f8b77f1f78434d6efafc4d65c16a2cca4f1b80c8a4e3f463/pandas-3.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:dedc76bfbba83fe43734ba9229190b4a987f6263ad734726bb28b4ecb93f4bf7", size = 13040280, upload-time = "2026-11-04T15:06:27.522Z" }, + { url = "https://files.pythonhosted.org/packages/38/ef/15b6a24451e75f2d48931062f73a5ebbd00d86394d750699dbd8d6b159b6/pandas-3.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:6d84760cc1bd799440a66b4df2ceb7a508870f3b8b4d8dda21befd62779cd3b4", size = 10732758, upload-time = "2026-11-04T15:06:29.957Z" }, + { url = "https://files.pythonhosted.org/packages/27/f3/0b64bded0e8003ba54589e03896edffd7aea543949f3d3c654cd10225a92/pandas-3.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:1eb3cca75e64bb1c0aab36e74413ad319f2f102daee222db7019c68e4f30cab5", size = 10119360, upload-time = "2026-11-04T15:06:32.623Z" }, +] + +[[package]] +name = "pillow" +version = "13.0.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ce/a4/9cc30690a394a8305e8be4c9036aa16d0dfddadd09079860b582f562496d/pillow-13.0.0.tar.gz", hash = "sha256:cdcd1ba258178f7356d74170c9a81ba4eab6a5d55748bc402a5a2a6fe6be3510", size = 47058631, upload-time = "2026-10-16T22:18:09.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/82/e2/9132d38df320e8099e2642d9fa538f18a7dfebf68a875a31725dc2a115aa/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:e98b4f91f99b24b1da72e10621ba181f7281922384a7403094debb4199de6c00", size = 4190620, upload-time = "2026-10-16T22:16:02.527Z" }, + { url = "https://files.pythonhosted.org/packages/cb/be/436dac0996876f65ef1916ffb711c5ef4af2ebc57414b6f16642e07f6b47/pillow-13.0.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:34fb3db1149c879343861831728c243c432d4a5afc8f1878ca7612ef8de2a033", size = 4290286, upload-time = "2026-10-16T22:16:04.861Z" }, + { url = "https://files.pythonhosted.org/packages/60/16/7c1007162e4169ea0d5bec47e2e0b2174f56c50cf5b8c02a1dc23e41037e/pillow-13.0.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:2d50500a4a3bc6469adcdb319cf05d688b08ca3bf0f22a05339f3b25b433a599", size = 3723169, upload-time = "2026-10-16T22:16:06.956Z" }, + { url = "https://files.pythonhosted.org/packages/08/bc/578ab2eaa04705a8978bd9be0fe15c3d43a8fc95097c4f7e39540e79e4fa/pillow-13.0.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:ef5fe6b7db3f501c56000ba8fe7c7e1a35ca1d45824fbeb95a67daa85cff4dbe", size = 5568469, upload-time = "2026-10-16T22:16:08.664Z" }, + { url = "https://files.pythonhosted.org/packages/98/c8/ccede3dcc4f274b80fb49199eed1ef34ba05566c8b71976b9d1f111da2e3/pillow-13.0.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f11a3c1358bb3c68012a7b1f41b223c3db9f7bfde90b481df028cfe1c3363313", size = 4852187, upload-time = "2026-10-16T22:16:10.693Z" }, + { url = "https://files.pythonhosted.org/packages/fb/3c/cd0770e96d20bfd990db024bcbd43897ff3e88da1f4782cf90ea231b1d4f/pillow-13.0.0-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:19b66ca0a4d25cc0200b381ce824c7ea090db61427315e73cfb05dbf1b35c369", size = 6515908, upload-time = "2026-10-16T22:16:12.896Z" }, + { url = "https://files.pythonhosted.org/packages/ef/fe/f5cdaa2d1c4086e757430f368c271a58ee29cfe7378e7ae7b9d964015c25/pillow-13.0.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:5f56499c1a74d2b862beb0c33b8016f99d095858455df9d21583bbbc1c15b582", size = 7142544, upload-time = "2026-10-16T22:16:14.844Z" }, + { url = "https://files.pythonhosted.org/packages/fb/b5/a54f6d44adbcd23737c8c12953f42be107e4cca64e247c0ca3a5b563061c/pillow-13.0.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2a14cd73d5e6c927f644b0110ee81f59c4ef506259ec9183904747f2caacc81", size = 6613097, upload-time = "2026-10-16T22:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/e6/b4/9e6c1207c21b2e91db0d15c16d30f3701ce5add1bd4da0e787761e66cb6e/pillow-13.0.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:08b826a9bf1265c76de04a42061d61ea6b109418b7826f28ff1ecdfaa26c5502", size = 7224846, upload-time = "2026-10-16T22:16:19.195Z" }, + { url = "https://files.pythonhosted.org/packages/78/9f/d3c3cb0518f3dd1eee0ef501535f53d15597a53c5c4118d178086143397a/pillow-13.0.0-cp313-cp313-win32.whl", hash = "sha256:12b0fa15879fe5a9d9eebe66e4e2d74128a773b1a4448010c9c714f45e04b9d8", size = 6516013, upload-time = "2026-10-16T22:16:21.389Z" }, + { url = "https://files.pythonhosted.org/packages/d7/ed/1b16fb66a37e1b9e41370b93b2c614c7da761a5b2a41dc333f7af4639962/pillow-13.0.0-cp313-cp313-win_amd64.whl", hash = "sha256:9dda0788a9932776a75d8bcc020076edc308ce2508b51f6739a45e3158b3fc42", size = 7284777, upload-time = "2026-10-16T22:16:23.393Z" }, + { url = "https://files.pythonhosted.org/packages/87/7d/8d02eba9f7ecc87f8e90f731e032cc4773802f2a843763afd0c66a535ff4/pillow-13.0.0-cp313-cp313-win_arm64.whl", hash = "sha256:40a266371ece581e5de13b6635ef78d7487824af80561b6ca27694a88c19bc0f", size = 2698826, upload-time = "2026-10-16T22:16:25.382Z" }, +] + +[[package]] +name = "pluggy" +version = "1.7.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bf/db/7fc19e6f2dc92a966727031389fc2e08b558f0f25eb7403c1119ad4713cd/pluggy-1.7.0.tar.gz", hash = "sha256:d1eaa46ebb595891b860ab086b4d09c8588af65ebd4361b8e8f4bb8920b90ba8", size = 123304, upload-time = "2026-10-15T09:50:58.343Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/40/9e/2b38731e0fc536806f16490e1a12d7f0dc2a1235aa8cc07bcc75416a7daa/pluggy-1.7.0-py3-none-any.whl", hash = "sha256:7dd7b0d8832ba3cb632c306926ded123429211b83641b35dc5c41ad2d34f9bec", size = 27082, upload-time = "2026-10-15T09:50:56.808Z" }, +] + +[[package]] +name = "propcache" +version = "0.5.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/b3/9a/9fbf4e4ec0c2d7f1c32519fff782ef467859b8faa9fbc5331a96f6395d43/propcache-0.5.4.tar.gz", hash = "sha256:ff6b113f50bc066a698db5d944d2c6dc7507168dd3341e255a8892fd0715a558", size = 61545, upload-time = "2026-09-16T00:17:14.386Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/78/4c/3b1365d58a667689e067e13d055fcd92bdf8d9a2fca3d9201b47ed5b3631/propcache-0.5.4-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:36c0d9db44b523ef93d03341b1c42d69ff01d673c053d1b1c6c3a363bcaa39ba", size = 85290, upload-time = "2026-09-16T00:14:52.342Z" }, + { url = "https://files.pythonhosted.org/packages/8f/61/5f9c29c3aa67c30238c4eadf95149b1d983a48f69b86b0cff927a7d6df13/propcache-0.5.4-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e1d52a05dc417279f7e5c7618c5dfbbc29923aaf9bc0a5c1802ddcebf54c61a0", size = 50027, upload-time = "2026-09-16T00:14:53.67Z" }, + { url = "https://files.pythonhosted.org/packages/25/7d/c1ab1ef09e9d4d835be5d58c0a32a1e1de8397abaa4e502a9d4141328cad/propcache-0.5.4-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:44149f46500a0a41b95b4d99c2e586a77319539730607b9892974a092788b111", size = 51425, upload-time = "2026-09-16T00:14:54.826Z" }, + { url = "https://files.pythonhosted.org/packages/73/36/0093091ebb270fcd1bc1f6e095f93b2e0ed7f1011c28837dc2dbe5f96b99/propcache-0.5.4-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:dbab5f5ff6897c81f355d079010cdae85b02e5a0b518b5251523b8ad8ae9ac3c", size = 233595, upload-time = "2026-09-16T00:14:56.09Z" }, + { url = "https://files.pythonhosted.org/packages/ae/8f/0de9d4c8e05ce0be71b436919a216bd7fc5cc6e2691c0602295efb22b9ed/propcache-0.5.4-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:c3e98c55bde2bcf7db3c70d1aed7ae9aa8aebbf19a250c66645cde44cdb8b867", size = 240318, upload-time = "2026-09-16T00:14:57.674Z" }, + { url = "https://files.pythonhosted.org/packages/7d/71/2b35e91455209b85ee98f7859583e0814fab57d3af0f2381aaee34c37304/propcache-0.5.4-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:db3ae52ccc150dbc84704e9d642743897f3e1c54742ff34cacb661e52e3818a9", size = 246649, upload-time = "2026-09-16T00:14:59.352Z" }, + { url = "https://files.pythonhosted.org/packages/ed/74/08e6c1faf26ee2732023a3828787ba535557122774f4a386b1f715cbd8e0/propcache-0.5.4-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f85915e00dcb1cd9f2f890ead064ed40a27df06f0db65be427b29482ae357572", size = 234316, upload-time = "2026-09-16T00:15:00.696Z" }, + { url = "https://files.pythonhosted.org/packages/5c/9a/08385733c9321c9bb78039d3ff31045e4fca962d9665023c4eb70f998819/propcache-0.5.4-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:c2ba30a89035b57b73e00475de948521602f543d79ce01db10b04b36c4c76fc8", size = 204666, upload-time = "2026-09-16T00:15:02.019Z" }, + { url = "https://files.pythonhosted.org/packages/1d/f4/e87bc7629af9a14a752b218764a78742d73c2c563ac58315da6841f0cbe4/propcache-0.5.4-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:ae58f361bd5dae942717c65d3413b478c70aea9c462599e7b9adad3731db3894", size = 225900, upload-time = "2026-09-16T00:15:03.394Z" }, + { url = "https://files.pythonhosted.org/packages/d9/6d/11014938d3fe9bea2ea2dcf930f26ed565bfb2f5be3c756362ea48c92636/propcache-0.5.4-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:96f7c5c15656040ddcbc51e56dc59b58aa25999d743c126abd425b9766ab43e9", size = 219988, upload-time = "2026-09-16T00:15:04.811Z" }, + { url = "https://files.pythonhosted.org/packages/dc/72/fbf17c589f92c0b3bbf6709a425661f8ef2ed0d46b38985a7d7b5a0f6b91/propcache-0.5.4-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:7cc528e760a8af06f2b13e9b9f362cd90c7c718ea61228a96dbd31ba16ed7f47", size = 233611, upload-time = "2026-09-16T00:15:06.498Z" }, + { url = "https://files.pythonhosted.org/packages/55/7e/dbd637572a279692e5518d117274a9331bf5faac59f191d30e82521a3ec7/propcache-0.5.4-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:425f8cc86ab5018b4b8d4a23bc8e74d964bd3d757c3702e301aa79be76c53f6c", size = 204333, upload-time = "2026-09-16T00:15:07.961Z" }, + { url = "https://files.pythonhosted.org/packages/ba/5a/f99c92068f1e0f5c886899ce0e4a619db376ca98c5279d93f95bd86906af/propcache-0.5.4-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:a5793c7698a53f56f4a1889a4737c7eeb1b7ad0842fa6b1abca22913ff79c8c1", size = 235177, upload-time = "2026-09-16T00:15:09.334Z" }, + { url = "https://files.pythonhosted.org/packages/ee/28/95456fabd2daf6be89049a13fbf03341756014d2959c83d12957d4c49694/propcache-0.5.4-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:c02c0e570c5c7e077b0181a9f3cdb7d4c3617d1cda6b5c95bd5d34022923d82c", size = 228982, upload-time = "2026-09-16T00:15:10.729Z" }, + { url = "https://files.pythonhosted.org/packages/b1/bb/df90f62c9cf7c93ea235f6f9405143bba802914607317266dd81fc8d737e/propcache-0.5.4-cp313-cp313-win32.whl", hash = "sha256:3e413d7a4a9b4866b7a761d6060d434b64d23cd35122eda3b026a0bbe8196b25", size = 42611, upload-time = "2026-09-16T00:15:12.111Z" }, + { url = "https://files.pythonhosted.org/packages/01/bc/e0a7b84af04ec02d73a48aa71f091e1e4a2107e3074b7ce12195b66901f4/propcache-0.5.4-cp313-cp313-win_amd64.whl", hash = "sha256:0c889f6fa84957bc7e8b4eab71fd16a0455068d5045e3aa40c733071d2b2fd77", size = 45342, upload-time = "2026-09-16T00:15:13.519Z" }, + { url = "https://files.pythonhosted.org/packages/9a/70/50b031cafe72a5c1878b903ee87303f71313345566bf3d6ec202e5ddc9ec/propcache-0.5.4-cp313-cp313-win_arm64.whl", hash = "sha256:69fc35c0779522da366c563e5faf203ffc1f8ff0021d5b1337fa4efa5be73177", size = 42408, upload-time = "2026-09-16T00:15:14.788Z" }, + { url = "https://files.pythonhosted.org/packages/f5/cd/785c64ed382f3f04201870267b02783f63b4678c2acfddc177a3ebcc2727/propcache-0.5.4-py3-none-any.whl", hash = "sha256:62c60aec739ed00124573cce1178138fd690c7676352d67a37328c1cf51d7468", size = 16338, upload-time = "2026-09-16T00:17:13.106Z" }, +] + +[[package]] +name = "psutil" +version = "7.1.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e1/88/bdd0a41e5857d5d703287598cbf08dad90aed56774ea52ae071bae9071b6/psutil-7.1.3.tar.gz", hash = "sha256:6c86281738d77335af7aec228328e944b30930899ea760ecf33a4dba66be5e74", size = 489059, upload-time = "2025-11-02T12:25:54.619Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/bd/93/0c49e776b8734fef56ec9c5c57f923922f2cf0497d62e0f419465f28f3d0/psutil-7.1.3-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0005da714eee687b4b8decd3d6cc7c6db36215c9e74e5ad2264b90c3df7d92dc", size = 239751, upload-time = "2025-11-02T12:25:58.161Z" }, + { url = "https://files.pythonhosted.org/packages/6f/8d/b31e39c769e70780f007969815195a55c81a63efebdd4dbe9e7a113adb2f/psutil-7.1.3-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:19644c85dcb987e35eeeaefdc3915d059dac7bd1167cdcdbf27e0ce2df0c08c0", size = 240368, upload-time = "2025-11-02T12:26:00.491Z" }, + { url = "https://files.pythonhosted.org/packages/62/61/23fd4acc3c9eebbf6b6c78bcd89e5d020cfde4acf0a9233e9d4e3fa698b4/psutil-7.1.3-cp313-cp313t-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:95ef04cf2e5ba0ab9eaafc4a11eaae91b44f4ef5541acd2ee91d9108d00d59a7", size = 287134, upload-time = "2025-11-02T12:26:02.613Z" }, + { url = "https://files.pythonhosted.org/packages/30/1c/f921a009ea9ceb51aa355cb0cc118f68d354db36eae18174bab63affb3e6/psutil-7.1.3-cp313-cp313t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1068c303be3a72f8e18e412c5b2a8f6d31750fb152f9cb106b54090296c9d251", size = 289904, upload-time = "2025-11-02T12:26:05.207Z" }, + { url = "https://files.pythonhosted.org/packages/a6/82/62d68066e13e46a5116df187d319d1724b3f437ddd0f958756fc052677f4/psutil-7.1.3-cp313-cp313t-win_amd64.whl", hash = "sha256:18349c5c24b06ac5612c0428ec2a0331c26443d259e2a0144a9b24b4395b58fa", size = 249642, upload-time = "2025-11-02T12:26:07.447Z" }, + { url = "https://files.pythonhosted.org/packages/df/ad/c1cd5fe965c14a0392112f68362cfceb5230819dbb5b1888950d18a11d9f/psutil-7.1.3-cp313-cp313t-win_arm64.whl", hash = "sha256:c525ffa774fe4496282fb0b1187725793de3e7c6b29e41562733cae9ada151ee", size = 245518, upload-time = "2025-11-02T12:26:09.719Z" }, + { url = "https://files.pythonhosted.org/packages/ef/94/46b9154a800253e7ecff5aaacdf8ebf43db99de4a2dfa18575b02548654e/psutil-7.1.3-cp36-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2bdbcd0e58ca14996a42adf3621a6244f1bb2e2e528886959c72cf1e326677ab", size = 238359, upload-time = "2025-11-02T12:26:25.284Z" }, + { url = "https://files.pythonhosted.org/packages/68/3a/9f93cff5c025029a36d9a92fef47220ab4692ee7f2be0fba9f92813d0cb8/psutil-7.1.3-cp36-abi3-macosx_11_0_arm64.whl", hash = "sha256:bc31fa00f1fbc3c3802141eede66f3a2d51d89716a194bf2cd6fc68310a19880", size = 239171, upload-time = "2025-11-02T12:26:27.23Z" }, + { url = "https://files.pythonhosted.org/packages/ce/b1/5f49af514f76431ba4eea935b8ad3725cdeb397e9245ab919dbc1d1dc20f/psutil-7.1.3-cp36-abi3-manylinux2010_x86_64.manylinux_2_12_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3bb428f9f05c1225a558f53e30ccbad9930b11c3fc206836242de1091d3e7dd3", size = 263261, upload-time = "2025-11-02T12:26:29.48Z" }, + { url = "https://files.pythonhosted.org/packages/e0/95/992c8816a74016eb095e73585d747e0a8ea21a061ed3689474fabb29a395/psutil-7.1.3-cp36-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:56d974e02ca2c8eb4812c3f76c30e28836fffc311d55d979f1465c1feeb2b68b", size = 264635, upload-time = "2025-11-02T12:26:31.74Z" }, + { url = "https://files.pythonhosted.org/packages/55/4c/c3ed1a622b6ae2fd3c945a366e64eb35247a31e4db16cf5095e269e8eb3c/psutil-7.1.3-cp37-abi3-win_amd64.whl", hash = "sha256:f39c2c19fe824b47484b96f9692932248a54c43799a84282cfe58d05a6449efd", size = 247633, upload-time = "2025-11-02T12:26:33.887Z" }, + { url = "https://files.pythonhosted.org/packages/c9/ad/33b2ccec09bf96c2b2ef3f9a6f66baac8253d7565d8839e024a6b905d45d/psutil-7.1.3-cp37-abi3-win_arm64.whl", hash = "sha256:bd0d69cee829226a761e92f28140bec9a5ee9d5b4fb4b0cc589068dbfff559b1", size = 244608, upload-time = "2025-11-02T12:26:36.136Z" }, +] + +[[package]] +name = "pyarrow" +version = "26.0.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/bc/5e/9cb2a56d5e293aab4e2fbecc5b0620d93227d66b8d5a63c554c31e1f80fe/pyarrow-26.0.1.tar.gz", hash = "sha256:93affcbd8a343e98dc19e9ec8fe17271ebf8fe98102d8b7454175074409f8b72", size = 1237985, upload-time = "2026-11-03T10:54:17.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/15/b8/c31c51fbe7df901817d88c73eeec25079d0da5f7c7b67fc0bf071f6a2df5/pyarrow-26.0.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:4cb739ccb87292c673e1f69819b68432a73bb8bb456e8599641bba9183a8a1dd", size = 37292947, upload-time = "2026-11-03T10:50:12.333Z" }, + { url = "https://files.pythonhosted.org/packages/fd/63/0c2559ae33ce59d2ca5ce74117676f8ff8da4cf102729a158ea46415eb50/pyarrow-26.0.1-cp313-cp313-macosx_12_0_x86_64.whl", hash = "sha256:50b40aea92f43b2b6da3427548a5337741b4b93b92e8015a8a3eefc0e75acca2", size = 39767535, upload-time = "2026-11-03T10:50:18.254Z" }, + { url = "https://files.pythonhosted.org/packages/31/02/d9462d1ae4e54c3964af38316a802b29c28970b7d375722ef190af736640/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:a3a79661404ba3d41b7c9a45cb56113246a244b38cb1393fadae289bc66b91b4", size = 51815955, upload-time = "2026-11-03T10:50:25.332Z" }, + { url = "https://files.pythonhosted.org/packages/96/54/33c2df56948d88a4d83a52999a4a81a4871b2de481ff25ccd6f5ccd2589a/pyarrow-26.0.1-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:f71221bbc7707e3fad920d0478db9350791d4714ec445299ee0d56559fbc156c", size = 55038406, upload-time = "2026-11-03T10:50:32.551Z" }, + { url = "https://files.pythonhosted.org/packages/99/57/8e1f886ee96c7edab89ab6f15fbb00c85c2bb2173f3cb504925731d00564/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:8ccfb9958bcd09f34678c64fb42a0e270b47cd092ae79578da51e0d7bb144296", size = 55437362, upload-time = "2026-11-03T10:50:39.89Z" }, + { url = "https://files.pythonhosted.org/packages/8c/c3/d87939a5f6cd30bb406bad6c20926fcedafc52ec5629f6eb27e4cd5db709/pyarrow-26.0.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:029e881af986375a2731da79c999fe734a72547fabb16503d65fc079d4bc7eb2", size = 58618865, upload-time = "2026-11-03T10:50:48.029Z" }, + { url = "https://files.pythonhosted.org/packages/c1/9e/b6c8afec2ffc06bbd00a88326826f9d66e4bbca752c0837ee8e2dbf2238f/pyarrow-26.0.1-cp313-cp313-win_amd64.whl", hash = "sha256:8196f36a2f4cb8d2d6ef3651941b80e5ccf125d7653657d99af5bb298e7a7026", size = 28989592, upload-time = "2026-11-03T10:50:53.384Z" }, +] + +[[package]] +name = "pygments" +version = "2.21.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/49/2e/ced460408999b33da6b31b0021b0f37d329e202d4169aeb164493778f25b/pygments-2.21.0.tar.gz", hash = "sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c", size = 5005329, upload-time = "2026-08-17T08:02:48.824Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/46/17f022dd3e953bf20a04a028a21ec746d942f8d2af30fa0f124fa0e6a684/pygments-2.21.0-py3-none-any.whl", hash = "sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9", size = 1250147, upload-time = "2026-08-17T08:02:44.912Z" }, +] + +[[package]] +name = "pyparsing" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/11/b213bebff182584360cb8d17c72c1677fec5c5c228de439e63bcf8ab1c8f/pyparsing-3.3.3.tar.gz", hash = "sha256:928ae7e20211f3b6f3915a72f06a0cfd29ab9d24279dd6346b6b1a7146397d36", size = 1050487, upload-time = "2026-09-20T20:59:05.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" }, +] + +[[package]] +name = "pytest" +version = "8.4.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, + { name = "iniconfig" }, + { name = "packaging" }, + { name = "pluggy" }, + { name = "pygments" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/a3/5c/00a0e072241553e1a7496d638deababa67c5058571567b92a7eaa258397c/pytest-8.4.2.tar.gz", hash = "sha256:86c0d0b93306b961d58d62a4db4879f27fe25513d4b969df351abdddb3c30e01", size = 1519618, upload-time = "2025-09-04T14:34:22.711Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a8/a4/20da314d277121d6534b3a980b29035dcd51e6744bd79075a6ce8fa4eb8d/pytest-8.4.2-py3-none-any.whl", hash = "sha256:872f880de3fc3a5bdc88a11b39c9710c3497a547cfa9320bc3c5e62fbf272e79", size = 365750, upload-time = "2025-09-04T14:34:20.226Z" }, +] + +[[package]] +name = "python-dateutil" +version = "4.0.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tzdata" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/18/39/b3927f3616f6223832f9b760e4208e8a7c7e1dea2b4d9ad7d32a5d214c3a/python_dateutil-4.0.0.tar.gz", hash = "sha256:d7295ff14fdc0f92f662100bfb6c551d160ca090f2939f1ec5b9794265c03f06", size = 250419, upload-time = "2026-11-01T07:02:42.426Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2f/a9/52b89563d154433d79b51ed1eb4842bf7334cb2696891a7fe135618853d7/python_dateutil-4.0.0-py3-none-any.whl", hash = "sha256:a5e246f79eb80475e691bf93862cead98decd8a498cf53ba0516fcdc0f50dc1c", size = 92853, upload-time = "2026-11-01T07:02:40.797Z" }, +] + +[[package]] +name = "pyyaml" +version = "6.0.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/05/8e/961c0007c59b8dd7729d542c61a4d537767a59645b82a0b521206e1e25c2/pyyaml-6.0.3.tar.gz", hash = "sha256:d76623373421df22fb4cf8817020cbb7ef15c725b9d5e45f17e189bfc384190f", size = 130960, upload-time = "2025-09-25T21:33:16.546Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/d1/11/0fd08f8192109f7169db964b5707a2f1e8b745d4e239b784a5a1dd80d1db/pyyaml-6.0.3-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8da9669d359f02c0b91ccc01cac4a67f16afec0dac22c2ad09f46bee0697eba8", size = 181669, upload-time = "2025-09-25T21:32:23.673Z" }, + { url = "https://files.pythonhosted.org/packages/b1/16/95309993f1d3748cd644e02e38b75d50cbc0d9561d21f390a76242ce073f/pyyaml-6.0.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2283a07e2c21a2aa78d9c4442724ec1eb15f5e42a723b99cb3d822d48f5f7ad1", size = 173252, upload-time = "2025-09-25T21:32:25.149Z" }, + { url = "https://files.pythonhosted.org/packages/50/31/b20f376d3f810b9b2371e72ef5adb33879b25edb7a6d072cb7ca0c486398/pyyaml-6.0.3-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ee2922902c45ae8ccada2c5b501ab86c36525b883eff4255313a253a3160861c", size = 767081, upload-time = "2025-09-25T21:32:26.575Z" }, + { url = "https://files.pythonhosted.org/packages/49/1e/a55ca81e949270d5d4432fbbd19dfea5321eda7c41a849d443dc92fd1ff7/pyyaml-6.0.3-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a33284e20b78bd4a18c8c2282d549d10bc8408a2a7ff57653c0cf0b9be0afce5", size = 841159, upload-time = "2025-09-25T21:32:27.727Z" }, + { url = "https://files.pythonhosted.org/packages/74/27/e5b8f34d02d9995b80abcef563ea1f8b56d20134d8f4e5e81733b1feceb2/pyyaml-6.0.3-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0f29edc409a6392443abf94b9cf89ce99889a1dd5376d94316ae5145dfedd5d6", size = 801626, upload-time = "2025-09-25T21:32:28.878Z" }, + { url = "https://files.pythonhosted.org/packages/f9/11/ba845c23988798f40e52ba45f34849aa8a1f2d4af4b798588010792ebad6/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f7057c9a337546edc7973c0d3ba84ddcdf0daa14533c2065749c9075001090e6", size = 753613, upload-time = "2025-09-25T21:32:30.178Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e0/7966e1a7bfc0a45bf0a7fb6b98ea03fc9b8d84fa7f2229e9659680b69ee3/pyyaml-6.0.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:eda16858a3cab07b80edaf74336ece1f986ba330fdb8ee0d6c0d68fe82bc96be", size = 794115, upload-time = "2025-09-25T21:32:31.353Z" }, + { url = "https://files.pythonhosted.org/packages/de/94/980b50a6531b3019e45ddeada0626d45fa85cbe22300844a7983285bed3b/pyyaml-6.0.3-cp313-cp313-win32.whl", hash = "sha256:d0eae10f8159e8fdad514efdc92d74fd8d682c933a6dd088030f3834bc8e6b26", size = 137427, upload-time = "2025-09-25T21:32:32.58Z" }, + { url = "https://files.pythonhosted.org/packages/97/c9/39d5b874e8b28845e4ec2202b5da735d0199dbe5b8fb85f91398814a9a46/pyyaml-6.0.3-cp313-cp313-win_amd64.whl", hash = "sha256:79005a0d97d5ddabfeeea4cf676af11e647e41d81c9a7722a193022accdb6b7c", size = 154090, upload-time = "2025-09-25T21:32:33.659Z" }, + { url = "https://files.pythonhosted.org/packages/73/e8/2bdf3ca2090f68bb3d75b44da7bbc71843b19c9f2b9cb9b0f4ab7a5a4329/pyyaml-6.0.3-cp313-cp313-win_arm64.whl", hash = "sha256:5498cd1645aa724a7c71c8f378eb29ebe23da2fc0d7a08071d89469bf1d2defb", size = 140246, upload-time = "2025-09-25T21:32:34.663Z" }, +] + +[[package]] +name = "regex" +version = "2026.11.9" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/61/27/a5afeb952577b84ee5fe48b8b9ce47ae662dbb69cc5b76c28eff98f83b1e/regex-2026.11.9.tar.gz", hash = "sha256:316a70fbd70e999c9664681cb0eb5b4982b2cc0f623c7c86a8a112e1bd4c6277", size = 419513, upload-time = "2026-11-09T00:42:09.786Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/90/55/7b6278e0babda54fe4b619c13019aef42247de912180777d49afae8eefac/regex-2026.11.9-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:224b73a26a1e64cf87fc8da9ee7a9994f152b92a728a7786b5c002fcebb205b8", size = 498358, upload-time = "2026-11-09T00:40:22.495Z" }, + { url = "https://files.pythonhosted.org/packages/4c/96/e37e54801fcd80fe7d2929708cd0c459aef588bc887da2de58a7c3c963d8/regex-2026.11.9-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:6852035568af30020a538f945863d2dca3d5baadfe9d9387f9d54de2f1b30a45", size = 296847, upload-time = "2026-11-09T00:40:23.623Z" }, + { url = "https://files.pythonhosted.org/packages/f6/69/8bb15a5dcc3f8c9a57b069847fd65552bb7d1de22861e283e0139e5d5c71/regex-2026.11.9-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:24c9479dc1215a1ebc96fedc9a0cd026240209e9b69aa223df411c443bdf1d93", size = 294046, upload-time = "2026-11-09T00:40:25.026Z" }, + { url = "https://files.pythonhosted.org/packages/19/74/b13616c437d4141e9b73ef8f44d2be36058dc83cc1316048a081b73eead7/regex-2026.11.9-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c5e3b575067d381f59cd6896a0126aef5dfb80a16b03594e8fc86bdc9dcf1cec", size = 804872, upload-time = "2026-11-09T00:40:26.115Z" }, + { url = "https://files.pythonhosted.org/packages/45/e4/8a0597242b57ef983f50ce84a2f35ba681e72333ff34aadee2805de2deea/regex-2026.11.9-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:38225e2f77e094c5a118e64af55655192eb16966b1e61ed8f4674ea94bedbb04", size = 878457, upload-time = "2026-11-09T00:40:27.223Z" }, + { url = "https://files.pythonhosted.org/packages/2e/a7/3ed73ae7e9b7ae09f80d09a59ee21fefc4a3e33a08e2b039934e57b86a76/regex-2026.11.9-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b4957fa9142e4850f454e7e76366245677cb917c608d7f8088b0105c9948db2f", size = 919209, upload-time = "2026-11-09T00:40:28.425Z" }, + { url = "https://files.pythonhosted.org/packages/35/3c/d6f2b69b141b3d0aa82d69fbbfe2b38dc49138e3f6843cc763774202d024/regex-2026.11.9-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:32183c31b090e1ee2bbb60898d236addc0029bf04a6def37175c2bb5419dcfb5", size = 808929, upload-time = "2026-11-09T00:40:29.882Z" }, + { url = "https://files.pythonhosted.org/packages/68/68/2fbbb66b68d0babc7260c1538f5d422f9edbbbdf4d6e5c916f8fe7c0fcbc/regex-2026.11.9-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:86b0004630d82a7fa993a40c599d77180622ba356d68dc48eef8f47e8c836853", size = 783522, upload-time = "2026-11-09T00:40:31.095Z" }, + { url = "https://files.pythonhosted.org/packages/8f/fa/50f1b4e85430cb4aba15320eb0a8204e48d175317168771b8c05a00373c5/regex-2026.11.9-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:d6bf83cfc92e7f6402cc10b8542fc562d4183929bdf126a0ccea1c15b55a109f", size = 791604, upload-time = "2026-11-09T00:40:33.218Z" }, + { url = "https://files.pythonhosted.org/packages/96/6e/fbf5139423566e051cedd6f71c97bc16fb34653e921b6654e24a0c16df8a/regex-2026.11.9-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c88a1749323036f3b3f67c32c1df4c6f2889f1ad5508eb3b66032019e0acb14b", size = 866818, upload-time = "2026-11-09T00:40:34.861Z" }, + { url = "https://files.pythonhosted.org/packages/f0/d7/d873103dffac3b4558437dd622edff275f88a0cd32d0bed5175ac0c389b5/regex-2026.11.9-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:0dbed59cc01d38778091845ac229dc24b909bc326b82d3043972b0acd1349bb6", size = 770466, upload-time = "2026-11-09T00:40:36.345Z" }, + { url = "https://files.pythonhosted.org/packages/6c/71/d681e7949e91de573808a0d609a84d99411fad3680d346e436f68528c4fd/regex-2026.11.9-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:d0517aff825aaa7a242ce85938ff4a51fa73633ec14a0b6639f658b29a78e6f2", size = 861497, upload-time = "2026-11-09T00:40:37.572Z" }, + { url = "https://files.pythonhosted.org/packages/5c/17/052721465a9e96a340b73d6bc7bffacd7bd9d57b4ddc38ac95e6671b7882/regex-2026.11.9-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:a1919cb74f076c93b3d7344ba8ec930e9aa6d70272801779ba0e9bb48eb12d4f", size = 795612, upload-time = "2026-11-09T00:40:38.81Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ad/f5eeae00983238972bbcd3b31122437f729299d4a7ecd661b07a61448a6f/regex-2026.11.9-cp313-cp313-win32.whl", hash = "sha256:bd66446f042de0b2fdc4870f590eed990285d7c5d677545dc5aa8fd0dcf5f0e9", size = 269754, upload-time = "2026-11-09T00:40:40.004Z" }, + { url = "https://files.pythonhosted.org/packages/f3/e5/27d16943df68676aba97db64e58b10702627eac1b983d96342b80b71f6c1/regex-2026.11.9-cp313-cp313-win_amd64.whl", hash = "sha256:19d36876d5783f157f280e67e51038a63a30630bd069528070d83a711f170e99", size = 280845, upload-time = "2026-11-09T00:40:41.348Z" }, + { url = "https://files.pythonhosted.org/packages/6d/34/74fbef82831900af4da247486576f867e6ffdb531841adc771af5797b213/regex-2026.11.9-cp313-cp313-win_arm64.whl", hash = "sha256:2062558aead9322ce54479b0ac356453d1455a30ec40d16b263b4cb0dcd5fd0d", size = 280234, upload-time = "2026-11-09T00:40:43.225Z" }, +] + +[[package]] +name = "requests" +version = "2.34.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "charset-normalizer" }, + { name = "idna" }, + { name = "urllib3" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/ac/c3/e2a2b89f2d3e2179abd6d00ebd70bff6273f37fb3e0cc209f48b39d00cbf/requests-2.34.2.tar.gz", hash = "sha256:f288924cae4e29463698d6d60bc6a4da69c89185ad1e0bcc4104f584e960b9ed", size = 142856, upload-time = "2026-05-14T19:25:27.735Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a0/f4/c67b0b3f1b9245e8d266f0f112c500d50e5b4e83cb6f3b71b6528104182a/requests-2.34.2-py3-none-any.whl", hash = "sha256:2a0d60c172f83ac6ab31e4554906c0f3b3588d37b5cb939b1c061f4907e278e0", size = 73075, upload-time = "2026-05-14T19:25:26.443Z" }, +] + +[[package]] +name = "safetensors" +version = "0.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/45/06/f955dbbb1859e3bd23c8ac6141af5106e7ad5fedec4a3a6e3d60f94b7001/safetensors-0.8.0.tar.gz", hash = "sha256:fabaf3e0f18a6618d9b36560682562157f77c2b71fcffc7b432be2baed9d753d", size = 325846, upload-time = "2026-06-09T07:52:25.563Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/39/a0/f718cda65b05407d228f97602cf60dca269c979867aa5beb25410de26cd3/safetensors-0.8.0-cp310-abi3-macosx_10_12_x86_64.whl", hash = "sha256:c554f85858e05226d3c2828e32395e677434685d6d94594a41643361c5e837f0", size = 473568, upload-time = "2026-06-09T07:52:18.829Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b1/fa7c600e7dceae12e9606c7578cbc9ff1e1ed55844883ee5c92205e86226/safetensors-0.8.0-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:c80201d22cbf405b80647a60ada77bba06c8fba2da2743ba1e89cdcc39a81f25", size = 484562, upload-time = "2026-06-09T07:52:17.518Z" }, + { url = "https://files.pythonhosted.org/packages/09/7d/65a7de0af421317bb36a067241e4235fff194eed60b961ed6d3f59a3fc60/safetensors-0.8.0-cp310-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:7a46e5ff292c356d6991e60942ba7f79817682d3a2cef0702136448cb9c4d235", size = 502844, upload-time = "2026-06-09T07:52:07.624Z" }, + { url = "https://files.pythonhosted.org/packages/91/4f/3175c9d75634e0e0dda0082794193521035edd7c70a6f212bf33ca06ddf4/safetensors-0.8.0-cp310-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4124502b78f03534117c848f87a39b8f31e577b15eff423bf8bfb95f2a8c30d0", size = 511823, upload-time = "2026-06-09T07:52:09.565Z" }, + { url = "https://files.pythonhosted.org/packages/20/87/846c289e7aa2299eff406335717cf43ce8777194ece8aad75772e0411615/safetensors-0.8.0-cp310-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:7bc0a787ba8a35be368ee3574edfa2b1ad389eebd0a72e482ae275490e3f6c98", size = 633461, upload-time = "2026-06-09T07:52:11.128Z" }, + { url = "https://files.pythonhosted.org/packages/76/22/8d64d9df2c45d5ded401df889d0ad90882804ca172d79ec4f0df8f727fe0/safetensors-0.8.0-cp310-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:040070828e36dc8e122178bbbd5830ff9e97920affb84cbe0f46442497bed358", size = 545148, upload-time = "2026-06-09T07:52:13.603Z" }, + { url = "https://files.pythonhosted.org/packages/28/50/f203ff3a3ddfe19308efc83c5a3a29ed02bf786732ec35e68bf9162f3365/safetensors-0.8.0-cp310-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:fd6f3f93c9a0a7cc2788ee63fb763353d4bd2e89b0751bc78fcf7dda00bea774", size = 516040, upload-time = "2026-06-09T07:52:16.29Z" }, + { url = "https://files.pythonhosted.org/packages/46/fb/cdaed17ceb2948784fd9c36b6fd3e951b608547cea81a48e8ee6f8cfdfcb/safetensors-0.8.0-cp310-abi3-manylinux_2_31_riscv64.whl", hash = "sha256:fcdd41ec4628fee5799f807c73c353629130fbd942aa23d83c623dd6c9d52d78", size = 513832, upload-time = "2026-06-09T07:52:12.37Z" }, + { url = "https://files.pythonhosted.org/packages/0d/49/1e15de264dcc3b77943d2d0c56a95809956883b1c2d6d585c792523f180b/safetensors-0.8.0-cp310-abi3-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8e9f537aa183a38ace122d27303dcd986b26bd2a7591f9181d7f0c396f4677ca", size = 559930, upload-time = "2026-06-09T07:52:14.743Z" }, + { url = "https://files.pythonhosted.org/packages/2a/43/bf38443278eab4b1be1fce2931e2b012ad9cb7df52ada751d0aab8f7659a/safetensors-0.8.0-cp310-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:87eec7ffed2b809f05a398a8becb7d013f19f7837cd15d9748580d6cf30dbaf4", size = 678670, upload-time = "2026-06-09T07:52:20.032Z" }, + { url = "https://files.pythonhosted.org/packages/72/e3/68cd3fa5b48488e84add63e04cb12f3bc28ae4638c06d4508c6e88823d0e/safetensors-0.8.0-cp310-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:4a95ae2b05d7726d751da4ebf626a2ca782b706e101bd894c95bc2450b1cffcc", size = 786679, upload-time = "2026-06-09T07:52:21.322Z" }, + { url = "https://files.pythonhosted.org/packages/29/4b/1c19c509d56e01f4fbb3d0a2e597450f6cc04d1d56cf52defb0a62dfd715/safetensors-0.8.0-cp310-abi3-musllinux_1_2_i686.whl", hash = "sha256:3ae091f16662658bdc019a4ff6cb4c085bb7d725eb5978b183ffd265863b6d2d", size = 765683, upload-time = "2026-06-09T07:52:22.594Z" }, + { url = "https://files.pythonhosted.org/packages/27/43/41c1621732edd934d868a00d1b891584c892a7b62a9aab82ea5a0a5623ee/safetensors-0.8.0-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:8e080062fcde23be189565e1c3305d16751a218ecf9412c8601e64204eb6f846", size = 722361, upload-time = "2026-06-09T07:52:23.924Z" }, + { url = "https://files.pythonhosted.org/packages/8e/3f/73ccf82579412b4a71c4ca673f10b5f1f888d7cf5af7fe24f27d30307be4/safetensors-0.8.0-cp310-abi3-win32.whl", hash = "sha256:2ddf52eac562eda224f99acfa7889d02968c1fd59a5b011ae7d8137c37e9c02d", size = 342401, upload-time = "2026-06-09T07:52:28.895Z" }, + { url = "https://files.pythonhosted.org/packages/1b/6d/3fba214c1e5e0f69991677ec3bc17023f0421776975e1de0c682dca475e2/safetensors-0.8.0-cp310-abi3-win_amd64.whl", hash = "sha256:096ec1a98435df7beb08853bb5aa9081a84f23d0adc67ed1a0a10550f608373f", size = 355540, upload-time = "2026-06-09T07:52:27.832Z" }, + { url = "https://files.pythonhosted.org/packages/8d/fc/7eedc3510d97878876e32774eebbeb61c43f148a96e915c84229a3e967aa/safetensors-0.8.0-cp310-abi3-win_arm64.whl", hash = "sha256:f7838e5135a406ad3e02efdcb8cf2e5397d368b0154537c4fec682dbc544d452", size = 340500, upload-time = "2026-06-09T07:52:26.745Z" }, +] + +[[package]] +name = "scikit-learn" +version = "1.7.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "joblib" }, + { name = "numpy" }, + { name = "scipy" }, + { name = "threadpoolctl" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/98/c2/a7855e41c9d285dfe86dc50b250978105dce513d6e459ea66a6aeb0e1e0c/scikit_learn-1.7.2.tar.gz", hash = "sha256:20e9e49ecd130598f1ca38a1d85090e1a600147b9c02fa6f15d69cb53d968fda", size = 7193136, upload-time = "2025-09-09T08:21:29.075Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ae/93/a3038cb0293037fd335f77f31fe053b89c72f17b1c8908c576c29d953e84/scikit_learn-1.7.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:0b7dacaa05e5d76759fb071558a8b5130f4845166d88654a0f9bdf3eb57851b7", size = 9212382, upload-time = "2025-09-09T08:20:54.731Z" }, + { url = "https://files.pythonhosted.org/packages/40/dd/9a88879b0c1104259136146e4742026b52df8540c39fec21a6383f8292c7/scikit_learn-1.7.2-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:abebbd61ad9e1deed54cca45caea8ad5f79e1b93173dece40bb8e0c658dbe6fe", size = 8592042, upload-time = "2025-09-09T08:20:57.313Z" }, + { url = "https://files.pythonhosted.org/packages/46/af/c5e286471b7d10871b811b72ae794ac5fe2989c0a2df07f0ec723030f5f5/scikit_learn-1.7.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:502c18e39849c0ea1a5d681af1dbcf15f6cce601aebb657aabbfe84133c1907f", size = 9434180, upload-time = "2025-09-09T08:20:59.671Z" }, + { url = "https://files.pythonhosted.org/packages/f1/fd/df59faa53312d585023b2da27e866524ffb8faf87a68516c23896c718320/scikit_learn-1.7.2-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7a4c328a71785382fe3fe676a9ecf2c86189249beff90bf85e22bdb7efaf9ae0", size = 9283660, upload-time = "2025-09-09T08:21:01.71Z" }, + { url = "https://files.pythonhosted.org/packages/a7/c7/03000262759d7b6f38c836ff9d512f438a70d8a8ddae68ee80de72dcfb63/scikit_learn-1.7.2-cp313-cp313-win_amd64.whl", hash = "sha256:63a9afd6f7b229aad94618c01c252ce9e6fa97918c5ca19c9a17a087d819440c", size = 8702057, upload-time = "2025-09-09T08:21:04.234Z" }, + { url = "https://files.pythonhosted.org/packages/55/87/ef5eb1f267084532c8e4aef98a28b6ffe7425acbfd64b5e2f2e066bc29b3/scikit_learn-1.7.2-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:9acb6c5e867447b4e1390930e3944a005e2cb115922e693c08a323421a6966e8", size = 9558731, upload-time = "2025-09-09T08:21:06.381Z" }, + { url = "https://files.pythonhosted.org/packages/93/f8/6c1e3fc14b10118068d7938878a9f3f4e6d7b74a8ddb1e5bed65159ccda8/scikit_learn-1.7.2-cp313-cp313t-macosx_12_0_arm64.whl", hash = "sha256:2a41e2a0ef45063e654152ec9d8bcfc39f7afce35b08902bfe290c2498a67a6a", size = 9038852, upload-time = "2025-09-09T08:21:08.628Z" }, + { url = "https://files.pythonhosted.org/packages/83/87/066cafc896ee540c34becf95d30375fe5cbe93c3b75a0ee9aa852cd60021/scikit_learn-1.7.2-cp313-cp313t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:98335fb98509b73385b3ab2bd0639b1f610541d3988ee675c670371d6a87aa7c", size = 9527094, upload-time = "2025-09-09T08:21:11.486Z" }, + { url = "https://files.pythonhosted.org/packages/9c/2b/4903e1ccafa1f6453b1ab78413938c8800633988c838aa0be386cbb33072/scikit_learn-1.7.2-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:191e5550980d45449126e23ed1d5e9e24b2c68329ee1f691a3987476e115e09c", size = 9367436, upload-time = "2025-09-09T08:21:13.602Z" }, + { url = "https://files.pythonhosted.org/packages/b5/aa/8444be3cfb10451617ff9d177b3c190288f4563e6c50ff02728be67ad094/scikit_learn-1.7.2-cp313-cp313t-win_amd64.whl", hash = "sha256:57dc4deb1d3762c75d685507fbd0bc17160144b2f2ba4ccea5dc285ab0d0e973", size = 9275749, upload-time = "2025-09-09T08:21:15.96Z" }, +] + +[[package]] +name = "scipy" +version = "1.18.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/7e/74/66de6258867beb2ef08f35f9f2ac017a52cacd5081714d239ff1a442d458/scipy-1.18.1.tar.gz", hash = "sha256:52c4b7422442aba924d03ad4019852b08a92e64ea187b933135687bfe2747307", size = 30781235, upload-time = "2026-08-21T23:28:50.599Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b6/55/4540ee0f9c42a9ad7109d0d1a8cc70de54c3572b01c6693a2b1c70e90ceb/scipy-1.18.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:3ab3523da44749156e1f68b464dc56af11ae4cbc5c739a49d05f32b982eca9f3", size = 31089958, upload-time = "2026-08-21T23:24:35.8Z" }, + { url = "https://files.pythonhosted.org/packages/2a/f5/769f36d14922b8071a43e95d24d18b6bdafad10d7f5cf647867e1ac052bc/scipy-1.18.1-cp313-cp313-macosx_12_0_arm64.whl", hash = "sha256:e6fb6a55cc0ba97b59a1f288fb86dc6fce8bdfc0fffcbfd015e3a954bf2a2d93", size = 28715106, upload-time = "2026-08-21T23:24:40.775Z" }, + { url = "https://files.pythonhosted.org/packages/9a/d7/21d890274f75ea37a8209d5519e72da3da90302e3b9fb8397a0918386a62/scipy-1.18.1-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:ea324d9dd34c38bfb9bec8ca4d1b407db97dbb74029f566b8e322b1b6fe56fe6", size = 20456846, upload-time = "2026-08-21T23:24:45.066Z" }, + { url = "https://files.pythonhosted.org/packages/ec/01/798430ecea2e78ec7c02663d5f71c007bb6abeca931080debd40d7fa55ea/scipy-1.18.1-cp313-cp313-macosx_14_0_x86_64.whl", hash = "sha256:75b00eb8fb802090aa903f4ea1c7f5a584779f967361e68b7e98e531cc2d7174", size = 23087986, upload-time = "2026-08-21T23:24:49.539Z" }, + { url = "https://files.pythonhosted.org/packages/e6/5f/4634e9d35c68496e4e34cb6946eafab044458e6cedab42b40b6588e475b6/scipy-1.18.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d416b16cccfd70fbf62400e84d0bb2f4e6af519a45557f1692c749b37f14b315", size = 33998146, upload-time = "2026-08-21T23:24:54.714Z" }, + { url = "https://files.pythonhosted.org/packages/41/48/6450ed9243315322bbc19ac57b9b70d66a20bf1d38d124c96bc4bf6af9ea/scipy-1.18.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:fdaf5ea890a6183d0565f51a61799d67081bd5b1cf03c5f4b3fd3732108625c9", size = 35312578, upload-time = "2026-08-21T23:25:00.44Z" }, + { url = "https://files.pythonhosted.org/packages/00/bd/bf5a4be6a3525676499f6dff307991739ff6fdcad1481b1aeb6745339f58/scipy-1.18.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:c825cef2f49e46753726a7181a8e199804a912b29519ada542c6ebc654951899", size = 35612621, upload-time = "2026-08-21T23:25:06.144Z" }, + { url = "https://files.pythonhosted.org/packages/bd/4e/3c45c33e00a77996c4b1cb707929f833ba7b1d522ee29f882512c330676d/scipy-1.18.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e3b417bf8c2c7c16e8f58ad91db17783ec911ac16e7b50eb6eab6e809b4f5b07", size = 37457323, upload-time = "2026-08-21T23:25:12.483Z" }, + { url = "https://files.pythonhosted.org/packages/93/0e/e0348fbc0dbab65c114cf78957e7dfeb49f8e8b556b4d930cc12ff195e18/scipy-1.18.1-cp313-cp313-win_amd64.whl", hash = "sha256:559ed65f60c1af5a03f3912605a1b5114f522c7c32fb23c3376ae8f03219fe28", size = 36622841, upload-time = "2026-08-21T23:25:18.722Z" }, + { url = "https://files.pythonhosted.org/packages/50/a8/6a77f5f267c555108f0a864b6db714363dab567a8266422a79a385f9232b/scipy-1.18.1-cp313-cp313-win_arm64.whl", hash = "sha256:cd479fc04dd9401e3b4f49e76518768ef99c4f517a98c284eb091fd725719adf", size = 24399315, upload-time = "2026-08-21T23:25:23.458Z" }, +] + +[[package]] +name = "sentencepiece" +version = "0.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/15/15/2e7a025fc62d764b151ae6d0f2a92f8081755ebe8d4a64099accc6f77ba6/sentencepiece-0.2.1.tar.gz", hash = "sha256:8138cec27c2f2282f4a34d9a016e3374cd40e5c6e9cb335063db66a0a3b71fad", size = 3228515, upload-time = "2025-08-12T07:00:51.718Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ba/4a/85fbe1706d4d04a7e826b53f327c4b80f849cf1c7b7c5e31a20a97d8f28b/sentencepiece-0.2.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:dcd8161eee7b41aae57ded06272905dbd680a0a04b91edd0f64790c796b2f706", size = 1943150, upload-time = "2025-08-12T06:59:53.588Z" }, + { url = "https://files.pythonhosted.org/packages/c2/83/4cfb393e287509fc2155480b9d184706ef8d9fa8cbf5505d02a5792bf220/sentencepiece-0.2.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:c6c8f42949f419ff8c7e9960dbadcfbc982d7b5efc2f6748210d3dd53a7de062", size = 1325651, upload-time = "2025-08-12T06:59:55.073Z" }, + { url = "https://files.pythonhosted.org/packages/8d/de/5a007fb53b1ab0aafc69d11a5a3dd72a289d5a3e78dcf2c3a3d9b14ffe93/sentencepiece-0.2.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:097f3394e99456e9e4efba1737c3749d7e23563dd1588ce71a3d007f25475fff", size = 1253641, upload-time = "2025-08-12T06:59:56.562Z" }, + { url = "https://files.pythonhosted.org/packages/2c/d2/f552be5928105588f4f4d66ee37dd4c61460d8097e62d0e2e0eec41bc61d/sentencepiece-0.2.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d7b670879c370d350557edabadbad1f6561a9e6968126e6debca4029e5547820", size = 1316271, upload-time = "2025-08-12T06:59:58.109Z" }, + { url = "https://files.pythonhosted.org/packages/96/df/0cfe748ace5485be740fed9476dee7877f109da32ed0d280312c94ec259f/sentencepiece-0.2.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:c7f0fd2f2693309e6628aeeb2e2faf6edd221134dfccac3308ca0de01f8dab47", size = 1387882, upload-time = "2025-08-12T07:00:00.701Z" }, + { url = "https://files.pythonhosted.org/packages/ac/dd/f7774d42a881ced8e1739f393ab1e82ece39fc9abd4779e28050c2e975b5/sentencepiece-0.2.1-cp313-cp313-win32.whl", hash = "sha256:92b3816aa2339355fda2c8c4e021a5de92180b00aaccaf5e2808972e77a4b22f", size = 999541, upload-time = "2025-08-12T07:00:02.709Z" }, + { url = "https://files.pythonhosted.org/packages/dd/e9/932b9eae6fd7019548321eee1ab8d5e3b3d1294df9d9a0c9ac517c7b636d/sentencepiece-0.2.1-cp313-cp313-win_amd64.whl", hash = "sha256:10ed3dab2044c47f7a2e7b4969b0c430420cdd45735d78c8f853191fa0e3148b", size = 1054669, upload-time = "2025-08-12T07:00:04.915Z" }, + { url = "https://files.pythonhosted.org/packages/c9/3a/76488a00ea7d6931689cda28726a1447d66bf1a4837943489314593d5596/sentencepiece-0.2.1-cp313-cp313-win_arm64.whl", hash = "sha256:ac650534e2251083c5f75dde4ff28896ce7c8904133dc8fef42780f4d5588fcd", size = 1033922, upload-time = "2025-08-12T07:00:06.496Z" }, + { url = "https://files.pythonhosted.org/packages/4a/b6/08fe2ce819e02ccb0296f4843e3f195764ce9829cbda61b7513f29b95718/sentencepiece-0.2.1-cp313-cp313t-macosx_10_13_universal2.whl", hash = "sha256:8dd4b477a7b069648d19363aad0cab9bad2f4e83b2d179be668efa672500dc94", size = 1946052, upload-time = "2025-08-12T07:00:08.136Z" }, + { url = "https://files.pythonhosted.org/packages/ab/d9/1ea0e740591ff4c6fc2b6eb1d7510d02f3fb885093f19b2f3abd1363b402/sentencepiece-0.2.1-cp313-cp313t-macosx_10_13_x86_64.whl", hash = "sha256:0c0f672da370cc490e4c59d89e12289778310a0e71d176c541e4834759e1ae07", size = 1327408, upload-time = "2025-08-12T07:00:09.572Z" }, + { url = "https://files.pythonhosted.org/packages/99/7e/1fb26e8a21613f6200e1ab88824d5d203714162cf2883248b517deb500b7/sentencepiece-0.2.1-cp313-cp313t-macosx_11_0_arm64.whl", hash = "sha256:ad8493bea8432dae8d6830365352350f3b4144415a1d09c4c8cb8d30cf3b6c3c", size = 1254857, upload-time = "2025-08-12T07:00:11.021Z" }, + { url = "https://files.pythonhosted.org/packages/bc/85/c72fd1f3c7a6010544d6ae07f8ddb38b5e2a7e33bd4318f87266c0bbafbf/sentencepiece-0.2.1-cp313-cp313t-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:b81a24733726e3678d2db63619acc5a8dccd074f7aa7a54ecd5ca33ca6d2d596", size = 1315722, upload-time = "2025-08-12T07:00:12.989Z" }, + { url = "https://files.pythonhosted.org/packages/4a/e8/661e5bd82a8aa641fd6c1020bd0e890ef73230a2b7215ddf9c8cd8e941c2/sentencepiece-0.2.1-cp313-cp313t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:0a81799d0a68d618e89063fb423c3001a034c893069135ffe51fee439ae474d6", size = 1387452, upload-time = "2025-08-12T07:00:15.088Z" }, + { url = "https://files.pythonhosted.org/packages/99/5e/ae66c361023a470afcbc1fbb8da722c72ea678a2fcd9a18f1a12598c7501/sentencepiece-0.2.1-cp313-cp313t-win32.whl", hash = "sha256:89a3ea015517c42c0341d0d962f3e6aaf2cf10d71b1932d475c44ba48d00aa2b", size = 1002501, upload-time = "2025-08-12T07:00:16.966Z" }, + { url = "https://files.pythonhosted.org/packages/c1/03/d332828c4ff764e16c1b56c2c8f9a33488bbe796b53fb6b9c4205ddbf167/sentencepiece-0.2.1-cp313-cp313t-win_amd64.whl", hash = "sha256:33f068c9382dc2e7c228eedfd8163b52baa86bb92f50d0488bf2b7da7032e484", size = 1057555, upload-time = "2025-08-12T07:00:18.573Z" }, + { url = "https://files.pythonhosted.org/packages/88/14/5aee0bf0864df9bd82bd59e7711362908e4935e3f9cdc1f57246b5d5c9b9/sentencepiece-0.2.1-cp313-cp313t-win_arm64.whl", hash = "sha256:b3616ad246f360e52c85781e47682d31abfb6554c779e42b65333d4b5f44ecc0", size = 1036042, upload-time = "2025-08-12T07:00:20.209Z" }, +] + +[[package]] +name = "setuptools" +version = "84.2.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/70/b3/c19426f783614d625699a4b247faf628ea9ab1db228674491767b417f9e1/setuptools-84.2.1.tar.gz", hash = "sha256:3ff8b3b5492a0aa66960f4419365a86b84e013070d4313e4d4a6894f5d64d6bc", size = 1230289, upload-time = "2026-10-20T19:01:37.742Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ef/55/6dc6d6bb953bdfc52519a0059592c52b6e3b8ad51cf8256dffceb55b0610/setuptools-84.2.1-py3-none-any.whl", hash = "sha256:ca140b45d5325a9478f880e351484f62fef15f336462e449ca0c03c873d589c2", size = 876263, upload-time = "2026-10-20T19:01:35.678Z" }, +] + +[[package]] +name = "sympy" +version = "1.14.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "mpmath" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/d3/803453b36afefb7c2bb238361cd4ae6125a569b4db67cd9e79846ba2d68c/sympy-1.14.0.tar.gz", hash = "sha256:d3d3fe8df1e5a0b42f0e7bdf50541697dbe7d23746e894990c030e2b05e72517", size = 7793921, upload-time = "2025-04-27T18:05:01.611Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a2/09/77d55d46fd61b4a135c444fc97158ef34a095e5681d0a6c10b75bf356191/sympy-1.14.0-py3-none-any.whl", hash = "sha256:e091cc3e99d2141a0ba2847328f5479b05d94a6635cb96148ccb3f34671bd8f5", size = 6299353, upload-time = "2025-04-27T18:04:59.103Z" }, +] + +[[package]] +name = "threadpoolctl" +version = "3.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/56/97/b4748951a683e369513691c8eea33d100298d556308dcb0ab66b132a67f0/threadpoolctl-3.8.0.tar.gz", hash = "sha256:01080674ad7ac6182429c918a79de92da789bb448acc02fc0b620b1abd6b6137", size = 39424, upload-time = "2026-11-05T11:08:51.112Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/54/1b/831f2de4840a25db1dd7b1afea433ccafe6bb10aca07e13264f2079462d0/threadpoolctl-3.8.0-py3-none-any.whl", hash = "sha256:f1b49c82704d50f13ffae019c727b0fa4f6791a58f48f06a09c45face1be66da", size = 32091, upload-time = "2026-11-05T11:08:49.773Z" }, +] + +[[package]] +name = "tokenizers" +version = "0.22.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "huggingface-hub" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/73/6f/f80cfef4a312e1fb34baf7d85c72d4411afde10978d4657f8cdd811d3ccc/tokenizers-0.22.2.tar.gz", hash = "sha256:473b83b915e547aa366d1eee11806deaf419e17be16310ac0a14077f1e28f917", size = 372115, upload-time = "2026-01-05T10:45:15.988Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/97/5dbfabf04c7e348e655e907ed27913e03db0923abb5dfdd120d7b25630e1/tokenizers-0.22.2-cp39-abi3-macosx_10_12_x86_64.whl", hash = "sha256:544dd704ae7238755d790de45ba8da072e9af3eea688f698b137915ae959281c", size = 3100275, upload-time = "2026-01-05T10:41:02.158Z" }, + { url = "https://files.pythonhosted.org/packages/2e/47/174dca0502ef88b28f1c9e06b73ce33500eedfac7a7692108aec220464e7/tokenizers-0.22.2-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:1e418a55456beedca4621dbab65a318981467a2b188e982a23e117f115ce5001", size = 2981472, upload-time = "2026-01-05T10:41:00.276Z" }, + { url = "https://files.pythonhosted.org/packages/d6/84/7990e799f1309a8b87af6b948f31edaa12a3ed22d11b352eaf4f4b2e5753/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2249487018adec45d6e3554c71d46eb39fa8ea67156c640f7513eb26f318cec7", size = 3290736, upload-time = "2026-01-05T10:40:32.165Z" }, + { url = "https://files.pythonhosted.org/packages/78/59/09d0d9ba94dcd5f4f1368d4858d24546b4bdc0231c2354aa31d6199f0399/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:25b85325d0815e86e0bac263506dd114578953b7b53d7de09a6485e4a160a7dd", size = 3168835, upload-time = "2026-01-05T10:40:38.847Z" }, + { url = "https://files.pythonhosted.org/packages/47/50/b3ebb4243e7160bda8d34b731e54dd8ab8b133e50775872e7a434e524c28/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:bfb88f22a209ff7b40a576d5324bf8286b519d7358663db21d6246fb17eea2d5", size = 3521673, upload-time = "2026-01-05T10:40:56.614Z" }, + { url = "https://files.pythonhosted.org/packages/e0/fa/89f4cb9e08df770b57adb96f8cbb7e22695a4cb6c2bd5f0c4f0ebcf33b66/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:1c774b1276f71e1ef716e5486f21e76333464f47bece56bbd554485982a9e03e", size = 3724818, upload-time = "2026-01-05T10:40:44.507Z" }, + { url = "https://files.pythonhosted.org/packages/64/04/ca2363f0bfbe3b3d36e95bf67e56a4c88c8e3362b658e616d1ac185d47f2/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:df6c4265b289083bf710dff49bc51ef252f9d5be33a45ee2bed151114a56207b", size = 3379195, upload-time = "2026-01-05T10:40:51.139Z" }, + { url = "https://files.pythonhosted.org/packages/2e/76/932be4b50ef6ccedf9d3c6639b056a967a86258c6d9200643f01269211ca/tokenizers-0.22.2-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:369cc9fc8cc10cb24143873a0d95438bb8ee257bb80c71989e3ee290e8d72c67", size = 3274982, upload-time = "2026-01-05T10:40:58.331Z" }, + { url = "https://files.pythonhosted.org/packages/1d/28/5f9f5a4cc211b69e89420980e483831bcc29dade307955cc9dc858a40f01/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:29c30b83d8dcd061078b05ae0cb94d3c710555fbb44861139f9f83dcca3dc3e4", size = 9478245, upload-time = "2026-01-05T10:41:04.053Z" }, + { url = "https://files.pythonhosted.org/packages/6c/fb/66e2da4704d6aadebf8cb39f1d6d1957df667ab24cff2326b77cda0dcb85/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_armv7l.whl", hash = "sha256:37ae80a28c1d3265bb1f22464c856bd23c02a05bb211e56d0c5301a435be6c1a", size = 9560069, upload-time = "2026-01-05T10:45:10.673Z" }, + { url = "https://files.pythonhosted.org/packages/16/04/fed398b05caa87ce9b1a1bb5166645e38196081b225059a6edaff6440fac/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_i686.whl", hash = "sha256:791135ee325f2336f498590eb2f11dc5c295232f288e75c99a36c5dbce63088a", size = 9899263, upload-time = "2026-01-05T10:45:12.559Z" }, + { url = "https://files.pythonhosted.org/packages/05/a1/d62dfe7376beaaf1394917e0f8e93ee5f67fea8fcf4107501db35996586b/tokenizers-0.22.2-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:38337540fbbddff8e999d59970f3c6f35a82de10053206a7562f1ea02d046fa5", size = 10033429, upload-time = "2026-01-05T10:45:14.333Z" }, + { url = "https://files.pythonhosted.org/packages/fd/18/a545c4ea42af3df6effd7d13d250ba77a0a86fb20393143bbb9a92e434d4/tokenizers-0.22.2-cp39-abi3-win32.whl", hash = "sha256:a6bf3f88c554a2b653af81f3204491c818ae2ac6fbc09e76ef4773351292bc92", size = 2502363, upload-time = "2026-01-05T10:45:20.593Z" }, + { url = "https://files.pythonhosted.org/packages/65/71/0670843133a43d43070abeb1949abfdef12a86d490bea9cd9e18e37c5ff7/tokenizers-0.22.2-cp39-abi3-win_amd64.whl", hash = "sha256:c9ea31edff2968b44a88f97d784c2f16dc0729b8b143ed004699ebca91f05c48", size = 2747786, upload-time = "2026-01-05T10:45:18.411Z" }, + { url = "https://files.pythonhosted.org/packages/72/f4/0de46cfa12cdcbcd464cc59fde36912af405696f687e53a091fb432f694c/tokenizers-0.22.2-cp39-abi3-win_arm64.whl", hash = "sha256:9ce725d22864a1e965217204946f830c37876eee3b2ba6fc6255e8e903d5fcbc", size = 2612133, upload-time = "2026-01-05T10:45:17.232Z" }, +] + +[[package]] +name = "torch" +version = "2.13.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cuda-bindings", marker = "sys_platform == 'linux'" }, + { name = "cuda-toolkit", extra = ["cublas", "cudart", "cufft", "cufile", "cupti", "curand", "cusolver", "cusparse", "nvjitlink", "nvrtc", "nvtx"], marker = "sys_platform == 'linux'" }, + { name = "filelock" }, + { name = "fsspec" }, + { name = "jinja2" }, + { name = "networkx" }, + { name = "nvidia-cudnn-cu13", marker = "sys_platform == 'linux'" }, + { name = "nvidia-cusparselt-cu13", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nccl-cu13", marker = "sys_platform == 'linux'" }, + { name = "nvidia-nvshmem-cu13", marker = "sys_platform == 'linux'" }, + { name = "setuptools" }, + { name = "sympy" }, + { name = "triton", marker = "sys_platform == 'linux'" }, + { name = "typing-extensions" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/0d/fa/c1c10b7aff4a9a3e8956d4f0a5f468fa6db7abc3208805719076772b4833/torch-2.13.0-cp313-cp313-macosx_14_0_arm64.whl", hash = "sha256:33449899ce5496c1b84b4853179d94fd102028ae1407314d9fb956bb79e70d09", size = 111213743, upload-time = "2026-07-08T16:03:28.579Z" }, + { url = "https://files.pythonhosted.org/packages/11/18/9ecb37b56293a0be8d80f810bf672a72fe7e02f8b475d5ef1b9bf8a0d748/torch-2.13.0-cp313-cp313-manylinux_2_28_aarch64.whl", hash = "sha256:1e09d6a722504957c694faceca843acde562786df1144ebcc5a74075ec7f6005", size = 427213008, upload-time = "2026-07-08T16:03:44.106Z" }, + { url = "https://files.pythonhosted.org/packages/d4/5a/7c50ba1b7b713d71d34669c6d13dab0a11531a3eceb0307a5162dbfec0f7/torch-2.13.0-cp313-cp313-manylinux_2_28_x86_64.whl", hash = "sha256:a3a9a21312872af8a26950b2c15680335a386a1f56ed03e780653d78b9607e9e", size = 526602329, upload-time = "2026-07-08T16:03:12.649Z" }, + { url = "https://files.pythonhosted.org/packages/91/3d/e7adcc6aaf36961cd18f56cf8ad0f3058c3a5c84ccf391762176c94581b8/torch-2.13.0-cp313-cp313-win_amd64.whl", hash = "sha256:49b58f1e2c52440abb6f17c28f0335fe6c6d01ad1a7f55b0183b81e4b34d64e6", size = 122057920, upload-time = "2026-07-08T16:03:01.808Z" }, +] + +[[package]] +name = "tqdm" +version = "4.70.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "colorama", marker = "sys_platform == 'win32'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/0d/ea/b2a5bd54b28a324dae8211928b2d730b6547500342c7e6c6dea08bd0a485/tqdm-4.70.1.tar.gz", hash = "sha256:cefd0eca11b2a37a3aee776544d4f4ae913f02688135b5556b8788dfa474afc4", size = 171846, upload-time = "2026-09-11T07:25:16.601Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a7/03/921a3d3c75785aca9ebfbfcabfbc3a1be12e2ab5265deb026d55a5a3f83e/tqdm-4.70.1-py3-none-any.whl", hash = "sha256:c293e525e6fef9c20e8728fd4612df02a0aa31bb5fe91ecd93e123b1b7bffa73", size = 80199, upload-time = "2026-09-11T07:25:14.599Z" }, +] + +[[package]] +name = "transformers" +version = "4.57.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "filelock" }, + { name = "huggingface-hub" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pyyaml" }, + { name = "regex" }, + { name = "requests" }, + { name = "safetensors" }, + { name = "tokenizers" }, + { name = "tqdm" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/d6/68/a39307bcc4116a30b2106f2e689130a48de8bd8a1e635b5e1030e46fcd9e/transformers-4.57.1.tar.gz", hash = "sha256:f06c837959196c75039809636cd964b959f6604b75b8eeec6fdfc0440b89cc55", size = 10142511, upload-time = "2025-10-14T15:39:26.18Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/71/d3/c16c3b3cf7655a67db1144da94b021c200ac1303f82428f2beef6c2e72bb/transformers-4.57.1-py3-none-any.whl", hash = "sha256:b10d05da8fa67dc41644dbbf9bc45a44cb86ae33da6f9295f5fbf5b7890bd267", size = 11990925, upload-time = "2025-10-14T15:39:23.085Z" }, +] + +[[package]] +name = "triton" +version = "3.7.1" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/00/42/c5089d4d9327fcd1e862c599cc2927f39418f84dd11a84cb2ccff9d4787a/triton-3.7.1-cp313-cp313-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:cdbfc09d9ec58bc5e68321525653220de7515c199e7a8097a97c85e62b52cd0a", size = 184694629, upload-time = "2026-06-17T20:03:53.444Z" }, + { url = "https://files.pythonhosted.org/packages/07/42/2c3ac59253ae8892b6f307875263dd23dc875cdf732d3aea40d6d41fb7cb/triton-3.7.1-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:58c0e131da05134a2a4788ccbcc0c1105cf0f54c8e98f19e34cd465396dc15eb", size = 197729241, upload-time = "2026-06-17T19:53:27.801Z" }, +] + +[[package]] +name = "typing-extensions" +version = "4.16.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/f6/cc/6253133b5bb138fc3306cebfbda2c520f545d36b5be2c7255cc528bb45d6/typing_extensions-4.16.0.tar.gz", hash = "sha256:dc983d19a509c94dba722ee6abd33940f7c05a89e243c47e907eb4db6f1a43e5", size = 113555, upload-time = "2026-07-02T08:40:05.92Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, +] + +[[package]] +name = "tzdata" +version = "2026.6" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/7a/29/6a1391d31cd00ff9e927215a224a880e1e84e826b64ba80a499e51c074d8/tzdata-2026.6.tar.gz", hash = "sha256:85d2cd9c09f81f0bb29db27759fc83af4f1e620efb814f8c5bf8b4cc4feece6d", size = 201017, upload-time = "2026-10-28T09:57:09.137Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0a/66/9a06c2227fedfd4919f0eaaa8b94377d9730882a7e4f95823c9a331ab5e1/tzdata-2026.6-py2.py3-none-any.whl", hash = "sha256:0a10eec6e13ef16b627fabed9a5f2ba61a62b1c67f327305f4e7e412a70b4aec", size = 348210, upload-time = "2026-10-28T09:57:07.276Z" }, +] + +[[package]] +name = "urllib3" +version = "2.8.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e3/05/b17359e1cefb4f909b5e40b1b90a496d987258916dbbf88e842c729f510e/urllib3-2.8.0.tar.gz", hash = "sha256:63bf2ead4c879426ebf22ef2a781eeb4aa3b4ae798a0435506f8687fd5bb9b63", size = 458972, upload-time = "2026-09-15T19:29:36.253Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/92/9d/c4e665119135114480843e7ab388fa94d8480650450e6f8e26b70d323a4c/urllib3-2.8.0-py3-none-any.whl", hash = "sha256:0cf3cae568d36aa9576b28dfb35f11328f1cb974ca7647d9475ebb86c75ac6e3", size = 135717, upload-time = "2026-09-15T19:29:34.577Z" }, +] + +[[package]] +name = "xxhash" +version = "4.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/c9/b5/3d11d3830ace56d67ea83136c24385c3b07da5a9bc62b73b0b94ac096da3/xxhash-4.1.0.tar.gz", hash = "sha256:c9b288e4c1f5dae54417bc8a05e6f6daf505783d916b4783f4dd2f2e7d5db486", size = 114122, upload-time = "2026-11-09T13:47:33.276Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/c5/09/ab91d5a9e16fddabacd83b40b6fcc28496d36b081f9f89dd9e3b22843f76/xxhash-4.1.0-cp313-cp313-android_24_arm64_v8a.whl", hash = "sha256:88e6264cd2d9b5e1c37152f6e2b4612c3581c868e866a8e5d74cbeca8d92e6a7", size = 43920, upload-time = "2026-11-09T13:46:59.199Z" }, + { url = "https://files.pythonhosted.org/packages/a3/e3/4ba5deea6114260e6be56e12cbeb6a3f092b4cf183dcf62233fca87df835/xxhash-4.1.0-cp313-cp313-android_24_x86_64.whl", hash = "sha256:a922d22687aad3367c5ccd9939447dde8fecc85e9cb19697f07f317b01485623", size = 52996, upload-time = "2026-11-09T13:46:58.901Z" }, + { url = "https://files.pythonhosted.org/packages/10/c7/18f629492c3bd16e690e99a359368bac67da38d1681ee29396adee3d0174/xxhash-4.1.0-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:2e9038ffd3d88d114d0fb4f624723b7711dbc7971933f2a5548ccc27188312d6", size = 35447, upload-time = "2026-11-09T13:46:54.544Z" }, + { url = "https://files.pythonhosted.org/packages/9f/57/5ab752c958d55596724484f7ceca9c998805627343265b027a5fb023b402/xxhash-4.1.0-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:de100c9c1d75fc1304d9fd56553b3c277129921c460c3986a20f66780db6ad7d", size = 36313, upload-time = "2026-11-09T13:46:55.909Z" }, + { url = "https://files.pythonhosted.org/packages/e0/c1/014c737fa9de9f38e4fa3537e6f0a4152ce0d567f9fc19720861f12d21a2/xxhash-4.1.0-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:c6c897ae27e1b2b75e1d633e4527b763b0aeee85ba01afeea38652a7f4aff220", size = 51019, upload-time = "2026-11-09T13:46:59.371Z" }, + { url = "https://files.pythonhosted.org/packages/17/0f/1dfee11ef6fa0a984c5ce4a1da3d778a7fcbeea436ebcad45918a69f2c68/xxhash-4.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:676844aad46b4452c7ca2c182a8f388cb8e8ca86fc9e7aaca20455b732adaa57", size = 51135, upload-time = "2026-11-09T13:47:00.487Z" }, + { url = "https://files.pythonhosted.org/packages/5a/7d/1d7779bdf72dbb5178d4237f9f8dd26cc47013738013f20a1270ca6ee4a4/xxhash-4.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:01b051e221fface8991b545aea1ef6172cbfe4a1e15f631995d6f7f695377419", size = 36569, upload-time = "2026-11-09T13:46:55.183Z" }, + { url = "https://files.pythonhosted.org/packages/79/16/1493efa04053e9c5ee6d3cfd0385b4664818a28f4f85120dcec40929f270/xxhash-4.1.0-cp313-cp313-manylinux1_i686.manylinux_2_28_i686.manylinux_2_5_i686.whl", hash = "sha256:2ded3241fc1b42f1dcbf5a7a0bb7f26200a9da83c1a4b6ee2cb33ee6df682509", size = 453217, upload-time = "2026-11-09T13:47:01.016Z" }, + { url = "https://files.pythonhosted.org/packages/44/0c/e884d89f122a4c8df7dce900341c03b98db9c3d0bba50f05e45c55fc49ae/xxhash-4.1.0-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:973643f3fc481553985613d40f86d85e7c08b2de9203be09dd25c0f425c3bd54", size = 281306, upload-time = "2026-11-09T13:47:00.255Z" }, + { url = "https://files.pythonhosted.org/packages/42/14/29dacd0f6062faf65a1f83bcb25adbbc25f0bb5dafe320f4c8e2f4438e7b/xxhash-4.1.0-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:6e68d4a052996fa706ec8bfec6ed6456dfbbc5fe88ed083379d19beb9740f4dc", size = 304044, upload-time = "2026-11-09T13:46:55.722Z" }, + { url = "https://files.pythonhosted.org/packages/b9/0c/47a1670d914d746280564d83ea34e5baff82244a7b8f502902e45eeb3d4b/xxhash-4.1.0-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:47fe38cd4e546d48af7167440cc6df5da7a0cac8d53e307763d57535420417b4", size = 278493, upload-time = "2026-11-09T13:46:57.28Z" }, + { url = "https://files.pythonhosted.org/packages/1c/c9/5baa03d11791564093234e2ff0f47d3e1bd52bf7290ca13e795ca21d55ee/xxhash-4.1.0-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:04ed5c0d9a98bf2be9a905d8a44082732d97bec24d1d0246ac039033d5501420", size = 516917, upload-time = "2026-11-09T13:47:00.815Z" }, + { url = "https://files.pythonhosted.org/packages/b0/25/66b03795f349deca7b8641dd9b000e993fa7ad7ae58f75f3f2ef3d696cf7/xxhash-4.1.0-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:9ec781ad63129c8559d035cf0b876a3843c8ebb6e423c3e8742b3e9a92124b39", size = 478360, upload-time = "2026-11-09T13:47:02.425Z" }, + { url = "https://files.pythonhosted.org/packages/e4/94/ce39f1867a1d9571ce06bf0c0542af735fe5b42f97cd3aac447e6a4f99c4/xxhash-4.1.0-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:cce0371a613104b7b7f1bb0b49149d4ac776f63521887c216eed50c77d6846d4", size = 342264, upload-time = "2026-11-09T13:46:57.629Z" }, + { url = "https://files.pythonhosted.org/packages/e8/bb/1f55e268e06246cb37a038aff6f19743cbe4304911dc3ddad4464d3d1f76/xxhash-4.1.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:07be9de373a28bda9f058b31c0fcb519af48500255d13ea11b8deb2924a7783f", size = 277852, upload-time = "2026-11-09T13:47:02.639Z" }, + { url = "https://files.pythonhosted.org/packages/0c/25/a4ea7c6d1a08c848a34d2842fd4bb01f72efbf2be2652e5d1fd491a2d7bf/xxhash-4.1.0-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:2ea39f8217eaacf13c70a9d5e85a2dfed98f2cd7fda87c6f4759d5d317ba9ea2", size = 304898, upload-time = "2026-11-09T13:47:01.927Z" }, + { url = "https://files.pythonhosted.org/packages/d6/36/98489a65491c9ce938ad05b5ba9339017f7c9f2b7ab55253a45350c9e5b6/xxhash-4.1.0-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:48c2dbc094ccd950e570f095c235276988dcf50e1d2bc983d40b0035902486f4", size = 448603, upload-time = "2026-11-09T13:46:58.589Z" }, + { url = "https://files.pythonhosted.org/packages/36/4c/82bfbc10434b4540124ca5220a8f027112c7acdfd437407ea597cf95419f/xxhash-4.1.0-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:a624fcf09597f21dff4948a5a3df1848faf3c35d463dad4fd5482baeae714970", size = 276949, upload-time = "2026-11-09T13:46:58.637Z" }, + { url = "https://files.pythonhosted.org/packages/fe/4a/5203f70749649f685dc883cc2e59fcc5e7e8fedfecdceaf6e3ed9092b67c/xxhash-4.1.0-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:8ef2ff26e5030ad280337e7a6758d77da6c59ded18519ab436bf330e8c743cee", size = 333481, upload-time = "2026-11-09T13:47:02.341Z" }, + { url = "https://files.pythonhosted.org/packages/0d/95/451eb3aac847f154a6fcf6f4bc2ba821fe22c5de55916f8d3234236665fe/xxhash-4.1.0-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:4bd0951099697c00e2e8f67e76777cd73e5790d44d6dab0faa7ab9b685fe75c9", size = 484198, upload-time = "2026-11-09T13:47:04.513Z" }, + { url = "https://files.pythonhosted.org/packages/e6/c9/c0046ede67fb01b4e4d80c51dfb68b1a21c744d3e4308b94ebfffd6e58fa/xxhash-4.1.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:4afe8fcccfb678845b6f90bb3174d2f4254c9327f4bd8fe81a0e91c117940b21", size = 460302, upload-time = "2026-11-09T13:46:59.113Z" }, + { url = "https://files.pythonhosted.org/packages/03/c1/c5b8e551938a6163dc81005d500c040a596ec52338d5e4898ab7b84c61f1/xxhash-4.1.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:ffec5e9139b972051065cb58a3e74914d8a7f70c3bc9c23e03909df22c88dc30", size = 20825, upload-time = "2026-11-09T13:47:04.033Z" }, + { url = "https://files.pythonhosted.org/packages/ac/56/4aedbaa15d0a5736606bd2b8a25aa8642bbdab44f5ce3baf88b90cc46295/xxhash-4.1.0-cp313-cp313-win32.whl", hash = "sha256:5073ad9d46bee44ecf6d66b01cf989e5f37fea18d26735cd5952125ab037524c", size = 44875, upload-time = "2026-11-09T13:47:03.454Z" }, + { url = "https://files.pythonhosted.org/packages/d9/ef/e370e1cf8bc86b5f92b9a11debf529de62ebe9556d9767b2305c818c36da/xxhash-4.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:3cb7f59ea87872554c5484afc43a7c1e6c5295f4b53e76a4bfffcf72b4a67877", size = 47517, upload-time = "2026-11-09T13:47:00.757Z" }, + { url = "https://files.pythonhosted.org/packages/f1/55/55e33a06f083a3730d6adc296ca3c2df44019c4779d488e32d9255fa7417/xxhash-4.1.0-cp313-cp313-win_arm64.whl", hash = "sha256:a329dcca18a3bf27b792e79f42f04ff746da2cbc04db9f582fc985412d9dbf08", size = 33492, upload-time = "2026-11-09T13:47:00.332Z" }, + { url = "https://files.pythonhosted.org/packages/48/1a/1f5f87bf0c9b61088a1d2dfd4b30f577b21c96c43f8eb3eab4b0d670fe4d/xxhash-4.1.0-graalpy313-graalpy253_313_native-macosx_11_0_arm64.whl", hash = "sha256:d29b8c866dd9015eb343dd9f8689e7a51dfb33464145f57427194043ab58a33f", size = 33860, upload-time = "2026-11-09T13:47:28.079Z" }, + { url = "https://files.pythonhosted.org/packages/a6/2b/7535fde10a36d7106efcad4d0ca9c62b1be77c8b66851ae7024ea64a55ff/xxhash-4.1.0-graalpy313-graalpy253_313_native-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:3f06764754b12f71d88eec1041351942735998e107f7446b0be9c2ea02a12e5c", size = 38533, upload-time = "2026-11-09T13:47:32.186Z" }, + { url = "https://files.pythonhosted.org/packages/18/fb/8691c994eba2b3c05f165029a53f969f6496ebd209adf7a10d8c9f9acd0f/xxhash-4.1.0-graalpy313-graalpy253_313_native-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:28de1a2cec250771ad8a7709053a26fabd30f59b97b98013bfeeb4ba5e228196", size = 44932, upload-time = "2026-11-09T13:47:25.14Z" }, + { url = "https://files.pythonhosted.org/packages/da/e5/83fbb0bf6f93b021adfd31d41b03dbdf057b3fd992860611d2baf656c575/xxhash-4.1.0-graalpy313-graalpy253_313_native-win_amd64.whl", hash = "sha256:c9c61723c348a66096968fe754d8e4edc528817b9464da06808342eae5acf076", size = 47837, upload-time = "2026-11-09T13:49:03.759Z" }, +] + +[[package]] +name = "yarl" +version = "1.25.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "idna" }, + { name = "multidict" }, + { name = "propcache" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/75/16/e8be8e2fb175bbf41a0680381a319f1199fae256588241a2ac8677eafb49/yarl-1.25.1.tar.gz", hash = "sha256:03dd38de09bc213e9a8b29761eec33ee1d5318dac0e49d8af36e4d27830e23a7", size = 246245, upload-time = "2026-09-15T19:35:02.264Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7b/ed/2f3129bbcc9a5c8ba12cc2b29d8060a3bab9c8043c456cfd4b5ca3188890/yarl-1.25.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:25868beca8b6765f8f7d0e11fe6dd7c66dd4b0793b9500286d20cc92352126a5", size = 143623, upload-time = "2026-09-15T19:31:37.966Z" }, + { url = "https://files.pythonhosted.org/packages/17/e1/f1bc3390fdca352826676b531d0712736f156919090206700421d46b2c37/yarl-1.25.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:10b2fd95332f0d716d5eee3c9fb2ce8eada19082de7fee83d32e37992fd75c26", size = 104011, upload-time = "2026-09-15T19:31:40.25Z" }, + { url = "https://files.pythonhosted.org/packages/a8/aa/50acc5c3e5da04172ae3c281c75405af4d2ca911e16120ab0563f4dffb66/yarl-1.25.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0f12afda4eea8c8994a76d4df1875c765194f5fbe8a9d197929ea303caee29ec", size = 103677, upload-time = "2026-09-15T19:31:42.46Z" }, + { url = "https://files.pythonhosted.org/packages/30/d2/7d1e0ab9f8390e1fbcede5a6dbf70d23c96ad09b8c5567f3a514d1ddb0e2/yarl-1.25.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:14b79a30a93a3ce2e8832603fd0ab780ada281b0ba5110b519a634f2d7d7d1fc", size = 115392, upload-time = "2026-09-15T19:31:44.371Z" }, + { url = "https://files.pythonhosted.org/packages/71/e1/5ba1e3a2a22139213655e760919038e8ed7e2d4a99826d0bbddb3beb96e5/yarl-1.25.1-cp313-cp313-manylinux2014_armv7l.manylinux_2_17_armv7l.manylinux_2_31_armv7l.whl", hash = "sha256:4bd6340d20ae2c7ca719b87b426e808e90743b676d05d4c26c4fb5ca71f41184", size = 107493, upload-time = "2026-09-15T19:31:46.273Z" }, + { url = "https://files.pythonhosted.org/packages/f5/53/780653d5e0f73831f467cf13548912e5eec97f21dc49fc8daf21da027df4/yarl-1.25.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:126a2533570c554719ca40a1288fdee1700b6bc82e7131aa69fa85252d92e651", size = 122537, upload-time = "2026-09-15T19:31:48.654Z" }, + { url = "https://files.pythonhosted.org/packages/03/92/d54fa70236c6036271c9c9c09fd978df5cbe3ef49ef6c46e9b833476d215/yarl-1.25.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a3faadac7d812ddac258feb57b9846b60c1b437c4f4b9ad42595c6f6fe4390df", size = 126170, upload-time = "2026-09-15T19:31:50.872Z" }, + { url = "https://files.pythonhosted.org/packages/0e/b7/a82a49bf88340b837ef6972b508a1604ae377b9e6904b46b10cf5f1cf925/yarl-1.25.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:be80550d9bfe83d9b62398a37081a90434e6df2d978ec345c3d2820de6beddab", size = 117012, upload-time = "2026-09-15T19:31:53.189Z" }, + { url = "https://files.pythonhosted.org/packages/ef/78/5d684b411e3f3602464ee9b538db48205038f8605872985f61efb809ced0/yarl-1.25.1-cp313-cp313-manylinux_2_31_riscv64.manylinux_2_39_riscv64.whl", hash = "sha256:e07595c7d6f4db270ceede356a1bd1c07a34f1c26f958d1ed0cd7b48e0d2bba3", size = 114950, upload-time = "2026-09-15T19:31:55.694Z" }, + { url = "https://files.pythonhosted.org/packages/2f/11/51d82b852c64f7fad0fc7a7ff3031517204887e874c722bbca839c0b23ac/yarl-1.25.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:eb96ed1ae6c7d072d60840c0434aef07a2df611812810807fbc54263a6053e9a", size = 115428, upload-time = "2026-09-15T19:31:57.966Z" }, + { url = "https://files.pythonhosted.org/packages/e4/49/9d1978049bf646b9ea918313926453c6901b71c92f097467777d47d36a88/yarl-1.25.1-cp313-cp313-musllinux_1_2_armv7l.whl", hash = "sha256:3feb99222553a8cbedfa52c2f59dd84c3f50d5b582c728d522caf8d72769a54b", size = 108428, upload-time = "2026-09-15T19:32:00.048Z" }, + { url = "https://files.pythonhosted.org/packages/43/35/7b8f1ebb45d7ec3dda7d1909bf44f458de41ef91e2937f107733582a5166/yarl-1.25.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:a2ed0ba415ccdf08f14bf544cb78346d0f76086707ffee24921a2c84dbf1305a", size = 121961, upload-time = "2026-09-15T19:32:02.436Z" }, + { url = "https://files.pythonhosted.org/packages/63/d6/d8b689ab7ca26edeb85f6ff28812aac7a25376eefc1780e303a7bfbaceff/yarl-1.25.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:2b49375d22299b0a834c2bca72f39aaecc270d96fb24c30424899676f487b22a", size = 114961, upload-time = "2026-09-15T19:32:04.456Z" }, + { url = "https://files.pythonhosted.org/packages/cf/d5/1a1798ea4dc6b7ee3260010a27907ebc697c95dae99817d817ed446d24aa/yarl-1.25.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:ef74070ac553c59eb4f04258722066d6c6135b7baa03b2e9f2da65c096e96d98", size = 120036, upload-time = "2026-09-15T19:32:06.5Z" }, + { url = "https://files.pythonhosted.org/packages/91/8d/b1b35ed7903da6669b1d367cb2c09436acd4ff508029b4f39a0c0c2058fc/yarl-1.25.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:0a66db89ea473abeac4b70523cafd94db3772380e565f9d28af7a179b7af71fa", size = 117276, upload-time = "2026-09-15T19:32:09.401Z" }, + { url = "https://files.pythonhosted.org/packages/3a/8f/4db01cef62caff0d7a4593ed694fb8a41a27a11158cab80d290221f13e57/yarl-1.25.1-cp313-cp313-win_amd64.whl", hash = "sha256:1f51020b2eb8a003c84925638ec63c21a750a4bddd3a22ec8eac6a742dadf1b9", size = 101945, upload-time = "2026-09-15T19:32:11.545Z" }, + { url = "https://files.pythonhosted.org/packages/c0/5e/3ce00497c5c0babb74d4130c10c3828ccd215b4819d12020c42429f991ac/yarl-1.25.1-cp313-cp313-win_arm64.whl", hash = "sha256:b10dd0557ba422715b5206b3743192135a6022acca8baec51aa127d0a75db8fe", size = 97270, upload-time = "2026-09-15T19:32:14.127Z" }, + { url = "https://files.pythonhosted.org/packages/54/22/318c7980066769c6bcd9221ed2248294f5698811da099013098c670565ed/yarl-1.25.1-py3-none-any.whl", hash = "sha256:681c758b0490f9e96b78e5fa8e8dc6e648e9185bb6eaebe73183c33ea0c445f3", size = 63617, upload-time = "2026-09-15T19:34:59.616Z" }, +]