Git Product home page Git Product logo

llm-shearing's Issues

Avoid OOM using deepspeed zero-stage

When pruning or continue training, I got OOM error even with batch size 1 & 8 GPUs.
I'm trying to use deepspeed zero stage or FSDP to avoid OOM. However, it seems your code isn't compatible well with deepspeed.
Could you help me with these OOM errors?

Scaling Law for predicted loss

Hi! Thanks for finally releasing the code. I've been trying to shear Yi-34B (after modifying it to be identical in architecture and tokenizer to Llama2) down to 20B. In the pruning.sh script, there's a target_loss that needs to be specified. What scaling law is it based on?

Metric Scores and NQ Evaluation

Hi there, thanks very much for such an amazing work!
Currently, I'm trying to reproduce the results from the paper, but I have the following problems:

  • Metric scores: lm-eval-harness would return acc and acc_norm at the same time. Do you have a preference to use one of them?
  • NQ evaluation: I've checked the evaluation codebase and your starter scripts, but have no clues about the evaluation on the Natural Questions (NQ) dataset (it is not implemented in lm-eval-harness yet).
    Did you write an evaluation script, or adopt an existing repo to get the scores?

Thank you so much for your time and response~

在进行Building trainer时,训练会卡住;

你好,我使用的是样例测试集,想跑通README. 但是发现,在训练的时候,会卡住,然后超时;
[batch=23/3200]:
Train time/batch: 22
Train time/sample: 198
Train time/batch_in_epoch: 6
Train time/sample_in_epoch: 54
Train time/token: 811008
Train time/token_in_epoch: 221184
Train metrics/train/cc_weight: 0.6700
Train metrics/train/github_weight: 0.0450
Train metrics/train/book_weight: 0.0450
Train metrics/train/stackexchange_weight: 0.0200
Train metrics/train/wiki_weight: 0.0450
Train metrics/train/arxiv_weight: 0.0250
Train metrics/train/c4-rp_weight: 0.1500
Train memory/current_allocated_mem: 36.8820
Train memory/current_active_mem: 36.8820
Train memory/current_inactive_mem: 0.1744
Train memory/current_reserved_mem: 55.9060
Train memory/peak_allocated_mem: 42.9380
Train memory/peak_active_mem: 42.9380
Train memory/peak_inactive_mem: 7.8742
Train memory/peak_reserved_mem: 55.9060
Train memory/alloc_retries: 0
Train metrics/train/expected_head_sparsity: 0.0039
Train metrics/train/target_head_sparsity: 0.0129
Train metrics/train/expected_intermediate_sparsity: 0.0039
Train metrics/train/target_intermediate_sparsity: 0.0128
Train metrics/train/expected_layer_sparsity: 0.0039
Train metrics/train/target_layer_sparsity: 0.0000
Train metrics/train/expected_hidden_sparsity: 0.0039
Train metrics/train/target_hidden_sparsity: 0.0129
Train metrics/train/expected_sparsity: 0.0117
Train metrics/train/target_sparsity: 0.0209
Train trainer/device_train_microbatch_size: 3
Train loss/train/total: 1.4801
Train loss/train/ce_loss: 1.4716
Train loss/train/lag_loss: 0.0085
Train metrics/train/LanguageCrossEntropy: 1.4716
Train metrics/train/Perplexity: 4.3561
Train metrics/train/cc_LanguageCrossEntropy: 1.1558
Train metrics/train/cc_count: 65
Train metrics/train/github_LanguageCrossEntropy: nan
Train metrics/train/github_count: 7
Train metrics/train/book_LanguageCrossEntropy: nan
Train metrics/train/book_count: 7
Train metrics/train/stackexchange_LanguageCrossEntropy: 2.1491
Train metrics/train/stackexchange_count: 3
Train metrics/train/wiki_LanguageCrossEntropy: 1.5306
Train metrics/train/wiki_count: 8
Train metrics/train/arxiv_LanguageCrossEntropy: nan
Train metrics/train/arxiv_count: 6
Train metrics/train/c4-rp_LanguageCrossEntropy: 1.6471
Train metrics/train/c4-rp_count: 111
Train throughput/batches_per_sec: 0.0914
Train throughput/samples_per_sec: 0.8223
Train throughput/device/batches_per_sec: 0.0305
Train throughput/device/samples_per_sec: 0.2741
Train throughput/tokens_per_sec: 3368.2385
Train throughput/device/tokens_per_sec: 1122.7462
Train throughput/flops_per_sec: 157886485043818.8125
Train throughput/device/flops_per_sec: 52628828347939.6016
Train throughput/device/mfu: 0.1687
Train time/train: 0.0709
Train time/val: 0.0000
Train time/total: 0.0709
Train lr-DecoupledAdamW/group0: 0.0000
Train lr-DecoupledAdamW/group1: 0.0688
Train lr-DecoupledAdamW/group2: -0.0688
[E ProcessGroupNCCL.cpp:828] [Rank 2] Watchdog caught collective operation timeout: WorkNCCL(SeqNum=3777, OpType=_ALLGATHER_BASE, Timeout(ms)=1800000) ran for 1802129 milliseconds before timing out.
[E ProcessGroupNCCL.cpp:455] Some NCCL operations have failed or timed out. Due to the asynchronous nature of CUDA kernels, subsequent GPU operations might run on corrupted/incomplete data.
[E ProcessGroupNCCL.cpp:460] To avoid data inconsistency, we are taking the entire process down.
terminate called after throwing an instance of 'std::runtime_error'
what(): [Rank 2] Watchdog caught collective operation timeout: WorkNCCL(SeqNum=3777, OpType=_ALLGATHER_BASE, Timeout(ms)=1800000) ran for 1802129 milliseconds before timing out.

AssertionError: Currently only supports dynamic loading from each domain for once.

When I use a single node, 8*A100 80G configuration, I find that an error occurs:

LLM-Shearing/llmshearing/datasets/streaming_da │
│ taset.py:46 in generate_work                                                                     │
│                                                                                                  │
│    43 │   │   List[List[int]]: The epoch for each domain of data (num physical nodes,            │
│    44 │   │   ranks per node, workers per rank, batches per worker, batch size).                 │
│    45 │   """                                                                                    │
│ ❱  46 │   assert epoch == 0, "Currently only supports dynamic loading from each domain for onc   │
│    47 │   # Ensure that num_canonical_nodes has been set.                                        │
│    48 │   if dataset.num_canonical_nodes is None:                                                │
│    49 │   │   raise RuntimeError(f'`num_canonical_nodes` can never be None. ' +                  │
╰───────────────────────────────────────────
AssertionError: Currently only supports dynamic loading from each domain for once.

If I delete "assert epoch == 0, "Currently only supports dynamic loading from each domain for once.", i will cause another error in

# Currently only supports dynamically loading data from each domain for once. 
        # Issues could occur if one domain of data is used up. 
        while True:
            proportion = self.proportion
            stream_id = np.random.choice(range(self.num_streams), 1, p=proportion)[0].item()
            domain_sample_id = sample_ids_per_stream[stream_id]
            domain_sample_id = domain_sample_id[self.used_num_samples_per_stream[stream_id] \
                                % self.samples_per_stream[stream_id]]
            self.used_num_samples_per_stream[stream_id] += 1
            yield self[domain_sample_id]
---
IndexError: index 24 is out of bounds for axis 0 with size 24

If i add "if world.is_local_leader and epoch==0:"
SharedMemory in _attach_work will come error:

│   304 │   │   │   # Load the generated epoch shape from shared memory.                           │
│   305 │   │   │   name = _get_path(self._shm_prefix_int, EPOCH_SHAPE + f"_{stream_id}")          │
│   306 │   │   │   size = ndim * np.int64().nbytes                                                │
│ ❱ 307 │   │   │   shape_shm = SharedMemory(name=name, create=False, size=size, auto_cleanup=Fa   │
│   308 │   │   │   shape = tuple(np.ndarray(5, buffer=shape_shm.buf, dtype=np.int64))             │
│   309 │   │   │                                                                                  │
│   310 │   │   │   # Attach to the generated epoch data in shared memory.      
---
FileNotFoundError: [Errno 2] No such file or directory: '/000000_epoch_shape_0'
Exception ignored in atexit callback: <function Engine._close at 0x7fe6dc766a70>

KV head count on princeton-nlp/Sheared-LLaMA-1.3B-ShareGPT ?

Hi! While testing the model with vLLM vllm-project/vllm#1913 I found out that the KV head count seemed strange, why is it 32 instead of the 16 like the base sheared llama?

Is it safe for me to just change that value to 16 and use the model that way?

Thanks for the great work! I've dreamed about just pruning LLMs for speculative decoding instead of training a separate model for a long time! :)

Composer Model Transform problems encountered when shearing Pythia 1.4b

Pythia helps study the effects of pruning at different LM scales.
Noticed that you provided composer_pythia.py, so I tried running this experiment on 1.4b scale pythia. I'm having some problems.

The first is the writing of the pythia_to_composer conversion function for several settings I made.
The keymap here is what I inferred based on your composer_pythia.py

def get_gpt_key_map_from_hf_to_composer(num_layers):
    """ get the keymap from hf to composer """
    key_map = {}
    key_map.update({"gpt_neox.embed_in.weight": "model.transformer.wte.weight",
                    "gpt_neox.final_layer_norm.weight": "model.transformer.ln_f.weight",
                    "gpt_neox.final_layer_norm.bias": "model.transformer.ln_f.bias",
                    "embed_out.weight": "model.transformer.output.weight",
                    "embed_out.bias": "model.transformer.output.bias"})
    for i in range(num_layers):
        key_map.update({
                        f"gpt_neox.layers.{i}.input_layernorm.weight": f"model.transformer.blocks.{i}.ln_1.weight",
                        f"gpt_neox.layers.{i}.post_attention_layernorm.weight": f"model.transformer.blocks.{i}.ln_2.weight",
                        f"gpt_neox.layers.{i}.attention.query_key_value.weight": f"model.transformer.blocks.{i}.attn.query_key_value.weight",
                        f"gpt_neox.layers.{i}.attention.dense.weight": f"model.transformer.blocks.{i}.attn.out_proj.weight",
                        f"gpt_neox.layers.{i}.mlp.dense_h_to_4h.weight": f"model.transformer.blocks.{i}.mlp.up_proj.weight",
                        f"gpt_neox.layers.{i}.mlp.dense_4h_to_h.weight": f"model.transformer.blocks.{i}.mlp.down_proj.weight",
                        f"gpt_neox.layers.{i}.input_layernorm.bias": f"model.transformer.blocks.{i}.ln_1.bias",
                        f"gpt_neox.layers.{i}.post_attention_layernorm.bias": f"model.transformer.blocks.{i}.ln_2.bias",
                        f"gpt_neox.layers.{i}.attention.query_key_value.bias": f"model.transformer.blocks.{i}.attn.query_key_value.bias",
                        f"gpt_neox.layers.{i}.attention.dense.bias": f"model.transformer.blocks.{i}.attn.out_proj.bias",
                        f"gpt_neox.layers.{i}.mlp.dense_h_to_4h.bias": f"model.transformer.blocks.{i}.mlp.up_proj.bias",
                        f"gpt_neox.layers.{i}.mlp.dense_4h_to_h.bias": f"model.transformer.blocks.{i}.mlp.down_proj.bias",
                        f"gpt_neox.layers.{i}.attention.rotary_emb.inv_freq": f"model.transformer.blocks.{i}.attn.rotary_emb.inv_freq",
                       })
    return key_map

In test_composer_hf_equal.py

def construct_example_cfg(model_size, path=None, add_l0_module=False):
    """ construct example cfg for mosaicml llama models """
    if model_size == "1.4b":
        cfg = om.create({"name": "mosaic_pythia_1", "init_device": "cpu", "d_model": 2048, 
                         "n_heads": 16, "n_layers": 24, "intermediate_size": 8192,
                         "rotary_pct": 0.25, "rotary_emb_base": 10000
                         })

    # add default values
    cfg = om.merge(cfg, om.create({"max_seq_len": 2048, "vocab_size": 50304, "init_std": 0.02, "attn_pdrop": 0.0, "resid_pdrop": 0.0, "emb_pdrop": 0.0, "attn_impl": "norm", "layer_norm_eps": 1e-5}))
    if add_l0_module:
        cfg["l0_module"] = {"start_sparsity": 0, "target_sparsity": 0.6, "pruning_modules": ["head", "head_layer", "mlp", "intermediate", "hidden"], "lagrangian_warmup_steps": "320ba"}
    return cfg

final result

(Pdb) composer_model
ComposerMosaicPythia(
  (model): PythiaModel(
    (transformer): ModuleDict(
      (wte): PythiaEmbedding(50304, 2048)
      (blocks): ModuleList(
        (0-23): 24 x PythiaBlock(
          (ln_1): CoFiLayerNorm((2048,), eps=1e-05, elementwise_affine=True)
          (attn): PythiaAttention(
            (query_key_value): Linear(in_features=2048, out_features=6144, bias=True)
            (out_proj): Linear(in_features=2048, out_features=2048, bias=True)
            (rotary_emb): RotaryEmbedding()
          )
          (ln_2): CoFiLayerNorm((2048,), eps=1e-05, elementwise_affine=True)
          (mlp): PythiaMLP(
            (down_proj): Linear(in_features=8192, out_features=2048, bias=True)
            (up_proj): Linear(in_features=2048, out_features=8192, bias=True)
          )
        )
      )
      (output): Linear(in_features=2048, out_features=50304, bias=False)
      (ln_f): CoFiLayerNorm((2048,), eps=1e-05, elementwise_affine=True)
    )
  )
)
(Pdb) hf_model
GPTNeoXForCausalLM(
  (gpt_neox): GPTNeoXModel(
    (embed_in): Embedding(50304, 2048)
    (emb_dropout): Dropout(p=0.0, inplace=False)
    (layers): ModuleList(
      (0-23): 24 x GPTNeoXLayer(
        (input_layernorm): LayerNorm((2048,), eps=1e-05, elementwise_affine=True)
        (post_attention_layernorm): LayerNorm((2048,), eps=1e-05, elementwise_affine=True)
        (post_attention_dropout): Dropout(p=0.0, inplace=False)
        (post_mlp_dropout): Dropout(p=0.0, inplace=False)
        (attention): GPTNeoXAttention(
          (rotary_emb): GPTNeoXRotaryEmbedding()
          (query_key_value): Linear(in_features=2048, out_features=6144, bias=True)
          (dense): Linear(in_features=2048, out_features=2048, bias=True)
          (attention_dropout): Dropout(p=0.0, inplace=False)
        )
        (mlp): GPTNeoXMLP(
          (dense_h_to_4h): Linear(in_features=2048, out_features=8192, bias=True)
          (dense_4h_to_h): Linear(in_features=8192, out_features=2048, bias=True)
          (act): GELUActivation()
        )
      )
    )
    (final_layer_norm): LayerNorm((2048,), eps=1e-05, elementwise_affine=True)
  )
  (embed_out): Linear(in_features=2048, out_features=50304, bias=False)
)

The structure of the two models looks very different. I don't know if this is an issue with the structural organization in composer_pythia.py. Finally, I tested the output of the two models, and there was a huge difference.

Will you disclose Python-related experimental code? Do you need me to contribute relevant code?

The implementation of dynamic batch loading code seems inconsistent with the pseudo-code in the paper

For example, truncating the loss difference to 0 does not seem to be implemented.
image

diff = torch.tensor(losses) - torch.tensor(self.target_loss)

And, what is the purpose of this line?

updated_domain_weights = (1-c) * updated_alpha + c / self.n_domains

Error running CheckpointSaver.close(). Skipping CheckpointSaver.post_close()

batch=336/5000]:
Train time/batch: 335
Train time/sample: 85760
Train time/batch_in_epoch: 335
Train time/sample_in_epoch: 85760
Train time/token: 351272960
Train time/token_in_epoch: 351272960
Train metrics/train/academic_en_weight: 0.0733
Train metrics/train/book_en_weight: 0.2521
Train metrics/train/code_weight: 0.0122
Train metrics/train/qa_en_weight: 0.0900
Train metrics/train/webtext_en_weight: 0.4453
Train metrics/train/wiki_en_weight: 0.1271
Train memory/current_allocated_mem: 17.7600
Train memory/current_active_mem: 17.7600
Train memory/current_inactive_mem: 3.8283
Train memory/current_reserved_mem: 74.4430
Train memory/peak_allocated_mem: 60.7340
Train memory/peak_active_mem: 61.1380
Train memory/peak_inactive_mem: 27.1850
Train memory/peak_reserved_mem: 74.4430
Train memory/alloc_retries: 0
Train trainer/device_train_microbatch_size: 16
Train loss/train/total: 1.8199
Train loss/train/ce_loss: 1.8199
Train metrics/train/LanguageCrossEntropy: 1.8199
Train metrics/train/Perplexity: 6.1711
Train metrics/train/academic_en_LanguageCrossEntropy: 1.3244
Train metrics/train/academic_en_count: 9893
Train metrics/train/book_en_LanguageCrossEntropy: 1.8898
Train metrics/train/book_en_count: 20179
Train metrics/train/code_LanguageCrossEntropy: 0.8853
Train metrics/train/code_count: 4807
Train metrics/train/qa_en_LanguageCrossEntropy: 1.4436
Train metrics/train/qa_en_count: 10816
Train metrics/train/webtext_en_LanguageCrossEntropy: 2.0363
Train metrics/train/webtext_en_count: 27327
Train metrics/train/wiki_en_LanguageCrossEntropy: 1.5175
Train metrics/train/wiki_en_count: 12994
Train throughput/batches_per_sec: 0.0204
Train throughput/samples_per_sec: 5.2330
Train throughput/device/batches_per_sec: 0.0026
Train throughput/device/samples_per_sec: 0.6541
Train throughput/tokens_per_sec: 21434.4781
Train throughput/device/tokens_per_sec: 2679.3098
Train throughput/flops_per_sec: 1004697191366202.0000
Train throughput/device/flops_per_sec: 125587148920775.2500
Train time/train: 4.5453
Train time/val: 0.1311
Train time/total: 4.6764
Train lr-DecoupledAdamW/group0: 0.0001
Error running CheckpointSaver.close(). Skipping CheckpointSaver.post_close().
Traceback (most recent call last):
File "/home/pai/lib/python3.9/site-packages/composer/core/engine.py", line 527, in _close
callback.close(state, logger)
File "/home/pai/lib/python3.9/site-packages/composer/callbacks/checkpoint_saver.py", line 310, in close
self._save_checkpoint(
File "/home/pai/lib/python3.9/site-packages/composer/callbacks/checkpoint_saver.py", line 332, in _save_checkpoint
saved_path = checkpoint.save_checkpoint(
File "/home/pai/lib/python3.9/site-packages/composer/utils/checkpoint.py", line 761, in save_checkpoint
'state': state.state_dict(),
File "/home/pai/lib/python3.9/site-packages/composer/core/state.py", line 891, in state_dict
serialized_value = self.get_model_state_dict()
File "/home/pai/lib/python3.9/site-packages/composer/core/state.py", line 868, in get_model_state_dict
model_state_dict = self.model.state_dict()
File "/home/pai/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1818, in state_dict
module.state_dict(destination=destination, prefix=prefix + name + '.', keep_vars=keep_vars)
File "/home/pai/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1815, in state_dict
self._save_to_state_dict(destination, prefix, keep_vars)
File "/home/pai/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1722, in _save_to_state_dict
hook(self, prefix, keep_vars)
File "/home/pai/lib/python3.9/site-packages/torch/utils/_contextlib.py", line 115, in decorate_context
return func(*args, **kwargs)
File "/home/pai/lib/python3.9/site-packages/torch/distributed/fsdp/_state_dict_utils.py", line 669, in _pre_state_dict_hook
_pre_state_dict_hook_fn[fsdp_state._state_dict_type](
File "/home/pai/lib/python3.9/site-packages/torch/distributed/fsdp/_state_dict_utils.py", line 271, in _full_pre_state_dict_hook
_common_unshard_pre_state_dict_hook(
File "/home/pai/lib/python3.9/site-packages/torch/distributed/fsdp/_state_dict_utils.py", line 143, in _common_unshard_pre_state_dict_hook
_enter_unshard_params_ctx(
File "/home/pai/lib/python3.9/site-packages/torch/distributed/fsdp/_state_dict_utils.py", line 109, in _enter_unshard_params_ctx
fsdp_state._unshard_params_ctx[module].enter()
File "/home/pai/lib/python3.9/contextlib.py", line 119, in enter
return next(self.gen)
File "/home/pai/lib/python3.9/site-packages/torch/distributed/fsdp/_unshard_param_utils.py", line 186, in _unshard_fsdp_state_params
assert (
AssertionError: Expects the handle training to be IDLE but got HandleTrainingState.BACKWARD_PRE
Stack (most recent call last):
File "/home/pai/lib/python3.9/site-packages/composer/core/engine.py", line 483, in del
self.close()
File "/home/pai/lib/python3.9/site-packages/composer/core/engine.py", line 512, in close
self._close(self.state, self.logger)
File "/home/pai/lib/python3.9/site-packages/composer/core/engine.py", line 529, in _close

Has anyone encountered this issue before? Why do I always get an error when I train with eight cards on a single machine for over 300 batchs, even though I definitely have enough training data?

When should we apply hidden_z?

I notice that hidden_z is applied in almost every module in every layer, and I'm curious about whether it will result in issue like gradient vanishing and exploding? And, will it have a large influence on the magnitude of the last hidden state, as the same scale is repeatedly multiplied?

Sample.py error when sampling stackexchage

SLURM_ARRAY_TASK_ID=5 python sample.py --target_dir mds_redpajama --tokenized_dir hadoop/tokenized_redpajama An error will occur. The reason is that stackexchage only has one file, while sample.py requires multiple files to be split

> /root/personal-code/LLM-Shearing/llmshearing/data/sample.py(69)<module>()
-> folder_eval_target = args.eval_seq
(Pdb) c
Traceback (most recent call last):
  File "/root/personal-code/LLM-Shearing/llmshearing/data/sample.py", line 70, in <module>
    num_sample_each_file = max(1, folder_eval_target // len(selected) + 1)
ZeroDivisionError: integer division or modulo by zero```

How much compute will this take?

Hi,
If I want to make a 1B/3B model for Mistral, do you know approximately how many dollars I'll have to spend in compute, and whether I can do it on a consumer GPU? Thanks!

Missing index.json in dataset shared on drive

Hello,

Thank you for sharing the dataset used for pruning.
Trying to use that dataset (by setting DATA_DIR in pruning.sh) results in the below error however -

Building train loader...
╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮
│                          /LLM-Shearing/llmshearing/train.py:317 in <module>                      │
│                                                                                                  │
│   314 │   os.makedirs(save_dir, exist_ok=True)                                                   │
│   315 │   torch.save(cfg, save_dir + "/config.pt")                                               │
│   316 │                                                                                          │
│ ❱ 317 │   main(cfg)                                                                              │
│   318                                                                                            │
│   319                                                                                            │
│                                                                                                  │
│                          /LLM-Shearing/llmshearing/train.py:201 in main                          │
│                                                                                                  │
│   198 │                                                                                          │
│   199 │   # Dataloaders                                                                          │
│   200 │   print('Building train loader...')                                                      │
│ ❱ 201 │   train_loader = build_text_dataloader(cfg.train_loader,                                 │
│   202 │   │   │   │   │   │   │   │   │   │    cfg.device_train_batch_size,                      │
│   203 │   │   │   │   │   │   │   │   │   │    cfg.callbacks.data_loading.dynamic,               │
│   204 │   │   │   │   │   │   │   │   │   │    cfg.callbacks.data_loading.set_names,             │
│                                                                                                  │
│                          /LLM-Shearing/llmshearing/datasets/load_text_dataloader.py:36 in        │
│ build_text_dataloader                                                                            │
│                                                                                                  │
│    33 │   """                                                                                    │
│    34 │                                                                                          │
│    35 │   if dynamic:                                                                            │
│ ❱  36 │   │   dataset = TextDynamicStreamingDataset(local=cfg.dataset.local,                     │
│    37 │   │   │   │   │   │   │   │   │   │   │     max_seq_len=cfg.dataset.max_seq_len,         │
│    38 │   │   │   │   │   │   │   │   │   │   │     batch_size=device_batch_size,                │
│    39 │   │   │   │   │   │   │   │   │   │   │     shuffle=cfg.dataset.get(                     │
│                                                                                                  │
│                          /LLM-Shearing/llmshearing/datasets/streaming_dataset.py:415 in __init__ │
│                                                                                                  │
│   412 │   │   │   │    is_uint16: bool = False):                                                 │
│   413 │   │                                                                                      │
│   414 │   │   # Build Dataset                                                                    │
│ ❱ 415 │   │   super().__init__(local=local,                                                      │
│   416 │   │   │   │   │   │    shuffle=shuffle,                                                  │
│   417 │   │   │   │   │   │    shuffle_seed=shuffle_seed,                                        │
│   418 │   │   │   │   │   │    num_canonical_nodes=num_canonical_nodes,                          │
│                                                                                                  │
│                          /LLM-Shearing/llmshearing/datasets/streaming_dataset.py:114 in __init__ │
│                                                                                                  │
│   111 │   │   │   │    proportion: List[float] = None) -> None:                                  │
│   112 │   │                                                                                      │
│   113 │   │   streams = [Stream(local=local, split=set_name, repeat=1.0) for set_name in set_n   │
│ ❱ 114 │   │   super().__init__(streams=streams,                                                  │
│   115 │   │   │   │   │   │    split=None,                                                       │
│   116 │   │   │   │   │   │    num_canonical_nodes=num_canonical_nodes,                          │
│   117 │   │   │   │   │   │    batch_size=batch_size,                                            │
│                                                                                                  │
│                          /lib/python3.10/site-packages/streaming/base/dataset.py:443 in    │
│ __init__                                                                                         │
│                                                                                                  │
│    440 │   │   self.sample_offset_per_stream = np.zeros(self.num_streams, np.int64)              │
│    441 │   │   self.samples_per_stream = np.zeros(self.num_streams, np.int64)                    │
│    442 │   │   for stream_id, stream in enumerate(self.streams):                                 │
│ ❱  443 │   │   │   stream_shards = stream.get_shards(world)                                      │
│    444 │   │   │   num_stream_samples = sum(map(len, stream_shards))                             │
│    445 │   │   │   if not num_stream_samples:                                                    │
│    446 │   │   │   │   index_filename = os.path.join(stream.local, stream.split, get_index_base  │
│                                                                                                  │
│                                /lib/python3.10/site-packages/streaming/base/stream.py:437 in     │
│ get_shards                                                                                       │
│                                                                                                  │
│   434 │   │   │   │   │   os.rename(tmp_filename, filename)                                      │
│   435 │   │   │   │   else:                                                                      │
│   436 │   │   │   │   │   if not os.path.exists(filename):                                       │
│ ❱ 437 │   │   │   │   │   │   raise RuntimeError(f'No `remote` provided, but local file {filen   │
│   438 │   │   │   │   │   │   │   │   │   │      'does not exist either')                        │
│   439 │   │   │   else:                                                                          │
│   440 │   │   │   │   wait_for_file_to_exist(                                                    │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
RuntimeError: No `remote` provided, but local file /for_prune/cc/index.json does not exist either

If this is not the correct way to use this shared dataset, could you let me know what's the recommend way to use this shared dataset to reproduce the results? Or perhaps could you upload the dataset including the index.json files?

Pruning crash at iteration 592.

@xiamengzhou
[batch=592/3200]
Train time/batch: 591
Train time/sample: 18912
Train time/batch_in_epoch: 591
Train time/sample_in_epoch: 18912
Train time/token: 77463552
Train time/token_in_epoch: 77463552
Train metrics/train/cc_weight: 0.2292
Train metrics/train/github_weight: 0.0121
Train metrics/train/book_weight: 0.0220
Train metrics/train/stackexchange_weight: 0.0059
Train metrics/train/wiki_weight: 0.5933
Train metrics/train/arxiv_weight: 0.0038
Train metrics/train/c4-rp_weight: 0.1336
Train memory/current_allocated_mem: 14.6140
Train memory/current_active_mem: 14.6140
Train memory/current_inactive_mem: 1.9265
Train memory/current_reserved_mem: 43.4220
Train memory/peak_allocated_mem: 28.0710
Train memory/peak_active_mem: 28.0710
Train memory/peak_inactive_mem: 11.7290
Train memory/peak_reserved_mem: 43.4220
Train memory/alloc_retries: 0
Train metrics/train/expected_head_sparsity: 0.3583
Train metrics/train/target_head_sparsity: 0.3463
Train metrics/train/expected_intermediate_sparsity: 0.3196
Train metrics/train/target_intermediate_sparsity: 0.3436
Train metrics/train/expected_layer_sparsity: 0.0039
Train metrics/train/target_layer_sparsity: 0.0000
Train metrics/train/expected_hidden_sparsity: 0.4266
Train metrics/train/target_hidden_sparsity: 0.3463
Train metrics/train/expected_sparsity: 0.6188
Train metrics/train/target_sparsity: 0.5616
Train trainer/device_train_microbatch_size: 4
Train loss/train/total: 3.5578
Train loss/train/ce_loss: 2.8953
Train loss/train/lag_loss: 0.6625
Train metrics/train/LanguageCrossEntropy: 2.8953
Train metrics/train/Perplexity: 18.0886
Train metrics/train/cc_LanguageCrossEntropy: 3.0387
Train metrics/train/cc_count: 9884
Train metrics/train/github_LanguageCrossEntropy: nan
Train metrics/train/github_count: 652
Train metrics/train/book_LanguageCrossEntropy: nan
Train metrics/train/book_count: 712
Train metrics/train/stackexchange_LanguageCrossEntropy: nan
Train metrics/train/stackexchange_count: 236
Train metrics/train/wiki_LanguageCrossEntropy: 2.7964
Train metrics/train/wiki_count: 4011
Train metrics/train/arxiv_LanguageCrossEntropy: nan
Train metrics/train/arxiv_count: 267
Train metrics/train/c4-rp_LanguageCrossEntropy: 3.1243
Train metrics/train/c4-rp_count: 3182
Train throughput/batches_per_sec: 0.1329
Train throughput/samples_per_sec: 4.2523
Train throughput/device/batches_per_sec: 0.0166
Train throughput/device/samples_per_sec: 0.5315
Train throughput/tokens_per_sec: 17417.3748
Train throughput/device/tokens_per_sec: 2177.1719
Train throughput/flops_per_sec: 816440956730026.0000
Train throughput/device/flops_per_sec: 102055119591253.2500
Train time/train: 1.2715
Train time/val: 0.6538
Train time/total: 1.9253
Traceback (most recent call last):
File "/llm-shearing//llmshearing/train.py", line 317, in
main(cfg)
File "/llm-shearing//llmshearing/train.py", line 301, in main
trainer.fit()
File "/pyenv/py310-shear/lib/python3.10/site-packages/composer/trainer/trainer.py", line 18
76, in fit
self._train_loop()
File "/pyenv/py310-shear/lib/python3.10/site-packages/composer/trainer/trainer.py", line 20
18, in _train_loop
for batch_idx, self.state.batch in enumerate(self._iter_dataloader(TrainerMode.TRAIN)):
File "/pyenv/py310-shear/lib/python3.10/site-packages/composer/trainer/trainer.py", line 30
24, in _iter_dataloader
batch = next(dataloader_iter)
File "/pyenv/py310-shear/lib/python3.10/site-packages/torch/utils/data/dataloader.py", line
630, in next
data = self._next_data()
File "/pyenv/py310-shear/lib/python3.10/site-packages/torch/utils/data/dataloader.py", line
674, in _next_data
data = self._dataset_fetcher.fetch(index) # may raise StopIteration
File "/pyenv/py310-shear/lib/python3.10/site-packages/torch/utils/data/_utils/fetch.py", li
ne 32, in fetch
data.append(next(self.dataset_iter))
File "/llm-shearing/llmshearing/datasets/streaming_dataset.py", line 392,
in iter
domain_sample_id = domain_sample_id[self.used_num_samples_per_stream[stream_id]
IndexError: index 552 is out of bounds for axis 0 with size 552

Reproduce as follow:
prepare data for prunnig as paper said.
then execuate following command
/bin/bash llmshearing/scripts/prunning.sh

missmatch shape

下面是我的config.pt的文件内容

{'data_local': '/workspace/LLM-shearing/LLM-Shearing/llmshearing/data/mds_sample_redpajama/for_prune', 'data_remote': None, 'tokenizer_name': '/workspace/LLM-shearing/models/Llama-2-7b-hf', 'max_seq_len': 4096, 'global_seed': 17, 'run_name': 'llama2_7b_pruning_scaling_constant_to2.7b_sl4096', 'model': {'name': 'mosaic_llama2_7b', 'path': '/workspace/LLM-shearing/models/Llama-2-7b-composer/state_dict.pt', 'init_device': 'cpu', 'tokenizer_name': '${tokenizer_name}', 'd_model': 4096, 'n_heads': 32, 'n_layers': 32, 'intermediate_size': 11008, 'max_seq_len': '${max_seq_len}', 'vocab_size': 32000, 'init_std': 0.02, 'attn_pdrop': 0.0, 'resid_pdrop': 0.0, 'emb_pdrop': 0.0, 'attn_impl': 'flash', 'rms_norm_eps': 1e-05, 'l0_module': {'start_sparsity': 0.0, 'target_sparsity': 0.5, 'pruning_modules': ['head', 'intermediate', 'layer', 'hidden'], 'lagrangian_warmup_steps': '640ba', 'target_model': {'d_model': 2560, 'n_layers': 32, 'n_heads': 20, 'intermediate_size': 6912, 'vocab_size': 32000}, 'eval_target_model': False}}, 'tokenizer': {'type': 'hftokenizer', 'args': {'tokenizer_name': '${tokenizer_name}', 'max_seq_len': '${max_seq_len}'}}, 'train_loader': {'name': 'text', 'dataset': {'local': '${data_local}', 'remote': '${data_remote}', 'split': 'wikipedia', 'shuffle': True, 'tokenizer_name': '${tokenizer_name}', 'max_seq_len': '${max_seq_len}', 'shuffle_seed': '${global_seed}', 'is_uint16': True}, 'drop_last': True, 'num_workers': 0, 'prefetch_factor': None, 'persistent_workers': False}, 'eval_loader': {'name': 'text', 'dataset': {'local': '/workspace/LLM-shearing/LLM-Shearing/llmshearing/data/mds_sample_redpajama/eval', 'remote': '${data_remote}', 'split': 'eval_merge', 'shuffle': False, 'tokenizer_name': '${tokenizer_name}', 'max_seq_len': '${max_seq_len}', 'shuffle_seed': '${global_seed}', 'is_uint16': True}, 'drop_last': False, 'num_workers': 8}, 'scheduler': {'name': 'cosine_with_warmup', 't_warmup': '320ba', 'alpha_f': 0.1}, 'optimizer': {'name': 'decoupled_adamw', 'lr': 0.0001, 'betas': [0.9, 0.95], 'eps': 1e-08, 'weight_decay': 0.0, 'lag_lr': 1.0}, 'algorithms': {'gradient_clipping': {'clipping_type': 'norm', 'clipping_threshold': 1.0}}, 'max_duration': '3200ba', 'eval_interval': '50ba', 'eval_subset_num_batches': 1000, 'global_train_batch_size': 8, 'seed': '${global_seed}', 'device_eval_batch_size': 2, 'device_train_microbatch_size': 4, 'precision': 'amp_bf16', 'fsdp_config': {'sharding_strategy': 'FULL_SHARD', 'mixed_precision': 'DEFAULT', 'activation_checkpointing': True, 'activation_cpu_offload': False, 'verbose': False}, 'progress_bar': False, 'log_to_console': True, 'console_log_interval': '1ba', 'callbacks': {'speed_monitor': {'window_size': 10}, 'memory_monitor': {}, 'lr_monitor': {}, 'data_loading': {'dynamic': True, 'update_type': 'constant', 'proportion': [0.67, 0.045, 0.045, 0.02, 0.045, 0.025, 0.15], 'set_names': ['cc', 'github', 'book', 'stackexchange', 'wiki', 'arxiv', 'c4-rp'], 'target_loss': None}}, 'loggers': {'wandb': {'project': 'pruning', 'name': '${run_name}', 'entity': 'pruning', 'init_kwargs': {'mode': 'offline', 'dir': '/workspace/LLM-shearing/models/llama2_7b_pruning_scaling_constant_to2.7b_sl4096'}}}, 'save_interval': '3200ba', 'save_folder': '/workspace/LLM-shearing/models/llama2_7b_pruning_scaling_constant_to2.7b_sl4096', 'eval_first': False, 'autoresume': False}

我在执行composer_to_hf 时有2个问题:
一个是发现训练之后的模型结果存在keyError: l0_module找不到的问题,代码在
num_layers = get_layer_num_from_weights(weights) keymap = get_key_map_from_composer_to_hf(num_layers) hf_weights = {keymap[key]: weights[key] for key in weights if "rotary" not in key }
这段代码中是说过滤掉所有的包含 rotary 权重,但是问题是weights中有l0_module相关的权重信息,导致不能转到hf上,从而报错,我尝试将l0相关的weihgt干掉,然后保存下来的模型又说missmatch
1、去掉l0相关权重是否可行?
2、我training的配置文件是否存在问题?
感谢支持;

Any updates on the code?

Would love to experiment with LLM shearing, is the progress on finalizing the code still ongoing?

ShearedCodeLLama

Hi! I am working on a copilot backend and, even though I am using a GPTQ quant of codellama7b, it is still eating lots of VRAM
DeepSeek coder seems to have severe issues understanding fill in the middle

I wanted to ask if you plan on also shearing CodeLlama? :)

Dynamic Batch Loading v.s. Domain Reweighting

image

we can see from Table 3 that dynamic batch loading results in down-sampling CC & Github and up-sampling Book & C4. I wonder if I re-sample the pretraining data according to this recipe ahead-of-time, and do pruning and continue-training on the re-sampled data directly, will it reach the same performance ?

LanguageCrossEntropy logs nan when bash pruning.sh

When I conducted the pruning experiment, I simply configured the data set and made no other changes. I found that it seems that the metric is not updated, and the log repeatedly prints loss as nan, as follows:

[metric][batch=0]: time/epoch: 2365 
[metric][batch=0]: metrics/train/LanguageCrossEntropy: nan 
[metric][batch=0]: metrics/train/Perplexity: nan 
[metric][batch=0]: metrics/train/ArXiv_LanguageCrossEntropy: nan 
[metric][batch=0]: metrics/train/ArXiv_count: 0 
[metric][batch=0]: metrics/train/Books_LanguageCrossEntropy: nan 
[metric][batch=0]: metrics/train/Books_count: 0 
[metric][batch=0]: metrics/train/Wikipedia_LanguageCrossEntropy: nan 
[metric][batch=0]: metrics/train/Wikipedia_count: 0 
[metric][batch=0]: time/epoch: 2366 
[metric][batch=0]: metrics/train/LanguageCrossEntropy: nan 
[metric][batch=0]: metrics/train/Perplexity: nan 
[metric][batch=0]: metrics/train/ArXiv_LanguageCrossEntropy: nan 
[metric][batch=0]: metrics/train/ArXiv_count: 0 
[metric][batch=0]: metrics/train/Books_LanguageCrossEntropy: nan 
[metric][batch=0]: metrics/train/Books_count: 0 
[metric][batch=0]: metrics/train/Wikipedia_LanguageCrossEntropy: nan 
[metric][batch=0]: metrics/train/Wikipedia_count: 0 
.... repeat

I set pdb breakpoints in metric's update function and composerllama's update_mteric, but these breakpoints were not executed.
The input data seems to be intact. I tested trainloader and train.eval and everything is normal. However, this problem inevitably occurs in train.fit.

The Setting of pruning:

# learning setup
lr=1e-4 # learning rate for the main parameters
max_duration=3200ba # 0.42B tokens
save_interval=3200ba # save in the end
t_warmup=320ba # 10% learning rate warmup 

# dynamic loading setup
dynamic=True
# set_names=[cc,github,book,stackexchange,wiki,arxiv,c4-rp] # domain names
set_names=[ArXiv,Books,Wikipedia] # domain names
# proportion=[0.67,0.045,0.045,0.02,0.045,0.025,0.15] # initial proportion of RP, make sure that the sum(proportion) = 1
proportion=[0.4,0.3,0.3] 
# doremi: update weights with exponential descent
# constant: keep the weights constant
update_type=doremi 
if [[ $to_model == 1.3b ]]; then
    # target_loss=[1.9643,0.7459,2.1393,1.6117,1.7590,1.4449,2.1251] # 1.3b predicted loss from scaling law
    target_loss=[1.4449,2.1393,1.7590]
else
    # target_loss=[1.8712,0.6883,2.0325,1.5353,1.6297,1.3560,2.0328] # 2.7b predicted loss from scaling law
    target_loss=[1.3560,2.0325,1.6297]
fi
eval_split_name=eval_merge # eval on all domains
eval_target_model=false # evaluate on the current model, not the target model, otherwise the loss will be inaccurate
eval_interval=50ba # eval every 50 batches and update the loading proportion


# pruning setup
lag_lr=1.0 # learning rate or l0_module
lagr_warmup=640ba # 20% sparsity warmup
if [[ $to_model == 1.3b ]]; then
    target_d_model=2048; target_n_heads=16; target_n_layers=24; target_intermediate_size=5504
elif [[ $to_model == 3b ]]; then
    target_d_model=2560; target_n_heads=20; target_n_layers=32; target_intermediate_size=6912
fi

composer $TRAIN_SCRIPT \
    $config_file \
    run_name=${run_name} \
    data_local=${data_local} \
    eval_loader.dataset.split=${eval_split_name} \
    global_train_batch_size=${global_train_batch_size} \
    device_train_microbatch_size=${device_train_microbatch_size} \
    device_eval_batch_size=${device_eval_batch_size} \
    max_seq_len=${max_seq_len} \
    max_duration=${max_duration} \
    eval_first=false \
    scheduler.t_warmup=${t_warmup} \
    save_folder=${save_dir} \
    loggers.wandb.init_kwargs.dir=${wandb_dir} \
    eval_interval=${eval_interval} \
    save_interval=${save_interval} \
    optimizer.lr=${lr} \
    optimizer.lag_lr=${lag_lr} \
    model.l0_module.lagrangian_warmup_steps=${lagr_warmup} \
    model.l0_module.pruning_modules='[head,intermediate,layer,hidden]' \
    model.l0_module.eval_target_model=${eval_target_model} \
    model.l0_module.target_model.d_model=${target_d_model} \
    model.l0_module.target_model.n_heads=${target_n_heads} \
    model.l0_module.target_model.n_layers=${target_n_layers} \
    model.l0_module.target_model.intermediate_size=${target_intermediate_size} \
    callbacks.data_loading.dynamic=${dynamic} \
    callbacks.data_loading.set_names=${set_names} \
    callbacks.data_loading.proportion=${proportion} \
    callbacks.data_loading.update_type=${update_type} \
    callbacks.data_loading.target_loss=${target_loss} \
    train_loader.num_workers=0 \
    train_loader.prefetch_factor=null \
    train_loader.persistent_workers=false \
    autoresume=false

Flash-attn dependency issues

You said that Flash Attention version 2 is not currently supported and may require manual modifications to the model file. but In requirement.txt, you still have flash-attn2 installed. Does this cause some incompatibility issues?

Drive dress error

The Google Drive dress is error, I can not open it, would you give me a new dress, ths

image

sample data generate name

HI,after run bash sample_all_domains.sh I can't get the dirs as you list,eg:sample1、sample2、eval_merge.my dirs is:
.
├── eval
│ ├── arxiv
│ │ ├── index.json
│ │ └── shard.00000.mds
│ ├── book
│ │ ├── index.json
│ │ └── shard.00000.mds
│ ├── c4-rp
│ │ ├── index.json
│ │ └── shard.00000.mds
│ ├── cc
│ │ ├── index.json
│ │ └── shard.00000.mds
│ ├── github
│ │ ├── index.json
│ │ └── shard.00000.mds
│ ├── stackexchange
│ │ ├── index.json
│ │ └── shard.00000.mds
│ └── wiki
│ ├── index.json
│ └── shard.00000.mds
├── for_ft
│ ├── arxiv
│ │ ├── index.json
│ │ └── shard.00000.mds
│ ├── book
│ │ ├── index.json
│ │ └── shard.00000.mds
│ ├── c4-rp
│ │ ├── index.json
│ │ └── shard.00000.mds
│ ├── cc
│ │ └── index.json
│ ├── github
│ │ ├── index.json
│ │ └── shard.00000.mds
│ ├── stackexchange
│ │ ├── index.json
│ │ └── shard.00000.mds
│ └── wiki
│ ├── index.json
│ └── shard.00000.mds
└── for_prune
├── arxiv
│ ├── index.json
│ └── shard.00000.mds
├── book
│ ├── index.json
│ └── shard.00000.mds
├── c4-rp
│ ├── index.json
│ └── shard.00000.mds
├── cc
│ ├── index.json
│ └── shard.00000.mds
├── github
│ ├── index.json
│ └── shard.00000.mds
├── stackexchange
│ ├── index.json
│ └── shard.00000.mds
└── wiki
├── index.json
└── shard.00000.mds

Question about ComposerMosaicLlama.forward

Hello guys, This is not an issue but my question. I am confused about the forward function in ComposerMosaicLlama. Why the pruning parameters (parameters which "_z") can be read from batch? I can not find which class is preparing for those. In my understanding, those pruning parameters should be all in l0_module?

 def forward(self, batch):
        input_ids = batch["input_ids"]
        key_padding_mask = batch["attention_mask"].bool() if "attention_mask" in batch else None
        pruned_steps = batch.get("pruned_steps", None)
        if pruned_steps is not None:
            pruned_steps = pruned_steps[0].item()
        zs = {key: batch[key] for key in batch if "_z" in key} # why those parameters coming from batch?
        model_output = self.model(
            input_ids=input_ids, key_padding_mask=key_padding_mask, pruned_steps=pruned_steps, **zs
        )
        return model_output

Thank you very much!

meta-llama/Llama-2-7b-hf Model Preparation failed

(rzr_llmshearing) root@dsw70428-7485c78d87-pp4rr:/mnt/workspace/workgroup/qianqin.rzr/LLM-Shearing# sh modelprepare.sh
╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/runpy.py:197 in │
│ _run_module_as_main │
│ │
│ 194 │ main_globals = sys.modules["main"].dict
│ 195 │ if alter_argv: │
│ 196 │ │ sys.argv[0] = mod_spec.origin │
│ ❱ 197 │ return _run_code(code, main_globals, None, │
│ 198 │ │ │ │ │ "main", mod_spec) │
│ 199 │
│ 200 def run_module(mod_name, init_globals=None, │
│ │
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/runpy.py:87 in │
│ _run_code │
│ │
│ 84 │ │ │ │ │ loader = loader, │
│ 85 │ │ │ │ │ package = pkg_name, │
│ 86 │ │ │ │ │ spec = mod_spec) │
│ ❱ 87 │ exec(code, run_globals) │
│ 88 │ return run_globals │
│ 89 │
│ 90 def _run_module_code(code, init_globals=None, │
│ │
│ /mnt/workspace/workgroup/qianqin.rzr/LLM-Shearing/llmshearing/utils/composer_to_hf.py:107 in │
│ │
│ │
│ 104 if name == "main": │
│ 105 │ composer_model_path, output_path, other_args = sys.argv[1], sys.argv[2], sys.argv[3: │
│ 106 │ cli_cfg = om.from_cli(other_args) │
│ ❱ 107 │ save_composer_to_hf(composer_model_path, output_path, cli_cfg) │
│ 108 │
│ │
│ /mnt/workspace/workgroup/qianqin.rzr/LLM-Shearing/llmshearing/utils/composer_to_hf.py:89 in │
│ save_composer_to_hf │
│ │
│ 86 def save_composer_to_hf(composer_model_path, output_path=None, model_config:om = None): │
│ 87 │ """ convert composer ckpt's weights to huggingface """ │
│ 88 │ │
│ ❱ 89 │ weights = torch.load(composer_model_path)["state"]["model"] │
│ 90 │ num_layers = get_layer_num_from_weights(weights) │
│ 91 │ keymap = get_key_map_from_composer_to_hf(num_layers) │
│ 92 │ hf_weights = {keymap[key]: weights[key] for key in weights if "rotary" not in key} │
│ │
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/site-packages/t │
│ orch/serialization.py:791 in load │
│ │
│ 788 │ if 'encoding' not in pickle_load_args.keys(): │
│ 789 │ │ pickle_load_args['encoding'] = 'utf-8' │
│ 790 │ │
│ ❱ 791 │ with _open_file_like(f, 'rb') as opened_file: │
│ 792 │ │ if _is_zipfile(opened_file): │
│ 793 │ │ │ # The zipfile reader is going to advance the current file position. │
│ 794 │ │ │ # If we want to actually tail call to torch.jit.load, we need to │
│ │
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/site-packages/t │
│ orch/serialization.py:271 in _open_file_like │
│ │
│ 268 │
│ 269 def _open_file_like(name_or_buffer, mode): │
│ 270 │ if _is_path(name_or_buffer): │
│ ❱ 271 │ │ return _open_file(name_or_buffer, mode) │
│ 272 │ else: │
│ 273 │ │ if 'w' in mode: │
│ 274 │ │ │ return _open_buffer_writer(name_or_buffer) │
│ │
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/site-packages/t │
│ orch/serialization.py:252 in init
│ │
│ 249 │
│ 250 class _open_file(_opener): │
│ 251 │ def init(self, name, mode): │
│ ❱ 252 │ │ super().init(open(name, mode)) │
│ 253 │ │
│ 254 │ def exit(self, *args): │
│ 255 │ │ self.file_like.close() │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
IsADirectoryError: [Errno 21] Is a directory: '/mnt/workspace/workgroup/qianqin.rzr/model/llama-2-7b-hf'

these are my files in (rzr_llmshearing) root@dsw70428-7485c78d87-pp4rr:/mnt/workspace/workgroup/qianqin.rzr/LLM-Shearing# ls ../model/llama-2-7b-hf/
config.json LICENSE.txt model-00002-of-00002.safetensors pytorch_model-00001-of-00002.bin pytorch_model.bin.index.json Responsible-Use-Guide.pdf tokenizer_config.json tokenizer.model
generation_config.json model-00001-of-00002.safetensors model.safetensors.index.json pytorch_model-00002-of-00002.bin README.md special_tokens_map.json tokenizer.json USE_POLICY.md

Please what can I do to fix this error?

TypeError: load_data() missing 1 required positional argument: 'tokenizer_name'

Hello I was following the command in data/Readme.md

python3 -m llmshearing.data.merge_data
--input_dir $INPUT_DIR
--output_dir $OUTPUT_DIR
--output_split eval_merge
--split_names domain1 domain2

However I found two issues,
one is at line 31, you guys did not import sys, and the sys.argv[2:] should be change to sys.argv[1:], otherwise the input dir will always be none.
another is at line 50, It seems there should be a default value or guide for 'tokneizer_name'? Since I got TypeError: load_data() missing 1 required positional argument: 'tokenizer_name'

Thank you very much in advance

wiki proportion finally dominates at the end of the pruning stage

pruning_wiki_dynamic

the script of pruning as follow:

# Specify $PROJ_DIR in scripts/launch.sh and scripts/srun_launch.sh if using slurm

test=True

from_model=7b # source model size
to_model=3b # target model size
config_file=${PROJ_DIR}/llmshearing/configs/llama2/${from_model}.yaml
path=$MODEL_PATH/llama-2-7b-composer/state_dict.pt

# data setup
data_local=${DATA_DIR}

# basic setup
max_seq_len=4096
device_train_microbatch_size=4
global_train_batch_size=32
device_eval_batch_size=8

# learning setup
lr=1e-4 # learning rate for the main parameters
# max_duration=3200ba # 0.42B tokens
# save_interval=3200ba # save in the end
# t_warmup=320ba # 10% learning rate warmup 

max_duration=3000ba # 0.39B tokens
save_interval=3000ba # save in the end
t_warmup=300ba # 10% learning rate warmup 

# dynamic loading setup
dynamic=True
set_names=[cc,github,book,stackexchange,wiki,arxiv,c4-rp] # domain names
proportion=[0.67,0.045,0.045,0.02,0.045,0.025,0.15] # initial proportion of RP, make sure that the sum(proportion) = 1
# doremi: update weights with exponential descent
# constant: keep the weights constant
update_type=doremi 
if [[ $to_model == 1.3b ]]; then
    target_loss=[1.9643,0.7459,2.1393,1.6117,1.7590,1.4449,2.1251] # 1.3b predicted loss from scaling law
else
    target_loss=[1.8712,0.6883,2.0325,1.5353,1.6297,1.3560,2.0328] # 2.7b predicted loss from scaling law
fi
eval_split_name=../eval/eval_merge # eval on all domains
eval_target_model=false # evaluate on the current model, not the target model, otherwise the loss will be inaccurate
eval_interval=50ba # eval every 50 batches and update the loading proportion


# pruning setup
lag_lr=1.0 # learning rate or l0_module
lagr_warmup=640ba # 20% sparsity warmup
if [[ $to_model == 1.3b ]]; then
    target_d_model=2048; target_n_heads=16; target_n_layers=24; target_intermediate_size=5504
elif [[ $to_model == 3b ]]; then
    target_d_model=2560; target_n_heads=20; target_n_layers=32; target_intermediate_size=6912
fi

# save directroy
run_name=llama2_${from_model}_pruning_scaling_${update_type}_to${to_model}_sl${max_seq_len}
save_dir=${OUTPUT_DIR}/${run_name}
wandb_dir=${save_dir} # save locally

if [[ $test == True ]]; then t=00-01:00:00; else t=01-00:00:00; fi

# Run in bash, it will automatically use resources available in the current environment
# composer $TRAIN_SCRIPT \

# Run with slurm    
# sbatch -p cli \
#     --job-name ${run_name} \
#     --nodes=4 \
#     --gpus-per-node=2 \
#     --mem=512gb \
#     --cpus-per-task=8 \
#     --time $t \
composer $TRAIN_SCRIPT \
    $config_file \
    run_name=${run_name} \
    data_local=${data_local} \
    eval_loader.dataset.split=${eval_split_name} \
    global_train_batch_size=${global_train_batch_size} \
    device_train_microbatch_size=${device_train_microbatch_size} \
    device_eval_batch_size=${device_eval_batch_size} \
    max_seq_len=${max_seq_len} \
    max_duration=${max_duration} \
    eval_first=false \
    scheduler.t_warmup=${t_warmup} \
    save_folder=${save_dir} \
    loggers.wandb.init_kwargs.dir=${wandb_dir} \
    eval_interval=${eval_interval} \
    save_interval=${save_interval} \
    optimizer.lr=${lr} \
    optimizer.lag_lr=${lag_lr} \
    model.path=${path} \
    model.l0_module.lagrangian_warmup_steps=${lagr_warmup} \
    model.l0_module.pruning_modules='[head,intermediate,layer,hidden]' \
    model.l0_module.eval_target_model=${eval_target_model} \
    model.l0_module.target_model.d_model=${target_d_model} \
    model.l0_module.target_model.n_heads=${target_n_heads} \
    model.l0_module.target_model.n_layers=${target_n_layers} \
    model.l0_module.target_model.intermediate_size=${target_intermediate_size} \
    callbacks.data_loading.dynamic=${dynamic} \
    callbacks.data_loading.set_names=${set_names} \
    callbacks.data_loading.proportion=${proportion} \
    callbacks.data_loading.update_type=${update_type} \
    callbacks.data_loading.target_loss=${target_loss} \
    train_loader.num_workers=0 \
    train_loader.prefetch_factor=null \
    train_loader.persistent_workers=false \
    autoresume=true

Use without flash-attn?

Can I use this without Flash Attention? I really want to do this on my M1 MacBook or AMD GPU. Thanks!

Release sheared model without re-training?

Hello, will you release sheared models without re-training? Currently, there are only some graphs showing the averaged ACC of each training checkpoint. I think it would be instructive if we can evaulate the un-trained model!

NotImplementedError: offload_to_cpu=True and NO_SHARD is not supported yet

This problem occurs when the pruning program is finished and saved.
This issue results in no way to save checkpoints normally

User
log(event, f'Running callback {type(cb).__na │
│ ❱ 468 │   │   │   │   cb.run_event(event, self.state, self.logger)             │
│   469 │                                                                        │
│   470 │   def _run_loggers(self, event: Union[Event, str]):                    │
│   471 │   │   loggers = [callback for callback in self.state.callbacks if isin │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/composer/core/call │
│ back.py:96 in run_event                                                        │
│                                                                                │
│    93 │   │   │   logger (Logger): The logger.                                 │
│    94 │   │   """                                                              │
│    95 │   │   event_cb = getattr(self, event.value)                            │
│ ❱  96 │   │   return event_cb(state, logger)                                   │
│    97 │                                                                        │
│    98 │   def init(self, state: State, logger: Logger) -> None:                │
│    99 │   │   """Called on the :attr:`.Event.INIT` event.                      │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/composer/callbacks │
│ /checkpoint_saver.py:294 in batch_checkpoint                                   │
│                                                                                │
│   291 │   def batch_checkpoint(self, state: State, logger: Logger):            │
│   292 │   │   assert callable(self.save_interval)                              │
│   293 │   │   if self.save_interval(state, Event.BATCH_CHECKPOINT) and self.la │
│ ❱ 294 │   │   │   self._save_checkpoint(                                       │
│   295 │   │   │   │   state,                                                   │
│   296 │   │   │   │   logger,                                                  │
│   297 │   │   │   )                                                            │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/composer/callbacks │
│ /checkpoint_saver.py:332 in _save_checkpoint                                   │
│                                                                                │
│   329 │   │   # save the checkpoint to the filename                            │
│   330 │   │   filename_with_placeholders = self.filename.format(state, is_deep │
│   331 │   │                                                                    │
│ ❱ 332 │   │   saved_path = checkpoint.save_checkpoint(                         │
│   333 │   │   │   state=state,                                                 │
│   334 │   │   │   filename=filename_with_placeholders,                         │
│   335 │   │   │   weights_only=self.weights_only,                              │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/composer/utils/che │
│ ckpoint.py:761 in save_checkpoint                                              │
│                                                                                │
│   758 │   │   }                                                                │
│   759 │   else:                                                                │
│   760 │   │   state_dict = {                                                   │
│ ❱ 761 │   │   │   'state': state.state_dict(),                                 │
│   762 │   │   │   'rng': reproducibility.get_rng_state(),                      │
│   763 │   │   }                                                                │
│   764                                                                          │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/composer/core/stat │
│ e.py:891 in state_dict                                                         │
│                                                                                │
│    888 │   │   │   if attribute_name == 'dataset_state':                       │
│    889 │   │   │   │   serialized_value = self._dataset_state_dict()           │
│    890 │   │   │   elif attribute_name == 'model':                             │
│ ❱  891 │   │   │   │   serialized_value = self.get_model_state_dict()          │
│    892 │   │   │   elif attribute_name == 'optimizers':                        │
│    893 │   │   │   │   optimizer = ensure_tuple(attribute_value)[              │
│    894 │   │   │   │   │   0]  # Let's stop pretending. We don't support more  │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/composer/core/stat │
│ e.py:868 in get_model_state_dict                                               │
│                                                                                │
│    865 │   │   """                                                             │
│    866 │   │   if self.fsdp_enabled and self.fsdp_state_dict_type is not None: │
│    867 │   │   │   with fsdp_state_dict_type_context(self.model, state_dict_ty │
│ ❱  868 │   │   │   │   model_state_dict = self.model.state_dict()              │
│    869 │   │   else:                                                           │
│    870 │   │   │   model_state_dict = self.model.state_dict()                  │
│    871                                                                         │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/torch/nn/modules/m │
│ odule.py:1818 in state_dict                                                    │
│                                                                                │
│   1815 │   │   self._save_to_state_dict(destination, prefix, keep_vars)        │
│   1816 │   │   for name, module in self._modules.items():                      │
│   1817 │   │   │   if module is not None:                                      │
│ ❱ 1818 │   │   │   │   module.state_dict(destination=destination, prefix=prefi │
│   1819 │   │   for hook in self._state_dict_hooks.values():                    │
│   1820 │   │   │   hook_result = hook(self, destination, prefix, local_metadat │
│   1821 │   │   │   if hook_result is not None:                                 │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/torch/nn/modules/m │
│ odule.py:1815 in state_dict                                                    │
│                                                                                │
│   1812 │   │   if hasattr(destination, "_metadata"):                           │
│   1813 │   │   │   destination._metadata[prefix[:-1]] = local_metadata         │
│   1814 │   │                                                                   │
│ ❱ 1815 │   │   self._save_to_state_dict(destination, prefix, keep_vars)        │
│   1816 │   │   for name, module in self._modules.items():                      │
│   1817 │   │   │   if module is not None:                                      │
│   1818 │   │   │   │   module.state_dict(destination=destination, prefix=prefi │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/torch/nn/modules/m │
│ odule.py:1722 in _save_to_state_dict                                           │
│                                                                                │
│   1719 │   │   │   │   module                                                  │
│   1720 │   │   """                                                             │
│   1721 │   │   for hook in self._state_dict_pre_hooks.values():                │
│ ❱ 1722 │   │   │   hook(self, prefix, keep_vars)                               │
│   1723 │   │                                                                   │
│   1724 │   │   for name, param in self._parameters.items():                    │
│   1725 │   │   │   if param is not None:                                       │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/torch/utils/_conte │
│ xtlib.py:115 in decorate_context                                               │
│                                                                                │
│   112 │   @functools.wraps(func)                                               │
│   113 │   def decorate_context(*args, **kwargs):                               │
│   114 │   │   with ctx_factory():                                              │
│ ❱ 115 │   │   │   return func(*args, **kwargs)                                 │
│   116 │                                                                        │
│   117 │   return decorate_context                                              │
│   118                                                                          │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/torch/distributed/ │
│ fsdp/_state_dict_utils.py:669 in _pre_state_dict_hook                          │
│                                                                                │
│   666 │   │   StateDictType.LOCAL_STATE_DICT: _local_pre_state_dict_hook,      │
│   667 │   │   StateDictType.SHARDED_STATE_DICT: _sharded_pre_state_dict_hook,  │
│   668 │   }                                                                    │
│ ❱ 669 │   _pre_state_dict_hook_fn[fsdp_state._state_dict_type](                │
│   670 │   │   fsdp_state,                                                      │
│   671 │   │   module,                                                          │
│   672 │   │   *args,                                                           │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/torch/distributed/ │
│ fsdp/_state_dict_utils.py:271 in _full_pre_state_dict_hook                     │
│                                                                                │
│   268 │   in ``nn.Module``.                                                    │
│   269 │   """                                                                  │
│   270 │   _common_pre_state_dict_hook(module, fsdp_state)                      │
│ ❱ 271 │   _common_unshard_pre_state_dict_hook(                                 │
│   272 │   │   module,                                                          │
│   273 │   │   fsdp_state,                                                      │
│   274 │   │   offload_to_cpu=fsdp_state._state_dict_config.offload_to_cpu,     │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/torch/distributed/ │
│ fsdp/_state_dict_utils.py:143 in _common_unshard_pre_state_dict_hook           │
│                                                                                │
│   140 │   Performs the pre-state_dict tasks shared by all state_dict types tha │
│   141 │   ``_unshard_fsdp_state_params()``. FULL_STATE_DICT and SHARDED_STATE_ │
│   142 │   """                                                                  │
│ ❱ 143 │   _enter_unshard_params_ctx(                                           │
│   144 │   │   module,                                                          │
│   145 │   │   fsdp_state,                                                      │
│   146 │   │   writeback=False,                                                 │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/torch/distributed/ │
│ fsdp/_state_dict_utils.py:109 in _enter_unshard_params_ctx                     │
│                                                                                │
│   106 │   │   offload_to_cpu=offload_to_cpu,                                   │
│   107 │   │   with_grads=with_grads,                                           │
│   108 │   )                                                                    │
│ ❱ 109 │   fsdp_state._unshard_params_ctx[module].__enter__()                   │
│   110                                                                          │
│   111                                                                          │
│   112 @no_type_check                                                           │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/contextlib.py:135 in __enter__   │
│                                                                                │
│   132 │   │   # they are only needed for recreation, which is not possible any │
│   133 │   │   del self.args, self.kwds, self.func                              │
│   134 │   │   try:                                                             │
│ ❱ 135 │   │   │   return next(self.gen)                                        │
│   136 │   │   except StopIteration:                                            │
│   137 │   │   │   raise RuntimeError("generator didn't yield") from None       │
│   138                                                                          │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/torch/distributed/ │
│ fsdp/_unshard_param_utils.py:171 in _unshard_fsdp_state_params                 │
│                                                                                │
│   168 │   This unshards the parameters for a single FSDP state ``state`` that  │
│   169 │   corresponds to ``module``.                                           │
│   170 │   """                                                                  │
│ ❱ 171 │   _validate_unshard_params_args(                                       │
│   172 │   │   state, writeback, rank0_only, offload_to_cpu, with_grads         │
│   173 │   )                                                                    │
│   174 │   torch.cuda.synchronize()                                             │
│                                                                                │
│ /root/miniconda3/envs/shearing/lib/python3.10/site-packages/torch/distributed/ │
│ fsdp/_unshard_param_utils.py:140 in _validate_unshard_params_args              │
│                                                                                │
│   137 │   if offload_to_cpu and any(                                           │
│   138 │   │   not handle.uses_sharded_strategy for handle in state._handles    │
│   139 │   ):                                                                   │
│ ❱ 140 │   │   raise NotImplementedError(                                       │
│   141 │   │   │   "offload_to_cpu=True and NO_SHARD is not supported yet"      │
│   142 │   │   )                                                                │
│   143 │   if writeback and rank0_only:                                         │
╰────────────────────────────────────────────────────────────────────────────────╯
NotImplementedError: offload_to_cpu=True and NO_SHARD is not supported yet

There are related discussions about this problem on the Internet
huggingface/transformers#24874
huggingface/transformers#24874
, and it seems to have been fixed in the transformer library. Are you considering updating the version or adopting other fixes?

Finetuning using LoRA

Is it possible to finetune one of your checkpoints using LoRA on a dataset of our choice? If yes, how might we go about doing it?

Docker Request

Hi! Would anyone be willing to share a docker image where they can run the code successfully? I've tried installing in different environments but keep getting errors from mosaic composer.

Can Sheared-LLaMA beat OpenLLaMA v2 significantly with the same amount of compute ?

image

We can see from the picture that Sheared-LLaMA is on par with OpenLLaMA v2 with 1/32 compute, which is quite impressive. But from my experience, knowledge distillation and pruning is very data efficient indeed, but can not surpass pre-training from scatch significantly due to the size limit of the target model. I wonder if you train Sheared-LLaMA-2.7B longer, is it possible to surpass Open-LLaMA-3B-v2 by 4~5% on average downstream performance ?

License is missing

Dear authors,
Please add an Apache 2.0 or MIT license so that it is an open-source project. As it stands, users are not allowed to modify or distribute your code because there is no license available.

Train metrics/train/github_LanguageCrossEntropy: nan

During training stage of prunning, Train metrics/train/github_LanguageCrossEntropy is nan, is that normal?

[batch=189/3200]:
Train time/batch: 188
Train time/sample: 6016
Train time/batch_in_epoch: 188
Train time/sample_in_epoch: 6016
Train time/token: 24641536
Train time/token_in_epoch: 24641536
Train metrics/train/cc_weight: 0.6176
Train metrics/train/github_weight: 0.0408
Train metrics/train/book_weight: 0.0441
Train metrics/train/stackexchange_weight: 0.0168
Train metrics/train/wiki_weight: 0.0861
Train metrics/train/arxiv_weight: 0.0189
Train metrics/train/c4-rp_weight: 0.1757
Train memory/current_allocated_mem: 14.6140
Train memory/current_active_mem: 14.6140
Train memory/current_inactive_mem: 1.9258
Train memory/current_reserved_mem: 43.4220
Train memory/peak_allocated_mem: 28.0710
Train memory/peak_active_mem: 28.0710
Train memory/peak_inactive_mem: 11.7290
Train memory/peak_reserved_mem: 43.4220
Train memory/alloc_retries: 0
Train metrics/train/expected_head_sparsity: 0.0132
Train metrics/train/target_head_sparsity: 0.1102
Train metrics/train/expected_intermediate_sparsity: 0.0057
Train metrics/train/target_intermediate_sparsity: 0.1093
Train metrics/train/expected_layer_sparsity: 0.0039
Train metrics/train/target_layer_sparsity: 0.0000
Train metrics/train/expected_hidden_sparsity: 0.1882
Train metrics/train/target_hidden_sparsity: 0.1102
Train metrics/train/expected_sparsity: 0.1981
Train metrics/train/target_sparsity: 0.1786
Train trainer/device_train_microbatch_size: 4
Train loss/train/total: 3.9353
Train loss/train/ce_loss: 2.3241
Train loss/train/lag_loss: 1.6112
Train metrics/train/LanguageCrossEntropy: 2.3241
Train metrics/train/Perplexity: 10.2176
Train metrics/train/cc_LanguageCrossEntropy: 2.2752
Train metrics/train/cc_count: 3991
Train metrics/train/github_LanguageCrossEntropy: nan
Train metrics/train/github_count: 276
Train metrics/train/book_LanguageCrossEntropy: nan

cannot reshape array of size 4 into shape (1,newaxis,8)

╭─────────────────────────────── Traceback (most recent call last) ────────────────────────────────╮
│ /mnt/workspace/workgroup/qianqin.rzr/LLM-Shearing/llmshearing/train.py:317 in │
│ │
│ 314 │ os.makedirs(save_dir, exist_ok=True) │
│ 315 │ torch.save(cfg, save_dir + "/config.pt") │
│ 316 │ │
│ ❱ 317 │ main(cfg) │
│ 318 │
│ 319 │
│ │
│ /mnt/workspace/workgroup/qianqin.rzr/LLM-Shearing/llmshearing/train.py:301 in main │
│ │
│ 298 │ │ trainer.eval() │
│ 299 │ │
│ 300 │ print('Starting training...') │
│ ❱ 301 │ trainer.fit() │
│ 302 │ │
│ 303 │ print('Done.') │
│ 304 │
│ │
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/site-packages/c │
│ omposer/trainer/trainer.py:1876 in fit │
│ │
│ 1873 │ │ │ self.state.scaler = ClosureGradScaler() if self._use_closures() else GradSca │
│ 1874 │ │ │
│ 1875 │ │ self.first_batch_complete = False │
│ ❱ 1876 │ │ self._train_loop() │
│ 1877 │ │
│ 1878 │ def close(self): │
│ 1879 │ │ """Shutdown the trainer. │
│ │
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/site-packages/c │
│ omposer/trainer/trainer.py:2018 in _train_loop │
│ │
│ 2015 │ │ │ │ if isinstance(dataloader, DataLoader) and isinstance(dataloader.sampler, │
│ 2016 │ │ │ │ │ dataloader.sampler.set_epoch(int(self.state.timestamp.epoch)) │
│ 2017 │ │ │ │ │
│ ❱ 2018 │ │ │ │ for batch_idx, self.state.batch in enumerate(self._iter_dataloader(Train │
│ 2019 │ │ │ │ │ # Spin dataloader forward unless dataloader handles internally with │
│ 2020 │ │ │ │ │ if self.spin_dataloaders and 'train' not in self.state.dataset_resum │
│ 2021 │ │ │ │ │ │ │ self.state.timestamp.batch_in_epoch): │
│ │
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/site-packages/c │
│ omposer/trainer/trainer.py:3024 in _iter_dataloader │
│ │
│ 3021 │ │ │ │ # [BEFORE/AFTER]_DATALOADER only runs while training │
│ 3022 │ │ │ │ if trainer_mode == TrainerMode.TRAIN: │
│ 3023 │ │ │ │ │ self.engine.run_event(Event.BEFORE_DATALOADER) │
│ ❱ 3024 │ │ │ │ batch = next(dataloader_iter) │
│ 3025 │ │ │ except StopIteration: │
│ 3026 │ │ │ │ # [BEFORE/AFTER]_DATALOADER only runs while training │
│ 3027 │ │ │ │ if trainer_mode == TrainerMode.TRAIN: │
│ │
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/site-packages/t │
│ orch/utils/data/dataloader.py:633 in next
│ │
│ 630 │ │ │ if self._sampler_iter is None: │
│ 631 │ │ │ │ # TODO(pytorch/pytorch#76750) │
│ 632 │ │ │ │ self._reset() # type: ignore[call-arg] │
│ ❱ 633 │ │ │ data = self._next_data() │
│ 634 │ │ │ self._num_yielded += 1 │
│ 635 │ │ │ if self._dataset_kind == _DatasetKind.Iterable and \ │
│ 636 │ │ │ │ │ self._IterableDataset_len_called is not None and \ │
│ │
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/site-packages/t │
│ orch/utils/data/dataloader.py:677 in _next_data │
│ │
│ 674 │ │
│ 675 │ def _next_data(self): │
│ 676 │ │ index = self._next_index() # may raise StopIteration │
│ ❱ 677 │ │ data = self._dataset_fetcher.fetch(index) # may raise StopIteration │
│ 678 │ │ if self._pin_memory: │
│ 679 │ │ │ data = _utils.pin_memory.pin_memory(data, self._pin_memory_device) │
│ 680 │ │ return data │
│ │
│ /mnt/workspace/workgroup/qianli.myf/anaconda3/envs/rzr_llmshearing/lib/python3.9/site-packages/t │
│ orch/utils/data/_utils/fetch.py:32 in fetch │
│ │
│ 29 │ │ │ data = [] │
│ 30 │ │ │ for _ in possibly_batched_index: │
│ 31 │ │ │ │ try: │
│ ❱ 32 │ │ │ │ │ data.append(next(self.dataset_iter)) │
│ 33 │ │ │ │ except StopIteration: │
│ 34 │ │ │ │ │ self.ended = True │
│ 35 │ │ │ │ │ break │
│ │
│ /mnt/workspace/workgroup/qianqin.rzr/LLM-Shearing/llmshearing/datasets/streaming_dataset.py:384 │
│ in iter
│ │
│ 381 │ │ epoch, used_sample_ids = self._resume_incr_epoch(world) │
│ 382 │ │ │
│ 383 │ │ # Get this worker's partition of samples to process. │
│ ❱ 384 │ │ sample_ids_per_stream = self._get_work(world, epoch, used_sample_ids) │
│ 385 │ │ │
│ 386 │ │ # Currently only supports dynamically loading data from each domain for once. │
│ 387 │ │ # Issues could occur if one domain of data is used up. │
│ │
│ /mnt/workspace/workgroup/qianqin.rzr/LLM-Shearing/llmshearing/datasets/streaming_dataset.py:338 │
│ in _get_work │
│ │
│ 335 │ │ │
│ 336 │ │ # Do expensive work that may use a lot of cores/memory just once, in the local l │
│ 337 │ │ if world.is_local_leader: │
│ ❱ 338 │ │ │ sample_ids_per_stream = generate_work(self, world, epoch, used_domain_ids) │
│ 339 │ │ │ shape_shms, data_shms = self._share_work(sample_ids_per_stream) │
│ 340 │ │ │ self._shared_barrier(world.workers_per_node) │
│ 341 │ │ else: │
│ │
│ /mnt/workspace/workgroup/qianqin.rzr/LLM-Shearing/llmshearing/datasets/streaming_dataset.py:78 │
│ in generate_work │
│ │
│ 75 │ │ │ del reverse_mapping │
│ 76 │ │ │
│ 77 │ │ # check │
│ ❱ 78 │ │ stream_partition = get_partitions_orig(samples_in_stream, │
│ 79 │ │ │ │ │ │ │ │ │ │ │ dataset.num_canonical_nodes, world.num_no │
│ 80 │ │ │ │ │ │ │ │ │ │ │ world.ranks_per_node, world.workers_per_r │
│ 81 │ │ │ │ │ │ │ │ │ │ │ 0, used_stream_ids) │
│ │
│ /mnt/workspace/workgroup/qianqin.rzr/LLM-Shearing/llmshearing/datasets/partition.py:116 in │
│ get_partitions_orig │
│ │
│ 113 │ │ underflow = ranks_per_node - overflow │
│ 114 │ │ last = ids[:, -ranks_per_node - underflow + 1:-ranks_per_node + 1] │
│ 115 │ │ ids = np.concatenate([ids, last], 1) │
│ ❱ 116 │ ids = ids.reshape(num_physical_nodes, -1, ranks_per_node) │
│ 117 │ │
│ 118 │ # Pad with -1 adequately for reshaping across workers. │
│ 119 │ # │
╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
ValueError: cannot reshape array of size 4 into shape (1,newaxis,8)

anyone meet this problem,ask for help

Small typo on Table 2

image

Pythia-1.4B seems to be better than OPT-1.3B and Sheared-LLaMA-1.3B on LogiQA. :)

KeyError: 'state'

Hello,
Thank you for your study about pruning.

When I converted a pruned model to HuggingFace model, I have an error about key.

MODEL_PATH='models/Llama-2-7b-composer/pruned-state_dict.pt'
OUTPUT_PATH='models/Llama-2-7b-composer/hf-state_dict'
MODEL_CLASS='LlamaForCausalLM'
HIDDEN_SIZE=2048
NUM_ATTENTION_HEADS=16
NUM_HIDDEN_LAYERS=24
INTERMEDIATE_SIZE=5504
MODEL_NAME='Sheared-Llama-1.3B'

!python3 -m llmshearing.utils.composer_to_hf $MODEL_PATH $OUTPUT_PATH \
model_class=$MODEL_CLASS \
hidden_size=$HIDDEN_SIZE \
num_attention_heads=$NUM_ATTENTION_HEADS \
num_hidden_layers=$NUM_HIDDEN_LAYERS \
intermediate_size=$INTERMEDIATE_SIZE \
num_key_value_heads=$NUM_ATTENTION_HEADS \
_name_or_path=$MODEL_NAME

│ /tf/LLM-Shearing/llmshearing/utils/composer_to_hf.py:108 in <module>         │
│                                                                              │
│   105 if __name__ == "__main__":                                             │
│   106 │   composer_model_path, output_path, other_args = sys.argv[1], sys.ar │
│   107 │   cli_cfg = om.from_cli(other_args)                                  │
│ ❱ 108 │   save_composer_to_hf(composer_model_path, output_path, cli_cfg)     │
│   109 │   #save_hf_to_composer(composer_model_path, output_path)             │
│   110                                                                        │
│                                                                              │
│ /tf/LLM-Shearing/llmshearing/utils/composer_to_hf.py:90 in                   │
│ save_composer_to_hf                                                          │
│                                                                              │
│    87 def save_composer_to_hf(composer_model_path, output_path=None, model_c │
│    88 │   """ convert composer ckpt's weights to huggingface """             │
│    89 │                                                                      │
│ ❱  90 │   weights = torch.load(composer_model_path)["state"]["model"]        │
│    91 │   num_layers = get_layer_num_from_weights(weights)                   │
│    92 │   keymap = get_key_map_from_composer_to_hf(num_layers)               │
│    93 │   hf_weights = {keymap[key]: weights[key] for key in weights if "rot │
╰──────────────────────────────────────────────────────────────────────────────╯
KeyError: 'state'

Please what can I do to fix this error?

Thank you.

Repeated assignment in l0_module.py

In https://github.com/princeton-nlp/LLM-Shearing/blob/main/llmshearing/models/l0_module.py

def param_init_fn(self, module):
        """ Initialize the parameters for masking variables. """
        mean = math.log(1 - self.droprate_init) - math.log(self.droprate_init)
        mean = 5
        if isinstance(module, nn.Parameter):
            module.data.normal_(mean, 1e-2)
        else:
            for tensor in module.parameters():
                tensor.data.normal_(mean, 1e-2)
 

mean = math.log(1 - self.droprate_init) - math.log(self.droprate_init)
mean = 5

Repeated assignment, which may not be expected behavior
For what reason should this parameter be assigned to 5?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.