File size: 11,389 Bytes
08894ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
#!/usr/bin/env pwsh

Write-Host "==========================================="
Write-Host "GLEN Full Training on The Vault Dataset"
Write-Host "Processing 34M+ code samples"
Write-Host "==========================================="

# Production parameters
$GPU_MEMORY_THRESHOLD = 0.85
$GPU_CHECK_INTERVAL = 50
$WANDB_PROJECT = "glen-vault-production"

# Training configuration
$PHASE1_EPOCHS = 3
$PHASE2_EPOCHS = 5
$PHASE1_BATCH_SIZE = 32
$PHASE2_BATCH_SIZE = 16
$GRADIENT_ACCUMULATION = 4
$MAX_INPUT_LENGTH = 256
$LEARNING_RATE = 5e-5

Write-Host "πŸ”§ Production Configuration:"
Write-Host "  - Phase 1 epochs: $PHASE1_EPOCHS"
Write-Host "  - Phase 2 epochs: $PHASE2_EPOCHS"
Write-Host "  - Phase 1 batch size: $PHASE1_BATCH_SIZE"
Write-Host "  - Phase 2 batch size: $PHASE2_BATCH_SIZE"
Write-Host "  - Gradient accumulation: $GRADIENT_ACCUMULATION"
Write-Host "  - Max input length: $MAX_INPUT_LENGTH"
Write-Host "  - Learning rate: $LEARNING_RATE"
Write-Host ""

Write-Host "πŸ›‘οΈ Memory Protection:"
Write-Host "  - GPU memory threshold: ${GPU_MEMORY_THRESHOLD} (85%)"
Write-Host "  - Check interval: ${GPU_CHECK_INTERVAL} steps"
Write-Host "  - FP16 training enabled"
Write-Host "  - Automatic checkpoint saving on memory limit"
Write-Host ""

# Check prerequisites
Write-Host "πŸ“‹ Checking prerequisites..."

# Check if full dataset exists
if (-not (Test-Path "the_vault_dataset")) {
    Write-Error "❌ The Vault dataset not found! Please download and extract to 'the_vault_dataset/'"
    Write-Host "   Download from: https://github.com/microsoft/CodeXGLUE/tree/main/Code-Code/CodeT5-learning-framework/data"
    exit 1
}

# Ensure data preprocessing is done for full dataset
Write-Host "Checking full dataset preprocessing..."
if (-not (Test-Path "data/the_vault/DOC_VAULT_train.tsv")) {
    Write-Host "πŸ”„ Running full dataset preprocessing (this may take 30-60 minutes)..."
    python scripts/preprocess_vault_dataset.py --input_dir the_vault_dataset/ --output_dir data/the_vault/ --full_dataset
    if ($LASTEXITCODE -ne 0) {
        Write-Error "❌ Data preprocessing failed!"
        exit 1
    }
} else {
    $train_lines = (Get-Content "data/the_vault/DOC_VAULT_train.tsv").Count
    Write-Host "βœ… Full dataset already preprocessed ($train_lines training samples)"
}

# Check GPU availability
$gpu_count = 0
try {
    $gpu_info = nvidia-smi --query-gpu=name --format=csv,noheader,nounits 2>$null
    if ($gpu_info) {
        $gpu_count = ($gpu_info | Measure-Object).Count
        Write-Host "πŸ–₯️  Detected $gpu_count GPU(s): $($gpu_info -join ', ')"
    }
} catch {
    Write-Host "⚠️  No GPU detected, will use CPU (training will be much slower)"
}

if ($gpu_count -eq 0) {
    Write-Host "⚠️  Warning: Training on CPU will take days/weeks. Consider using GPU."
    $response = Read-Host "Continue with CPU training? (y/N)"
    if ($response -ne "y" -and $response -ne "Y") {
        Write-Host "Training cancelled."
        exit 0
    }
}

Write-Host ""
Write-Host "=== Phase 1 Training: Document ID Assignment ==="
Write-Host "🎯 Learning to assign semantic identifiers to code documents"

$PHASE1_OUTPUT = "logs/glen_vault_production/GLEN_P1"
$env:CUDA_VISIBLE_DEVICES = "0"

try {
    python examples/glen_phase1/train_glen.py `
        --output_dir $PHASE1_OUTPUT `
        --model_name_or_path t5-base `
        --query_type gtq_doc `
        --per_device_train_batch_size $PHASE1_BATCH_SIZE `
        --per_device_eval_batch_size 8 `
        --gradient_accumulation_steps $GRADIENT_ACCUMULATION `
        --learning_rate $LEARNING_RATE `
        --dropout_rate 0.1 `
        --Rdrop 0.15 `
        --aug_query True `
        --aug_query_type corrupted_query `
        --input_dropout 1 `
        --id_class t5_bm25_truncate_3 `
        --dataset_name the_vault `
        --tree 1 `
        --pretrain_decoder True `
        --max_input_length $MAX_INPUT_LENGTH `
        --val_check_interval 0.1 `
        --tie_word_embeddings True `
        --decoder_input doc_rep `
        --max_output_length 10 `
        --num_return_sequences 10 `
        --logging_steps 100 `
        --eval_steps 1000 `
        --save_steps 2000 `
        --overwrite_output_dir `
        --wandb_tag "phase1_production" `
        --project_name $WANDB_PROJECT `
        --do_eval True `
        --evaluation_strategy steps `
        --num_train_epochs $PHASE1_EPOCHS `
        --save_strategy steps `
        --save_total_limit 5 `
        --load_best_model_at_end True `
        --metric_for_best_model eval_loss `
        --greater_is_better False `
        --seed 42 `
        --gpu_memory_threshold $GPU_MEMORY_THRESHOLD `
        --gpu_check_interval $GPU_CHECK_INTERVAL `
        --fp16 True `
        --dataloader_num_workers 4 `
        --warmup_ratio 0.1

    if ($LASTEXITCODE -ne 0) {
        throw "Phase 1 training failed!"
    }
} catch {
    Write-Error "❌ Phase 1 training failed: $_"
    Write-Host "πŸ“ Check logs in: $PHASE1_OUTPUT"
    exit 1
}

Write-Host "βœ… Phase 1 training completed successfully!"

# Validate Phase 1 checkpoint
if (-not (Test-Path $PHASE1_OUTPUT)) {
    Write-Error "❌ Phase 1 checkpoint not found at $PHASE1_OUTPUT"
    exit 1
fi

# Find the best checkpoint
$best_checkpoint = Get-ChildItem -Path $PHASE1_OUTPUT -Directory -Name "checkpoint-*" | 
    Sort-Object {[int]($_.Split('-')[1])} | Select-Object -Last 1

if ($best_checkpoint) {
    Write-Host "πŸ“ Using Phase 1 checkpoint: $best_checkpoint"
    $PHASE1_CKPT = "$PHASE1_OUTPUT/$best_checkpoint"
} else {
    $PHASE1_CKPT = $PHASE1_OUTPUT
}

Write-Host ""
Write-Host "=== Phase 2 Training: Ranking-based Refinement ==="
Write-Host "🎯 Learning to rank and refine document identifiers"

$PHASE2_OUTPUT = "logs/glen_vault_production/GLEN_P2"

try {
    python examples/glen_phase2/train_glen.py `
        --output_dir $PHASE2_OUTPUT `
        --model_name_or_path $PHASE1_CKPT `
        --per_device_train_batch_size $PHASE2_BATCH_SIZE `
        --per_device_eval_batch_size 4 `
        --gradient_accumulation_steps $GRADIENT_ACCUMULATION `
        --learning_rate $LEARNING_RATE `
        --dropout_rate 0.1 `
        --warmup_ratio 0.1 `
        --id_class t5_bm25_truncate_3 `
        --dataset_name the_vault `
        --tree 1 `
        --q_max_len 64 `
        --p_max_len $MAX_INPUT_LENGTH `
        --negative_passage_type self `
        --positive_passage_no_shuffle True `
        --tie_word_embeddings True `
        --num_return_sequences 10 `
        --logging_steps 100 `
        --eval_steps 1000 `
        --save_steps 2000 `
        --overwrite_output_dir `
        --wandb_tag "phase2_production" `
        --project_name $WANDB_PROJECT `
        --do_eval True `
        --evaluation_strategy steps `
        --num_train_epochs $PHASE2_EPOCHS `
        --save_strategy steps `
        --save_total_limit 5 `
        --load_best_model_at_end True `
        --metric_for_best_model eval_loss `
        --greater_is_better False `
        --seed 42 `
        --gpu_memory_threshold $GPU_MEMORY_THRESHOLD `
        --gpu_check_interval $GPU_CHECK_INTERVAL `
        --fp16 True `
        --dataloader_num_workers 4

    if ($LASTEXITCODE -ne 0) {
        throw "Phase 2 training failed!"
    }
} catch {
    Write-Error "❌ Phase 2 training failed: $_"
    Write-Host "πŸ“ Check logs in: $PHASE2_OUTPUT"
    exit 1
}

Write-Host "βœ… Phase 2 training completed successfully!"

# Validate Phase 2 checkpoint
if (-not (Test-Path $PHASE2_OUTPUT)) {
    Write-Error "❌ Phase 2 checkpoint not found at $PHASE2_OUTPUT"
    exit 1
}

# Find the best Phase 2 checkpoint
$best_checkpoint_p2 = Get-ChildItem -Path $PHASE2_OUTPUT -Directory -Name "checkpoint-*" | 
    Sort-Object {[int]($_.Split('-')[1])} | Select-Object -Last 1

if ($best_checkpoint_p2) {
    Write-Host "πŸ“ Using Phase 2 checkpoint: $best_checkpoint_p2"
    $PHASE2_CKPT = "$PHASE2_OUTPUT/$best_checkpoint_p2"
} else {
    $PHASE2_CKPT = $PHASE2_OUTPUT
}

Write-Host ""
Write-Host "=== Document ID Generation ==="
Write-Host "🎯 Generating semantic IDs for all documents"

try {
    python examples/glen_phase2/makeid_glen.py `
        --model_name_or_path $PHASE2_CKPT `
        --infer_dir $PHASE2_CKPT `
        --dataset_name the_vault `
        --docid_file_name glen_vault_production_docids `
        --per_device_eval_batch_size 16 `
        --max_input_length $MAX_INPUT_LENGTH `
        --num_return_sequences 20

    if ($LASTEXITCODE -ne 0) {
        throw "Document ID generation failed!"
    }
} catch {
    Write-Error "❌ Document ID generation failed: $_"
    exit 1
}

# Validate docid file
$docid_file = "logs/glen_vault_production/glen_vault_production_docids.tsv"
if (-not (Test-Path $docid_file)) {
    Write-Error "❌ Document ID file not created: $docid_file"
    exit 1
fi

$total_docs = (Get-Content $docid_file).Count
Write-Host "βœ… Document ID generation completed! Generated $total_docs document IDs"

Write-Host ""
Write-Host "=== Model Evaluation ==="
Write-Host "🎯 Evaluating model performance on test set"

try {
    python examples/glen_phase2/evaluate_glen.py `
        --model_name_or_path $PHASE2_CKPT `
        --infer_dir $PHASE2_CKPT `
        --dataset_name the_vault `
        --docid_file_name glen_vault_production_docids `
        --per_device_eval_batch_size 8 `
        --q_max_len 64 `
        --num_return_sequences 20 `
        --logs_dir logs/glen_vault_production

    if ($LASTEXITCODE -ne 0) {
        throw "Model evaluation failed!"
    }
} catch {
    Write-Error "❌ Model evaluation failed: $_"
    exit 1
}

Write-Host "βœ… Model evaluation completed successfully!"

# Training completion summary
$training_time = Get-Date
Write-Host ""
Write-Host "==========================================="
Write-Host "πŸŽ‰ FULL TRAINING COMPLETED SUCCESSFULLY! πŸŽ‰"
Write-Host "==========================================="
Write-Host ""
Write-Host "πŸ“Š Training Summary:"
Write-Host "  βœ… Phase 1: Document ID Assignment ($PHASE1_EPOCHS epochs)"
Write-Host "  βœ… Phase 2: Ranking Refinement ($PHASE2_EPOCHS epochs)"
Write-Host "  βœ… Document ID Generation ($total_docs documents)"
Write-Host "  βœ… Model Evaluation & Metrics"
Write-Host ""
Write-Host "πŸ“ Production Model Artifacts:"
Write-Host "  🏷️  Phase 1 Checkpoint: $PHASE1_CKPT"
Write-Host "  🏷️  Phase 2 Checkpoint: $PHASE2_CKPT"
Write-Host "  πŸ“„ Document IDs: $docid_file"
Write-Host "  πŸ“Š Evaluation Results: logs/glen_vault_production/"
Write-Host ""
Write-Host "πŸ›‘οΈ Memory Protection Summary:"
Write-Host "  - GPU memory threshold: ${GPU_MEMORY_THRESHOLD} (85%)"
Write-Host "  - Check interval: ${GPU_CHECK_INTERVAL} steps"
Write-Host "  - FP16 training enabled throughout"
Write-Host "  - Automatic checkpoint saving on memory limits"
Write-Host ""
Write-Host "πŸ“ˆ Performance Optimizations Used:"
Write-Host "  - Gradient accumulation: ${GRADIENT_ACCUMULATION}x"
Write-Host "  - Multi-worker data loading"
Write-Host "  - Mixed precision training (FP16)"
Write-Host "  - Memory-efficient batch sizes"
Write-Host ""
Write-Host "πŸš€ Your GLEN model is ready for production use!"
Write-Host "   - Use the Phase 2 checkpoint for inference"
Write-Host "   - Document IDs are saved for fast retrieval"
Write-Host "   - Evaluation metrics are in the logs directory"
Write-Host ""
Write-Host "Training completed at: $training_time"