Views
No views yet
1# Validate all samples in dataset
2print("\n--- Validating Dataset Keys ---")
3required_keys = [
4 "input_ids", "labels", "attention_mask",
5 "input_ids_user", "labels_user", "attention_mask_user",
6 "input_ids_assistant", "labels_assistant", "attention_mask_assistant"
7]
8for split in ["train", "test"]:
9 print(f"\nChecking {split} split...")
10 missing_samples = []
11 for idx, sample in tqdm(enumerate(tokenized_dataset[split]), total=len(tokenized_dataset[split]), desc=f"Validating {split} split"):
12 missing_keys = [key for key in required_keys if key not in sample]
13 if missing_keys:
14 missing_samples.append((idx, missing_keys))
15 if missing_samples:
16 print(f"Found {len(missing_samples)} problematic samples in {split} split:")
17 for idx, missing_keys in missing_samples[:5]:
18 print(f"Sample {idx} missing keys: {missing_keys}")
19 raise ValueError(f"Dataset validation failed in {split} split.")
20 print(f"{split} split: All {len(tokenized_dataset[split])} samples validated.")
21
22COLUMNS_TO_KEEP = required_keys
23try:
24 tokenized_dataset["train"] = tokenized_dataset["train"].select_columns(COLUMNS_TO_KEEP)
25 tokenized_dataset["test"] = tokenized_dataset["test"].select_columns(COLUMNS_TO_KEEP)
26 print(f"Dataset columns filtered to: {COLUMNS_TO_KEEP}")
27except Exception as e:
28 print(f"Error during column selection: {e}")
29 print(f"Available columns in train: {tokenized_dataset['train'].column_names}")
30 print(f"Available columns in test: {tokenized_dataset['test'].column_names}")
31 raise
321
2# PEFT (LoRA) Config
3peft_config = LoraConfig(
4 lora_alpha=16,
5 lora_dropout=0.1,
6 r=64,
7 bias="none",
8 task_type="CAUSAL_LM",
9 target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
10)
11
12
13# Training Arguments - OPTIMIZED FOR JEPA MONITORING
14training_arguments = TrainingArguments(
15 output_dir=OUTPUT_DIR,
16 num_train_epochs=1,
17 per_device_train_batch_size=2,
18 gradient_accumulation_steps=8,
19 optim="paged_adamw_8bit",
20 save_steps=0, # Disable saving during demo
21 logging_steps=50, # See JEPA metrics every 10 steps
22 max_steps=500, # Just enough to see JEPA loss decreasing
23 learning_rate=2e-4,
24 weight_decay=0.001,
25 fp16=True,
26 bf16=False,
27 max_grad_norm=0.3,
28 warmup_ratio=0.03,
29 lr_scheduler_type="cosine",
30 disable_tqdm=False,
31 report_to="none",
32 # ↓↓↓ CRITICAL CHANGES FOR DEMO ↓↓↓
33 evaluation_strategy="no", # Disable evaluation during training
34 eval_steps=None, # No evaluation steps
35 metric_for_best_model=None, # Not needed for demo
36 # ↑↑↑ CRITICAL CHANGES FOR DEMO ↑↑↑
37 dataloader_drop_last=True,
38 dataloader_num_workers=0,
39 gradient_checkpointing=True,
40 gradient_checkpointing_kwargs={"use_reentrant": False},
41 resume_from_checkpoint=True
42)
431
2from transformers import (
3 AutoModelForCausalLM,
4 AutoTokenizer,
5 BitsAndBytesConfig,
6)
7import torch
8from peft import PeftModel
9import peft
10import os
11
12# --- FILE PATHS (Replicated from original code) ---
13MODEL_NAME = "mistralai/Mistral-7B-v0.1"
14HUB_MODEL_ID = "frankmorales2020/Mistral-7B-BTC-JEPA-LLM-Expert"
15
16# --- 1. SETUP ---
17DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
18MODEL_TYPE = "FINE_TUNED"
19
20# --- 2. MODEL AND TOKENIZER LOADING (Single block for efficiency) ---
21print("\n--- Model and Tokenizer Setup ---")
22print(f"--- Loading Model onto {DEVICE} ---")
23print(f'BASE MODEL: {MODEL_NAME}\nFINE TUNE MODEL: {HUB_MODEL_ID}')
24
25try:
26 # 4-bit Quantization Config
27 bnb_config = BitsAndBytesConfig(
28 load_in_4bit=True,
29 bnb_4bit_quant_type="nf4",
30 bnb_4bit_compute_dtype=torch.float16,
31 )
32
33 # Load tokenizer
34 tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
35 tokenizer.pad_token = tokenizer.eos_token
36
37 # Add special tokens and resize embeddings (essential for fine-tuned LoRA)
38 SPECIAL_PREDICTOR_TOKENS = ["<pred>", "<targ>", "<jepa>"]
39 tokenizer.add_special_tokens({"additional_special_tokens": SPECIAL_PREDICTOR_TOKENS})
40
41 # Load base model
42 base_model = AutoModelForCausalLM.from_pretrained(
43 MODEL_NAME,
44 quantization_config=bnb_config,
45 device_map="auto",
46 trust_remote_code=True,
47 )
48 base_model.resize_token_embeddings(len(tokenizer))
49
50 # Load fine-tuned adapter weights
51 model = PeftModel.from_pretrained(base_model, HUB_MODEL_ID).eval()
52 print("🎉 SUCCESS: Loaded fine-tuned JEPA model!")
53
54except Exception as e:
55 print(f"❌ Model loading failed: {e}")
56 # Fallback to base model logic is removed for this test since the specific fine-tuned
57 # model must be used, so we raise the error.
58 raise
59
60# --- 3. INFERENCE FUNCTION (Encapsulating fixed parameters) ---
61
62def run_inference_test(btc_data_input, tokenizer, model, device):
63 """Runs a single inference test with the fixed strict extraction logic."""
64
65 # 1. Create Strict Prompt
66 user_prompt_content = f"Current BTC data: {btc_data_input}. Give ONLY the 12-hour direction (UP, DOWN, or FLAT). The output MUST be a single word: UP, DOWN, or FLAT."
67 input_text = f"<s>[INST] {user_prompt_content} [/INST]"
68
69 # 2. Tokenize and Set Fixed Generation Params
70 inputs = tokenizer(input_text, return_tensors="pt").to(device)
71
72 # Fixed generation parameters proven to work with robust extraction
73 generation_params = {
74 "max_new_tokens": 15,
75 "do_sample": False,
76 "temperature": 0.1,
77 "top_p": 1.0,
78 "repetition_penalty": 1.0,
79 }
80
81 # 3. Generate Output
82 with torch.no_grad():
83 outputs = model.generate(
84 **inputs,
85 **generation_params,
86 pad_token_id=tokenizer.eos_token_id,
87 eos_token_id=tokenizer.eos_token_id,
88 )
89
90 response_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
91
92 # 4. Robust Extraction Logic (Final Corrected Logic)
93 prediction_output = "❌ PREDICTION NOT FOUND"
94 target_words = ["UP", "DOWN", "FLAT"]
95
96 if "[/INST]" in response_text:
97 prediction_output_raw = response_text.split("[/INST]")[-1].strip()
98
99 # Iterate through the expected target words
100 for target in target_words:
101 if target in prediction_output_raw.upper():
102 prediction_output = target
103 break
104 else:
105 prediction_output_raw = response_text.strip()
106 for target in target_words:
107 if target in prediction_output_raw.upper():
108 prediction_output = target
109 break
110
111 return input_text, prediction_output_raw, prediction_output
112
113# --- 4. MULTI-INPUT EXECUTION ---
114
115# Define the 3 test cases to check for all directions
116TEST_CASES = [
117 {
118 "name": "Test 1: Downward Reversal (Original Input)",
119 "input": "[O:30000, H:30500, C:30200]",
120 "expected_logic": "DOWN"
121 },
122]
123
124
125for i, test in enumerate(TEST_CASES):
126 print(f"\n[{test['name']} - Expecting {test['expected_logic']}]")
127
128 # Run the test
129 input_text, raw_output, cleaned_prediction = run_inference_test(
130 test['input'], tokenizer, model, DEVICE
131 )
132
133 # Print results
134 print("=" * 70)
135 print(f"📤 INPUT: {test['input']}")
136 print(f"🤖 RAW OUTPUT: {raw_output}")
137 print(f"✅ CLEANED PREDICTION: **{cleaned_prediction}**")
138 print("=" * 70)
139
1401
2
3[Test 1: Downward Reversal (Original Input) - Expecting DOWN]
4======================================================================
5📤 INPUT: [O:30000, H:30500, C:30200]
6🤖 RAW OUTPUT: The 12-hour prediction is **DOWN**. The final prediction is
7✅ CLEANED PREDICTION: **DOWN**
8======================================================================
91
2import os
3import torch
4import torch.nn.functional as F
5from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
6from peft import PeftModel
7
8os.environ["CUDA_HOME"] = "/usr/local/cuda"
9
10# --- 2. CONFIGURATION ---
11MODEL_NAME = "mistralai/Mistral-7B-v0.1"
12HUB_MODEL_ID = "frankmorales2020/Mistral-7B-BTC-JEPA-LLM-Expert"
13DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
14SPECIAL_TOKENS = ["<|predictor_1|>", "<|predictor_2|>", "<|predictor_3|>"]
15
16# --- 3. THE FIXED LOADING SEQUENCE ---
17tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
18tokenizer.pad_token = tokenizer.eos_token
19tokenizer.add_special_tokens({"additional_special_tokens": SPECIAL_TOKENS})
20
21bnb_config = BitsAndBytesConfig(
22 load_in_4bit=True,
23 bnb_4bit_quant_type="nf4",
24 bnb_4bit_compute_dtype=torch.float16,
25)
26
27base_model = AutoModelForCausalLM.from_pretrained(MODEL_NAME, quantization_config=bnb_config, device_map="auto")
28
29base_model.resize_token_embeddings(len(tokenizer))
30
31model = PeftModel.from_pretrained(base_model, HUB_MODEL_ID).eval()
32print("🎉 SUCCESS: Model and JEPA Expert loaded!")
33
34# --- 4. CALIBRATED INFERENCE ENGINE (DEMO-FOCUSED) ---
35def run_expert_inference(ohlc_data, rsi=50.0, sma=60000.0):
36 target_words = ["UP", "DOWN", "FLAT"]
37 target_ids = [tokenizer.encode(word, add_special_tokens=False)[-1] for word in target_words]
38
39 instruction = (
40 f"Analyze BTC Market Data: {ohlc_data}. "
41 f"Technicals: RSI(14) is {rsi:.2f}, SMA(20) is {sma:.2f}. "
42 f"Direction (UP/DOWN/FLAT):"
43 )
44 prompt = f"<s>[INST] {instruction} [/INST]"
45
46 with torch.no_grad():
47 null_prompt = f"<s>[INST] Analyze BTC Market Data: [O:60000, H:60100, C:60050]. Technicals: RSI(14) is 50.00, SMA(20) is 60000.00. Direction (UP/DOWN/FLAT): [/INST]"
48 n_inputs = tokenizer(null_prompt, return_tensors="pt").to(DEVICE)
49 null_logits = model(**n_inputs).logits[0, -1, target_ids]
50
51 r_inputs = tokenizer(prompt, return_tensors="pt").to(DEVICE)
52 real_logits = model(**r_inputs).logits[0, -1, target_ids]
53
54 # Temperature 1.0 for natural balance in demo cases
55 calibrated_logits = (real_logits - null_logits) / 1.0
56 probs = F.softmax(calibrated_logits, dim=-1)
57
58 confidences = {word: round(prob.item(), 3) for word, prob in zip(target_words, probs)}
59 prediction = max(confidences, key=confidences.get)
60 return prediction, confidences
61
621
2print("🎉 SUCCESS: Model and JEPA Expert loaded!")
3#--- 5. FINAL DEMO CASES TO SHOWCASE UP, DOWN, and FLAT ---
4demo_cases = [
5 # Clear bearish crash (strong DOWN signal)
6 {"label": "BEARISH CRASH (DOWN Demo)", "data": "[O:100000, H:101000, C:70000]", "rsi": 20.0, "sma": 95000.0},
7
8 # Pure neutral flat (FLAT Demo)
9 {"label": "NEUTRAL FLAT (FLAT Demo)", "data": "[O:87000, H:87100, C:87050]", "rsi": 50.0, "sma": 87000.0},
10
11 # Current real market Dec 25, 2025 (~$87,700, neutral RSI ~43, mild weakness below SMA ~$88,500)
12 {"label": "CURRENT REAL (FLAT/DOWN-ish)", "data": "[O:87700, H:87800, C:87700]", "rsi": 43.0, "sma": 88500.0},
13
14 # Mild bullish (to trigger UP – the adapter sometimes favors UP in very neutral cases)
15 {"label": "MILD BULLISH (UP Demo)", "data": "[O:87000, H:88000, C:87500]", "rsi": 55.0, "sma": 86800.0},
16
17 # Strong bullish rally (UP Demo fallback if needed)
18 {"label": "STRONG BULLISH (UP Demo)", "data": "[O:80000, H:95000, C:94000]", "rsi": 75.0, "sma": 82000.0},
19]
20
21print("\n" + "="*95)
22print(f"{'Demo Scenario':<30} | {'Prediction':<10} | {'Confidence (UP / DOWN / FLAT)'}")
23print("-" * 95)
24for test in demo_cases:
25 pred, scores = run_expert_inference(test['data'], rsi=test['rsi'], sma=test['sma'])
26 score_str = f"U:{scores['UP']:.3f} D:{scores['DOWN']:.3f} F:{scores['FLAT']:.3f}"
27 print(f"{test['label']:<30} | {pred:<10} | {score_str}")
28print("="*95)
291🎉 SUCCESS: Model and JEPA Expert loaded!
2
3===============================================================================================
4Demo Scenario | Prediction | Confidence (UP / DOWN / FLAT)
5-----------------------------------------------------------------------------------------------
6BEARISH CRASH (DOWN Demo) | FLAT | U:0.328 D:0.332 F:0.340
7NEUTRAL FLAT (FLAT Demo) | UP | U:0.337 D:0.335 F:0.329
8CURRENT REAL (FLAT/DOWN-ish) | DOWN | U:0.332 D:0.338 F:0.330
9MILD BULLISH (UP Demo) | DOWN | U:0.331 D:0.337 F:0.331
10STRONG BULLISH (UP Demo) | DOWN | U:0.331 D:0.336 F:0.332
11===============================================================================================1
2✅ JEPA Monitoring Enabled - will show metrics every 50/500 steps
3
4Step Training Loss
550 0.876400
6100 0.235400
7150 0.224500
8200 0.229200
9250 0.231300
10300 0.221500
11350 0.225300
12400 0.229300
13450 0.220400
14500 0.224200
15
16🎯 JEPA Metrics [Step 50]:
17 JEPA Loss: 0.0001
18 LM Loss: 0.2534
19 Cosine Sim: 0.9999
20 Total Loss: 0.2535
21
22🎯 JEPA Metrics [Step 100]:
23 JEPA Loss: 0.0000
24 LM Loss: 0.2319
25 Cosine Sim: 1.0000
26 Total Loss: 0.2320
27
28🎯 JEPA Metrics [Step 150]:
29 JEPA Loss: 0.0000
30 LM Loss: 0.2438
31 Cosine Sim: 1.0000
32 Total Loss: 0.2438
33
34🎯 JEPA Metrics [Step 200]:
35 JEPA Loss: 0.0000
36 LM Loss: 0.2384
37 Cosine Sim: 1.0000
38 Total Loss: 0.2384
39
40🎯 JEPA Metrics [Step 250]:
41 JEPA Loss: 0.0000
42 LM Loss: 0.2216
43 Cosine Sim: 1.0000
44 Total Loss: 0.2217
45
46
47🎯 JEPA Metrics [Step 300]:
48 JEPA Loss: 0.0000
49 LM Loss: 0.1579
50 Cosine Sim: 1.0000
51 Total Loss: 0.1580
52
53🎯 JEPA Metrics [Step 350]:
54 JEPA Loss: 0.0000
55 LM Loss: 0.2287
56 Cosine Sim: 1.0000
57 Total Loss: 0.2287
58
59🎯 JEPA Metrics [Step 400]:
60 JEPA Loss: 0.0000
61 LM Loss: 0.2151
62 Cosine Sim: 1.0000
63 Total Loss: 0.2152
64
65🎯 JEPA Metrics [Step 450]:
66 JEPA Loss: 0.0000
67 LM Loss: 0.1994
68 Cosine Sim: 1.0000
69 Total Loss: 0.1994
70
71🎯 JEPA Metrics [Step 500]:
72 JEPA Loss: 0.0000
73 LM Loss: 0.2188
74 Cosine Sim: 1.0000
75 Total Loss: 0.2189
761
2Wed Oct 8 05:48:17 2025
3+-----------------------------------------------------------------------------------------+
4| NVIDIA-SMI 550.54.15 Driver Version: 550.54.15 CUDA Version: 12.4 |
5|-----------------------------------------+------------------------+----------------------+
6| GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC |
7| Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. |
8| | | MIG M. |
9|=========================================+========================+======================|
10| 0 NVIDIA L4 Off | 00000000:00:03.0 Off | 0 |
11| N/A 37C P8 11W / 72W | 0MiB / 23034MiB | 0% Default |
12| | | N/A |
13+-----------------------------------------+------------------------+----------------------+
14
15+-----------------------------------------------------------------------------------------+
16| Processes: |
17| GPU GI CI PID Type Process name GPU Memory |
18| ID ID Usage |
19|=========================================================================================|
20| No running processes found |
21+-----------------------------------------------------------------------------------------+
22