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.
This commit is contained in:
gloamxun committed 2026-11-12 23:32:33 +08:00
commit e0feabec8f
596 files changed
+87356

No files matched your search

@@ -0,0 +1 @@
null
@@ -0,0 +1,3 @@
# -*- coding: utf-8 -*-
# @Author: pingzhili
# @Time: 2024/1/17
@@ -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
@@ -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()
+204
View File
@@ -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
+78
View File
@@ -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)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,8 @@
from .configuration_mistral import MistralConfig, MISTRAL_PRETRAINED_CONFIG_ARCHIVE_MAP
from .modeling_mistral import (
MistralModel,
MistralForCausalLM,
MistralForSequenceClassification,
MistralPreTrainedModel,
MistralForCausalLMWithHeadTuning
)
@@ -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,
)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+488
View File
@@ -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
+213
View File
@@ -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)
+218
View File
@@ -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()
+939
View File
@@ -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 <unk>
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()
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
@@ -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
Loaded 100 of 596 files, more files were not shown because too many files have changed in this diff. Show more