code stringlengths 17 6.64M |
|---|
class LossNN(Module, abc.ABC):
'Loss-oriented neural network used as an algorithm based on designing loss.\n '
def __init__(self):
super(LossNN, self).__init__()
def forward(self, x):
return x
@abc.abstractmethod
def criterion(self, X, y):
pass
@abc.abstractmetho... |
def timing(func):
@wraps(func)
def wrapper(*args, **kwargs):
t = time.time()
result = func(*args, **kwargs)
print(((("'" + func.__name__) + "'") + ' took {} s'.format((time.time() - t))))
return result
return wrapper
|
class lazy_property():
def __init__(self, func):
self.func = func
def __get__(self, instance, cls):
val = self.func(instance)
setattr(instance, self.func.__name__, val)
return val
|
def softmax(x):
e_x = np.exp((x - np.max(x, axis=(- 1), keepdims=True)))
return (e_x / np.sum(e_x, axis=(- 1), keepdims=True))
|
def cross_entropy_loss(y_pred, y_label):
if (y_pred.size() == y_label.size()):
return torch.mean((- torch.sum((torch.log_softmax(y_pred, dim=(- 1)) * y_label), dim=(- 1))))
else:
return torch.nn.CrossEntropyLoss()(y_pred, y_label.long())
|
def grad(y, x, create_graph=True, keepdim=False):
'\n y: [N, Ny] or [Ny]\n x: [N, Nx] or [Nx]\n Return dy/dx ([N, Ny, Nx] or [Ny, Nx]).\n '
N = (y.size(0) if (len(y.size()) == 2) else 1)
Ny = y.size((- 1))
Nx = x.size((- 1))
z = torch.ones_like(y[(..., 0)])
dy = []
for i in ran... |
def input_fn(features, labels, shuffle=True, batch_size=64, repeat=False, seed=None):
'\n A function for converting data into training/evaluation tf.Dataset\n\n inputs:\n features: np.ndarray containing features.\n labels : np.ndarray containing labels for all examples.\n shuffle : bool... |
def create_model(model_type='state_estimator', model_opt='best_noise_opt'):
"\n inputs:\n model_type: str specifying either 'state_estimator' or \n 'quality_control' type machine learning model.\n model_opt: str specifying dataset the model parameters were optimized \n on. V... |
def get_num_min_class(labels):
'\n Get the number of the minimum represented class in label vector.\n Used for resampling data.\n\n input:\n labels: np.ndarray of labels\n \n outputs:\n num_samples: int number of samples for minimum class\n '
argmax_labels = np.argmax(labels, a... |
def resample_data(features, state_labels, labels=None, seed=None):
'\n Resample data to be evenly distributed across classes in labels by cutting\n number of examples for each class to be equal to the number of examples\n in the least represented class. (classes assumed to be last axis of\n labels). S... |
def noise_mag_to_class(state_labels, noise_mags, low_thresholds=None, high_thresholds=None):
'\n Function to convert noise magnitudes to noise classes.\n Noise class thresholds are defined here. Thresholds for states\n order is: no dot, left dot, central dot, right dot, double dot\n Default low thresh... |
def get_data(f, train_test_split=0.9, dat_key='sensor', label_key='state', resample=True, seed=None, low_thresholds=None, high_thresholds=None):
"\n Reads in the subregion data and converts it to a format useful for training\n Note that the data is shuffled after reading in.\n\n inputs:\n f: one o... |
def gradient(x):
'\n Take gradient of an ndarray in specified direction. Thin wrapper around\n np.gradient(). Also note that x -> axis=1 and y-> axis=0\n \n input:\n x: An numpy ndarray to take the gradient of \n output:\n numpy ndarray containing gradient ... |
def apply_threshold(x, threshold_val=10, threshold_to=0):
'\n Thresholds an numpy ndarray to remove\n Args:\n x = numpy array with data to be filtered\n threshold_val = percentile below which to set values to zero\n '
x[(x < np.abs(np.percentile(x.flatten(), threshold_val)))] = threshol... |
def apply_clipping(x, clip_val=3, clip_to='clip_val'):
'\n Clip input symmetrically at clip_val number of std devs.\n Do not zscore norm x, but apply thresholds using normed x\n '
x_clipped = np.copy(x)
mean = np.mean(x)
std = np.std(x)
norm_x = ((x - mean) / std)
if (clip_to.lower() ... |
def autoflip_skew(data):
'\n Autoflip a numpy ndarray based on the skew of the values \n (effective for gradient data).\n '
skew_sign = np.sign(scipy_skew(np.ravel(data)))
return (data * skew_sign)
|
def zscore_norm(x):
'\n Takes a numpy ndarray and returns a z-score normalized version\n '
return ((x - x.mean()) / x.std())
|
class Preprocessor():
def __init__(self, autoflip=False, denoising=[], clip_val=None, thresh_val=None):
"\n Class for doing preprocessing of data.\n\n inputs:\n autoflip: bool specifying whether to autoflip data.\n denoising: list of str specifying denoising to apply t... |
def cnn_model_fn(features, labels, mode):
'Model function for CNN.'
input_layer = tf.cast(tf.reshape(features['x'], [(- 1), qf.SUB_SIZE, qf.SUB_SIZE, 1]), tf.float32)
conv1 = tf.layers.conv2d(inputs=input_layer, filters=16, kernel_size=[5, 5], padding='same', activation=tf.nn.relu)
pool1 = tf.layers.m... |
class CosEMA(nn.Module):
def __init__(self, total_steps, base_decay=0.996):
'Exponential moving average used in BYOL.\n\n :param base_decay: the base ema decay used to modulate\n :returns: EMA module\n :rtype: nn.Module\n\n '
super(CosEMA, self).__init__()
self... |
class BYOL(nn.Module):
'Simple BYOL implementation.'
def __init__(self, base_network_output_size, projection_output_size, classifier_output_size, total_training_steps, base_decay=0.996):
'BYOL model.\n\n :param base_network_output_size: output-size of resnet50 embedding\n :param project... |
def build_lr_schedule(optimizer, last_epoch=(- 1)):
' adds a lr scheduler to the optimizer.\n\n :param optimizer: nn.Optimizer\n :returns: scheduler\n :rtype: optim.lr_scheduler\n\n '
if (args.lr_update_schedule == 'fixed'):
sched = optim.lr_scheduler.LambdaLR(optimizer, (lambda epoch: 1.0... |
def build_optimizer(model, last_epoch=(- 1)):
' helper to build the optimizer and wrap model\n\n :param model: the model to wrap\n :returns: optimizer wrapping model provided\n :rtype: nn.Optim\n\n '
optim_map = {'rmsprop': optim.RMSprop, 'adam': optim.Adam, 'adadelta': optim.Adadelta, 'sgd': opti... |
def build_train_and_test_transforms():
'Returns torchvision OR nvidia-dali transforms.\n\n :returns: train_transforms, test_transforms\n :rtype: list, list\n\n '
resize_shape = (args.image_size_override, args.image_size_override)
if ('dali' in args.task):
import nvidia.dali.ops as ops
... |
def build_loader_model_grapher(args):
'builds a model, a dataloader and a grapher\n\n :param args: argparse\n :param transform: the dataloader transform\n :returns: a dataloader, a grapher and a model\n :rtype: list\n\n '
(train_transform, test_transform) = build_train_and_test_transforms()
... |
def lazy_generate_modules(model, loader):
' A helper to build the modules that are lazily compiled\n\n :param model: the nn.Module\n :param loader: the dataloader\n :returns: None\n :rtype: None\n\n '
model.eval()
for (augmentation1, augmentation2, labels) in loader:
with torch.no_g... |
def register_plots(loss, grapher, epoch, prefix='train'):
" Registers line plots with grapher.\n\n :param loss: the dict containing '*_mean' or '*_scalar' values\n :param grapher: the grapher object\n :param epoch: the current epoch\n :param prefix: prefix to append to the plot\n :returns: None\n ... |
def register_images(output_map, grapher, prefix='train'):
" Registers image with grapher. Overwrites the existing image due to space.\n\n :param output_map: the dict containing '*_img' of '*_imgs' as keys\n :param grapher: the grapher object\n :param prefix: prefix to attach to images\n :returns: None... |
def _extract_sum_scalars(v1, v2):
'Simple helper to sum values in a struct using dm_tree.'
def chk(c):
'Helper to check if we have a primitive or tensor'
return (not isinstance(c, (int, float, np.int32, np.int64, np.float32, np.float64)))
v1_detached = (v1.detach() if chk(v1) else v1)
... |
def execute_graph(epoch, model, loader, grapher, optimizer=None, prefix='test'):
" execute the graph; wphen 'train' is in the name the model runs the optimizer\n\n :param epoch: the current epoch number\n :param model: the torch model\n :param loader: the train or **TEST** loader\n :param grapher: the... |
def train(epoch, model, optimizer, train_loader, grapher, prefix='train'):
' Helper to run execute-graph for the train dataset\n\n :param epoch: the current epoch\n :param model: the model\n :param test_loader: the train data-loader\n :param grapher: the grapher object\n :param prefix: the default ... |
def test(epoch, model, test_loader, grapher, prefix='test'):
' Helper to run execute-graph for the test dataset\n\n :param epoch: the current epoch\n :param model: the model\n :param test_loader: the test data-loaderpp\n :param grapher: the grapher object\n :param prefix: the default prefix; useful... |
def init_multiprocessing_and_cuda(rank, args_from_spawn):
'Sets the appropriate flags for multi-process jobs.'
if args_from_spawn.multi_gpu_distributed:
os.environ['CUDA_VISIBLE_DEVICES'] = str(rank)
args_from_spawn.distributed_rank = rank
args_from_spawn.cuda = ((not args_from_spawn.no_cu... |
def run(rank, args):
' Main entry-point into the program\n\n :param rank: current device rank\n :param args: argparse\n :returns: None\n :rtype: None\n\n '
init_multiprocessing_and_cuda(rank, args)
(loader, model, grapher) = build_loader_model_grapher(args)
print(pprint.PrettyPrinter(in... |
def regression_loss(x, y):
'Pulled directly from BYOL'
(norm_x, norm_y) = (x.norm(), y.norm())
return (((- 2) * torch.sum((x * y), dim=(- 1))) / (norm_x * norm_y))
|
def loss_function(online_prediction1, online_prediction2, target_projection1, target_projection2):
'BYOL loss.\n\n :param online_prediction1: the output of the final MLP of the online model for augmentation 1\n :param online_prediction2: the output of the final MLP of the online model for augmentation 2\n ... |
class LARS(Optimizer):
"Implements 'LARS (Layer-wise Adaptive Rate Scaling)'__ as Optimizer a\n :class:`~torch.optim.Optimizer` wrapper.\n\n __ : https://arxiv.org/abs/1708.03888\n\n Wraps an arbitrary optimizer like :class:`torch.optim.SGD` to use LARS. If\n you want to the same performance obtained ... |
class Scheduler(object):
'Simple container for warmup and normal scheduler.'
def __init__(self, normal_schededuler, warmup_scheduler=None):
self.warmup = warmup_scheduler
self.sched = normal_schededuler
def get_last_lr(self):
' Return last computed learning rate by current schedu... |
class LinearWarmup(LambdaLR):
' Linear warmup and then constant.\n Linearly increases learning rate schedule from 0 to 1 over `warmup_steps` training steps.\n Keeps learning rate schedule equal to 1. after warmup_steps.\n\n From https://bit.ly/39o2W1f\n '
def __init__(self, optimizer,... |
def load_model(model, args):
if args.custom_model:
from scaled_rope.modeling_llama_yarn import LlamaForCausalLM
from scaled_rope.configuration_llama import LlamaConfig
model_cls = LlamaForCausalLM
config_cls = LlamaConfig
elif args.custom_model_together:
from scaled_rop... |
def add_args(parser: ArgumentParser):
parser.add_argument('--dynamic-linear', action='store_true')
parser.add_argument('--dynamic-ntk', type=float)
parser.add_argument('--dynamic-part-ntk', action='store_true')
parser.add_argument('--dynamic-yarn', action='store_true')
parser.add_argument('--ntk',... |
def apply_patches(model, args):
if ((not args.custom_model) and (not args.custom_model_together) and (not args.custom_model_mistral)):
if ('GPTNeoXForCausalLM' in model.config.architectures):
assert (args.gpt_neox_max_length is not None)
patch_gptneox_for_longer_sequences(model, ar... |
def load_model_and_apply_patches(model, args):
return apply_patches(load_model(model, args), args)
|
def generate_prompt(n_garbage):
'Generates a text file and inserts an execute line at a random position.'
n_garbage_prefix = random.randint(0, n_garbage)
n_garbage_suffix = (n_garbage - n_garbage_prefix)
task_description = 'There is an important info hidden inside a lot of irrelevant text. Find it and... |
def test_model(pipe, prompt_text, pass_key):
response = pipe(prompt_text, num_return_sequences=1, max_new_tokens=10)[0]['generated_text'][len(prompt_text):]
assert (f'The pass key is {pass_key}' in prompt_text)
try:
pass_key = int(re.search('\\d+', response).group())
except:
pass_key =... |
def main(args):
models = [x[0] for x in args.model]
tokenizer = AutoTokenizer.from_pretrained(models[0], model_max_length=sys.maxsize, padding_side='right', trust_remote_code=True)
if args.fixed_length:
lengths = [args.fixed_length]
tokens = [len(tokenizer.encode(generate_prompt(args.fixed... |
def order(i):
if (((i % 10) == 1) and ((i % 10) != 11)):
return (str(i) + 'st')
elif (((i % 10) == 2) and ((i % 10) != 12)):
return (str(i) + 'nd')
elif (((i % 19) == 3) and ((i % 10) != 13)):
return (str(i) + 'rd')
else:
return (str(i) + 'th')
|
def generate_prompt(docs, num_keys=1):
task_description = 'There is an important info hidden inside a lot of irrelevant text. Find it and memorize them. I will quiz you about the important information there.'
pass_keys = [random.randint(1, 50000) for _ in range(num_keys)]
start_pos = sorted([random.randin... |
def test_model(pipe, prompt_text):
response = pipe(prompt_text, num_return_sequences=1, max_new_tokens=10)[0]['generated_text'][len(prompt_text):]
try:
pass_key = int(re.search('\\d+', response).group())
except:
pass_key = response[:20]
return (pass_key, response)
|
def construct_junk(data, length, tokenizer):
token_count = 0
docs = []
length = (length or 8192)
while (token_count < length):
sample = random.choice(data)['text']
toks = tokenizer(sample, return_offsets_mapping=True)
offsets = [(i, j) for (i, j) in toks['offset_mapping'] if (i... |
def main(args):
models = [x[0] for x in args.model]
tokenizer = AutoTokenizer.from_pretrained(models[0], model_max_length=sys.maxsize, padding_side='right', trust_remote_code=True)
data = load_dataset(args.dataset)[args.split]
junks = construct_junk(data, args.fixed_length, tokenizer)
if args.rest... |
def main(args):
tokenizer = AutoTokenizer.from_pretrained(args.model, model_max_length=sys.maxsize, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
model = load_model_and_apply_patches(args.model, args)
pipe = pipeline('text-generation', model=model, tokenizer=tokenizer, pad_token_id... |
def get_prompt(sample):
options = sample['options']
instruction = ZERO_SCROLLS_QUALITY_PROMPT.format(story=sample['article'], question=sample['question'], a=options[0], b=options[1], c=options[2], d=options[3])
return f'''{instruction}
Answer: ('''
|
def main(args):
models = [x[0] for x in args.model]
tokenizer = AutoTokenizer.from_pretrained(models[0], model_max_length=sys.maxsize, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.pad_token_id = tokenizer.eos_token_id
dataset = load_dataset('emozilla/quality', split=... |
def find_all_linear_names(model):
lora_module_names = set()
for (name, module) in model.named_modules():
if isinstance(module, torch.nn.Linear):
names = name.split('.')
lora_module_names.add((names[0] if (len(names) == 1) else names[(- 1)]))
if ('lm_head' in lora_module_nam... |
def main(args):
if args.output_dir:
os.makedirs(args.output_dir, exist_ok=True)
if args.wandb:
import wandb
wandb.login()
set_seed(args.seed)
timeout = InitProcessGroupKwargs(timeout=timedelta(seconds=1000000))
accelerator = Accelerator(gradient_accumulation_steps=args.grad... |
def main(args):
obj = json.load(open(args.file, 'r', encoding='utf-8'))
results = [result['acc'] for result in obj['results'].values()]
print(numpy.average(results))
|
def main(args):
data = pd.read_csv(args.csv)
(fig, ax) = plt.subplots(figsize=(10, 5))
x_data = [float(x) for x in data.columns[1:]]
for row in data.values:
label = row[0].replace('NousResearch/', '')
ax.plot(x_data, [float(x) for x in row[1:]], label=label)
ax.set_xlabel('Context ... |
class LlamaConfig(PretrainedConfig):
'\n This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA\n model according to the specified arguments, defining the model architecture. Instantiating a configuration with the\n defaults will yield a similar... |
class MistralConfig(PretrainedConfig):
'\n This is the configuration class to store the configuration of a [`MistralModel`]. It is used to instantiate an\n Mistral model according to the specified arguments, defining the model architecture. Instantiating a configuration\n with the defaults will yield a s... |
def patch_llama_for_dynamic_scaled_rotary_embeddings(model, ntk):
from .LlamaDynamicScaledRotaryEmbedding import LlamaDynamicScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaDynamicScaledRotaryEmbedding(each.self_attn.head_dim, device=each.self_attn.rotary_emb.inv... |
def patch_llama_for_dynamic_part_ntk_rotary_embeddings(model, finetuned):
from .LlamaDynamicPartNTKScaledRotaryEmbedding import LlamaDynamicPartNTKScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaDynamicPartNTKScaledRotaryEmbedding(each.self_attn.head_dim, finetun... |
def patch_llama_for_dynamic_yarn_rotary_embeddings(model, original_max_position_embeddings, finetuned):
from .LlamaDynamicYaRNScaledRotaryEmbedding import LlamaDynamicYaRNScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaDynamicYaRNScaledRotaryEmbedding(each.self_a... |
def patch_falcon_for_dynamic_part_ntk_rotary_embeddings(model):
from .FalconDynamicPartNTKScaledRotaryEmbedding import FalconDynamicPartNTKScaledRotaryEmbedding
for each in model.transformer.h:
each.self_attention.maybe_rotary = FalconDynamicPartNTKScaledRotaryEmbedding(each.self_attention.head_dim)
|
def patch_llama_for_ntk_scaled_rotary_embeddings(model, alpha):
from .LlamaNTKScaledRotaryEmbedding import LlamaNTKScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaNTKScaledRotaryEmbedding(each.self_attn.head_dim, alpha=alpha, device=each.self_attn.rotary_emb.inv_... |
def patch_llama_for_linear_scaled_rotary_embeddings(model, scale):
from .LlamaLinearScaledRotaryEmbedding import LlamaLinearScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaLinearScaledRotaryEmbedding(each.self_attn.head_dim, scale=scale, device=each.self_attn.rot... |
def patch_llama_for_part_ntk_scaled_rotary_embeddings(model, scale):
from .LlamaPartNTKScaledRotaryEmbedding import LlamaPartNTKScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaPartNTKScaledRotaryEmbedding(each.self_attn.head_dim, scale=scale, device=each.self_att... |
def patch_llama_for_yarn_scaled_rotary_embeddings(model, scale, original_max_position_embeddings):
from .LlamaYaRNScaledRotaryEmbedding import LlamaYaRNScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaYaRNScaledRotaryEmbedding(each.self_attn.head_dim, scale=scale,... |
def patch_gptneox_for_scaled_rotary_embeddings(model):
from .GPTNeoXDynamicScaledRotaryEmbedding import GPTNeoXDynamicScaledRotaryEmbedding
for each in model.gpt_neox.layers:
each.attention.rotary_emb = GPTNeoXDynamicScaledRotaryEmbedding(each.attention.rotary_ndims, model.config.max_position_embeddin... |
def patch_gptneox_for_ntk_scaled_rotary_embeddings(model, alpha):
from .GPTNeoXNTKScaledRotaryEmbedding import GPTNeoXNTKScaledRotaryEmbedding
for each in model.gpt_neox.layers:
each.attention.rotary_emb = GPTNeoXNTKScaledRotaryEmbedding(each.attention.rotary_ndims, model.config.max_position_embedding... |
def patch_gptneox_for_longer_sequences(model, max_positions):
for each in model.gpt_neox.layers:
each.attention.bias = torch.tril(torch.ones((max_positions, max_positions), dtype=each.attention.bias.dtype, device=each.attention.bias.device)).view(1, 1, max_positions, max_positions)
|
def patch_llama_for_rerope(model, training_length, window):
from .LlamaReRoPE import forward_with_rerope
for each in model.model.layers:
def forward(*args, **kwargs):
return forward_with_rerope(each.self_attn, *args, **kwargs)
each.self_attn.training_length = int(training_length)
... |
def main(args):
if ((args.dataset is None) or (len(args.dataset[0]) == 0)):
raise RuntimeError('No datasets provided')
datasets = args.dataset[0]
splits = [(x.split(',')[1] if (len(x.split(',')) == 2) else '') for x in datasets]
datasets = [x.split(',')[0] for x in datasets]
tokenizer = Au... |
def main(args):
dataset = load_dataset(args.dataset, split='train')
def truncate(sample):
sample['input_ids'] = sample['input_ids'][0:args.truncate]
sample['labels'] = sample['labels'][0:args.truncate]
sample['attention_mask'] = sample['attention_mask'][0:args.truncate]
return... |
def load_model(model, args):
if args.custom_model:
from scaled_rope.modeling_llama_yarn import LlamaForCausalLM
from scaled_rope.configuration_llama import LlamaConfig
model_cls = LlamaForCausalLM
config_cls = LlamaConfig
elif args.custom_model_together:
from scaled_rop... |
def add_args(parser: ArgumentParser):
parser.add_argument('--dynamic-linear', action='store_true')
parser.add_argument('--dynamic-ntk', type=float)
parser.add_argument('--dynamic-part-ntk', action='store_true')
parser.add_argument('--dynamic-yarn', action='store_true')
parser.add_argument('--ntk',... |
def apply_patches(model, args):
if ((not args.custom_model) and (not args.custom_model_together) and (not args.custom_model_mistral)):
if ('GPTNeoXForCausalLM' in model.config.architectures):
assert (args.gpt_neox_max_length is not None)
patch_gptneox_for_longer_sequences(model, ar... |
def load_model_and_apply_patches(model, args):
return apply_patches(load_model(model, args), args)
|
def generate_prompt(n_garbage):
'Generates a text file and inserts an execute line at a random position.'
n_garbage_prefix = random.randint(0, n_garbage)
n_garbage_suffix = (n_garbage - n_garbage_prefix)
task_description = 'There is an important info hidden inside a lot of irrelevant text. Find it and... |
def test_model(pipe, prompt_text, pass_key):
response = pipe(prompt_text, num_return_sequences=1, max_new_tokens=10)[0]['generated_text'][len(prompt_text):]
assert (f'The pass key is {pass_key}' in prompt_text)
try:
pass_key = int(re.search('\\d+', response).group())
except:
pass_key =... |
def main(args):
models = [x[0] for x in args.model]
tokenizer = AutoTokenizer.from_pretrained(models[0], model_max_length=sys.maxsize, padding_side='right', trust_remote_code=True)
if args.fixed_length:
lengths = [args.fixed_length]
tokens = [len(tokenizer.encode(generate_prompt(args.fixed... |
def order(i):
if (((i % 10) == 1) and ((i % 10) != 11)):
return (str(i) + 'st')
elif (((i % 10) == 2) and ((i % 10) != 12)):
return (str(i) + 'nd')
elif (((i % 19) == 3) and ((i % 10) != 13)):
return (str(i) + 'rd')
else:
return (str(i) + 'th')
|
def generate_prompt(docs, num_keys=1):
task_description = 'There is an important info hidden inside a lot of irrelevant text. Find it and memorize them. I will quiz you about the important information there.'
pass_keys = [random.randint(1, 50000) for _ in range(num_keys)]
start_pos = sorted([random.randin... |
def test_model(pipe, prompt_text):
response = pipe(prompt_text, num_return_sequences=1, max_new_tokens=10)[0]['generated_text'][len(prompt_text):]
try:
pass_key = int(re.search('\\d+', response).group())
except:
pass_key = response[:20]
return (pass_key, response)
|
def construct_junk(data, length, tokenizer):
token_count = 0
docs = []
length = (length or 8192)
while (token_count < length):
sample = random.choice(data)['text']
toks = tokenizer(sample, return_offsets_mapping=True)
offsets = [(i, j) for (i, j) in toks['offset_mapping'] if (i... |
def main(args):
models = [x[0] for x in args.model]
tokenizer = AutoTokenizer.from_pretrained(models[0], model_max_length=sys.maxsize, padding_side='right', trust_remote_code=True)
data = load_dataset(args.dataset)[args.split]
junks = construct_junk(data, args.fixed_length, tokenizer)
if args.rest... |
def main(args):
tokenizer = AutoTokenizer.from_pretrained(args.model, model_max_length=sys.maxsize, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
model = load_model_and_apply_patches(args.model, args)
pipe = pipeline('text-generation', model=model, tokenizer=tokenizer, pad_token_id... |
def get_prompt(sample):
options = sample['options']
instruction = ZERO_SCROLLS_QUALITY_PROMPT.format(story=sample['article'], question=sample['question'], a=options[0], b=options[1], c=options[2], d=options[3])
return f'''{instruction}
Answer: ('''
|
def main(args):
models = [x[0] for x in args.model]
tokenizer = AutoTokenizer.from_pretrained(models[0], model_max_length=sys.maxsize, trust_remote_code=True)
tokenizer.pad_token = tokenizer.eos_token
tokenizer.pad_token_id = tokenizer.eos_token_id
dataset = load_dataset('emozilla/quality', split=... |
def find_all_linear_names(model):
lora_module_names = set()
for (name, module) in model.named_modules():
if isinstance(module, torch.nn.Linear):
names = name.split('.')
lora_module_names.add((names[0] if (len(names) == 1) else names[(- 1)]))
if ('lm_head' in lora_module_nam... |
def main(args):
if args.output_dir:
os.makedirs(args.output_dir, exist_ok=True)
if args.wandb:
import wandb
wandb.login()
set_seed(args.seed)
timeout = InitProcessGroupKwargs(timeout=timedelta(seconds=1000000))
accelerator = Accelerator(gradient_accumulation_steps=args.grad... |
def main(args):
obj = json.load(open(args.file, 'r', encoding='utf-8'))
results = [result['acc'] for result in obj['results'].values()]
print(numpy.average(results))
|
def main(args):
data = pd.read_csv(args.csv)
(fig, ax) = plt.subplots(figsize=(10, 5))
x_data = [float(x) for x in data.columns[1:]]
for row in data.values:
label = row[0].replace('NousResearch/', '')
ax.plot(x_data, [float(x) for x in row[1:]], label=label)
ax.set_xlabel('Context ... |
class LlamaConfig(PretrainedConfig):
'\n This is the configuration class to store the configuration of a [`LlamaModel`]. It is used to instantiate an LLaMA\n model according to the specified arguments, defining the model architecture. Instantiating a configuration with the\n defaults will yield a similar... |
class MistralConfig(PretrainedConfig):
'\n This is the configuration class to store the configuration of a [`MistralModel`]. It is used to instantiate an\n Mistral model according to the specified arguments, defining the model architecture. Instantiating a configuration\n with the defaults will yield a s... |
def patch_llama_for_dynamic_scaled_rotary_embeddings(model, ntk):
from .LlamaDynamicScaledRotaryEmbedding import LlamaDynamicScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaDynamicScaledRotaryEmbedding(each.self_attn.head_dim, device=each.self_attn.rotary_emb.inv... |
def patch_llama_for_dynamic_part_ntk_rotary_embeddings(model, finetuned):
from .LlamaDynamicPartNTKScaledRotaryEmbedding import LlamaDynamicPartNTKScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaDynamicPartNTKScaledRotaryEmbedding(each.self_attn.head_dim, finetun... |
def patch_llama_for_dynamic_yarn_rotary_embeddings(model, original_max_position_embeddings, finetuned):
from .LlamaDynamicYaRNScaledRotaryEmbedding import LlamaDynamicYaRNScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaDynamicYaRNScaledRotaryEmbedding(each.self_a... |
def patch_falcon_for_dynamic_part_ntk_rotary_embeddings(model):
from .FalconDynamicPartNTKScaledRotaryEmbedding import FalconDynamicPartNTKScaledRotaryEmbedding
for each in model.transformer.h:
each.self_attention.maybe_rotary = FalconDynamicPartNTKScaledRotaryEmbedding(each.self_attention.head_dim)
|
def patch_llama_for_ntk_scaled_rotary_embeddings(model, alpha):
from .LlamaNTKScaledRotaryEmbedding import LlamaNTKScaledRotaryEmbedding
for each in model.model.layers:
each.self_attn.rotary_emb = LlamaNTKScaledRotaryEmbedding(each.self_attn.head_dim, alpha=alpha, device=each.self_attn.rotary_emb.inv_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.