mouadtarif commited on
Commit
bc310f5
·
verified ·
1 Parent(s): 1deb6e5

Upload 2 files

Browse files
Files changed (2) hide show
  1. hybridize_models.py +54 -0
  2. load_and_test_hybrid.py +93 -0
hybridize_models.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from safetensors import safe_open
3
+ from safetensors.torch import save_file
4
+ import gc
5
+
6
+ # File paths
7
+ model_a_path = "/path/to/model.safetensors"
8
+ model_b_path = "/path/to/model1.safetensors"
9
+ output_path = "/path/to/hybrid_model.safetensors"
10
+
11
+ print("Starting hybridization of two Safetensors models (Max RAM: 4GB)")
12
+ print("=" * 60)
13
+
14
+ final_weights = {}
15
+
16
+ # Stage 1: Load first model
17
+ print("Loading first model...")
18
+ with safe_open(model_a_path, framework="pt", device="cpu") as f:
19
+ total_keys = len(f.keys())
20
+ for i, key in enumerate(f.keys()):
21
+ tensor = f.get_tensor(key).half()
22
+ final_weights[key] = tensor
23
+ if (i + 1) % 50 == 0:
24
+ print(f" Loaded {i+1}/{total_keys} keys")
25
+ gc.collect()
26
+
27
+ print(f" Loaded {len(final_weights)} keys from first model")
28
+ print("=" * 60)
29
+
30
+ # Stage 2: Load second model and add as donor
31
+ print("Loading second model...")
32
+ count_b = 0
33
+ with safe_open(model_b_path, framework="pt", device="cpu") as f:
34
+ for key in f.keys():
35
+ new_key = f"donor.{key}"
36
+ tensor = f.get_tensor(key).half()
37
+ final_weights[new_key] = tensor
38
+ count_b += 1
39
+ if count_b % 50 == 0:
40
+ print(f" Loaded {count_b} keys from second model")
41
+ gc.collect()
42
+
43
+ print(f" Loaded {count_b} keys from second model")
44
+ print("=" * 60)
45
+
46
+ # Stage 3: Save hybrid model
47
+ print(f"Saving hybrid model...")
48
+ save_file(final_weights, output_path)
49
+
50
+ print("=" * 60)
51
+ print(f"Hybridization completed successfully!")
52
+ print(f" Total tensors: {len(final_weights)}")
53
+ print(f" Saved to: {output_path}")
54
+ print("=" * 60)
load_and_test_hybrid.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # can change the model paths and test inputs as needed to test the hybrid model after loading it. This script assumes that the merged weights were created correctly and that the base model's config is compatible with the merged weights. Adjust the input texts for testing based on the expected capabilities of the hybrid model.
2
+ import torch
3
+ from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer
4
+ from safetensors.torch import load_file
5
+ import os
6
+
7
+ # ============================================================
8
+ # 1. Configuration
9
+ # ============================================================
10
+ base_model_name = "user/model1" #huggingface model name for the base model (English)
11
+ second_model_name = "user/model2" #huggingface model name for the second model (Japanese)
12
+ merged_weights_path = "hybrid_model.safetensors"
13
+ output_dir = "./my_hybrid_model"
14
+
15
+ # ============================================================
16
+ # 2. Create empty model from base model config
17
+ # ============================================================
18
+ print(f"Creating empty model from config of: {base_model_name}")
19
+ config = AutoConfig.from_pretrained(base_model_name)
20
+ model = AutoModelForCausalLM.from_config(config)
21
+
22
+ # ============================================================
23
+ # 3. Load merged weights
24
+ # ============================================================
25
+ print(f"Loading merged weights from: {merged_weights_path}")
26
+ state_dict = load_file(merged_weights_path)
27
+
28
+ # ============================================================
29
+ # 4. Load state dict into empty model (strict=False)
30
+ # ============================================================
31
+ print("Loading state dict into the model (strict=False)...")
32
+ missing, unexpected = model.load_state_dict(state_dict, strict=False)
33
+ print(f" Missing keys (from base model): {len(missing)}")
34
+ print(f" Unexpected keys (from donor model): {len(unexpected)}")
35
+
36
+ # ============================================================
37
+ # 5. Save the hybrid model
38
+ # ============================================================
39
+ print(f"Saving the hybrid model to: {output_dir}")
40
+ model.save_pretrained(output_dir)
41
+
42
+ # ============================================================
43
+ # 6. Save tokenizer from base model
44
+ # ============================================================
45
+ print(f"Saving tokenizer from: {base_model_name}")
46
+ tokenizer = AutoTokenizer.from_pretrained(base_model_name)
47
+ tokenizer.save_pretrained(output_dir)
48
+
49
+ print(f"Hybrid model saved successfully to: {output_dir}")
50
+ print("=" * 60)
51
+
52
+ # ============================================================
53
+ # 7. Load and test the hybrid model
54
+ # ============================================================
55
+ print("Loading the hybrid model back for testing...")
56
+ loaded_model = AutoModelForCausalLM.from_pretrained(output_dir)
57
+ loaded_tokenizer = AutoTokenizer.from_pretrained(output_dir)
58
+
59
+ # Test 1: English generation (base model language)
60
+ input_text_en = "def hello_world():"
61
+ inputs_en = loaded_tokenizer(input_text_en, return_tensors="pt")
62
+ outputs_en = loaded_model.generate(**inputs_en, max_new_tokens=20)
63
+ generated_text_en = loaded_tokenizer.decode(outputs_en[0], skip_special_tokens=True)
64
+
65
+ print("\n" + "=" * 60)
66
+ print("Test 1 - English generation:")
67
+ print(f" Input: {input_text_en}")
68
+ print(f" Output: {generated_text_en}")
69
+
70
+ # ============================================================
71
+ # 8. Test Japanese understanding (donor model language)
72
+ # ============================================================
73
+ print("\n" + "=" * 60)
74
+ print("Test 2 - Japanese understanding (donor language test):")
75
+
76
+ input_text_ja = "konnichiwa, watashi wa jinsei desu."
77
+ inputs_ja = loaded_tokenizer(input_text_ja, return_tensors="pt")
78
+ outputs_ja = loaded_model.generate(**inputs_ja, max_new_tokens=20)
79
+ generated_text_ja = loaded_tokenizer.decode(outputs_ja[0], skip_special_tokens=True)
80
+
81
+ print(f" Input (Japanese romaji): {input_text_ja}")
82
+ print(f" Output: {generated_text_ja}")
83
+
84
+ # Analysis
85
+ if "konnichiwa" in generated_text_ja.lower():
86
+ print(" Analysis: Model attempted Japanese response (partial understanding)")
87
+ elif "hello" in generated_text_ja.lower():
88
+ print(" Analysis: Model recognized greeting but switched to English")
89
+ else:
90
+ print(" Analysis: Model did not understand Japanese input")
91
+
92
+ print("=" * 60)
93
+ print("Testing completed.")