Aadhitech1 commited on
Commit
6082a5d
·
verified ·
1 Parent(s): 40fd778

Upload 8 files

Browse files
Files changed (8) hide show
  1. PROJECT_STRUCTURE.txt +53 -0
  2. README.txt +20 -0
  3. compare_models.py +2805 -0
  4. requirements.txt +8 -0
  5. run_all.bat +3 -0
  6. run_all.sh +4 -0
  7. test.py +1353 -0
  8. train.py +848 -0
PROJECT_STRUCTURE.txt ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TELECOM QLoRA FOUR-OUTPUT COMPLETE WORKSPACE
2
+
3
+ Project structure
4
+ =================
5
+ train.py
6
+ test.py
7
+ requirements.txt
8
+ run_all.sh
9
+ run_all.bat
10
+ README.txt
11
+
12
+ sample/
13
+ data/
14
+ train_four_output.jsonl
15
+ validation_four_output.jsonl
16
+ test_four_output.jsonl
17
+ .cache/
18
+ huggingface/
19
+
20
+ models/
21
+ (training output will be written here)
22
+
23
+ Training
24
+ ========
25
+ 1. Install dependencies:
26
+ pip install -r requirements.txt
27
+
28
+ 2. Make sure CUDA + a compatible NVIDIA GPU/bitsandbytes setup is available.
29
+
30
+ 3. Train:
31
+ python train.py
32
+
33
+ 4. Evaluate:
34
+ python test.py --adapter "models/telecom-qwen-four-output" --test "sample/data/test_four_output.jsonl" --samples 0
35
+
36
+ Debug:
37
+ ======
38
+ python test.py --adapter "models/telecom-qwen-four-output" --test "sample/data/test_four_output.jsonl" --samples 10 --debug
39
+
40
+ Expected response sections
41
+ ===========================
42
+ Probable Root Cause:
43
+ Explanation:
44
+ Recommendation:
45
+ Fault Severity:
46
+ fault_severity=0|1|2
47
+
48
+ Important
49
+ =========
50
+ Root Cause, Explanation, and Recommendation targets are structured,
51
+ data-constrained synthetic targets because the source dataset contains
52
+ fault_severity labels but not engineer-validated root-cause/remediation
53
+ annotations. See README.txt.
README.txt ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TELECOM FOUR-OUTPUT DATASET
2
+
3
+ Files:
4
+ - train_four_output.jsonl
5
+ - validation_four_output.jsonl
6
+ - test_four_output.jsonl
7
+
8
+ IMPORTANT:
9
+ The original cleaned data provides fault_severity labels and telecom
10
+ event/log features, but it does not provide independently verified root-cause
11
+ or remediation ground truth. Therefore, the Root Cause, Explanation, and
12
+ Recommendation fields in these files are STRUCTURED, DATA-CONSTRAINED
13
+ SYNTHETIC TARGETS derived from the supplied features and the existing label.
14
+ They must not be presented as ground-truth engineering diagnoses.
15
+
16
+ The targets intentionally avoid inventing RSRP/RSRQ/SINR/CQI/PRB/PCI,
17
+ throughput, alarms, hardware failures, or other absent telemetry.
18
+
19
+ For a production root-cause model, replace these synthetic targets with
20
+ engineer-validated annotations.
compare_models.py ADDED
@@ -0,0 +1,2805 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # ============================================================
4
+ #
5
+ # Compare:
6
+ #
7
+ # 1. Original Qwen/Qwen2.5-1.5B-Instruct
8
+ # 2. Fine-tuned QLoRA adapter
9
+ #
10
+ # Evaluation:
11
+ #
12
+ # - Fault Severity Accuracy
13
+ # - Fault Severity Macro F1
14
+ # - Fault Severity Weighted F1
15
+ # - Root Cause Token-F1
16
+ # - Explanation Token-F1
17
+ # - Recommendation Token-F1
18
+ # - Four-output Format Compliance
19
+ # - Input Tokens
20
+ # - Output Tokens
21
+ # - Total Tokens
22
+ # - Generation Time
23
+ # - Tokens / Second
24
+ #
25
+ # IMPORTANT:
26
+ #
27
+ # This version does NOT use an LLM judge.
28
+ # It is therefore faster and reproducible.
29
+ #
30
+ # ============================================================
31
+
32
+ import os
33
+ import re
34
+ import json
35
+ import csv
36
+ import argparse
37
+ import time
38
+ import gc
39
+ from collections import Counter
40
+
41
+ import torch
42
+
43
+ from datasets import load_dataset
44
+
45
+ from transformers import (
46
+ AutoTokenizer,
47
+ AutoModelForCausalLM,
48
+ BitsAndBytesConfig,
49
+ )
50
+
51
+ from peft import PeftModel
52
+
53
+
54
+ # ============================================================
55
+ # CONFIGURATION
56
+ # ============================================================
57
+
58
+ MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"
59
+
60
+ DEFAULT_ADAPTER = (
61
+ "models/telecom-qwen-four-output"
62
+ )
63
+
64
+ DEFAULT_TEST_FILE = (
65
+ "sample/data/test_four_output.jsonl"
66
+ )
67
+
68
+ DEFAULT_OUTPUT_DIR = (
69
+ "evaluation_results"
70
+ )
71
+
72
+ CACHE_DIR = (
73
+ "sample/.cache/huggingface"
74
+ )
75
+
76
+ # Number of examples:
77
+ #
78
+ # 10 = very quick test
79
+ # 50 = quick evaluation
80
+ # 100 = better evaluation
81
+ # 0 = entire test set
82
+ #
83
+ DEFAULT_SAMPLES = 50
84
+
85
+ MAX_INPUT_LENGTH = 1024
86
+
87
+ MAX_NEW_TOKENS = 220
88
+
89
+
90
+ # ============================================================
91
+ # COMMAND LINE
92
+ # ============================================================
93
+
94
+ parser = argparse.ArgumentParser(
95
+ description="Fast comparison of original and fine-tuned Qwen models"
96
+ )
97
+
98
+ parser.add_argument(
99
+ "--adapter",
100
+ default=DEFAULT_ADAPTER,
101
+ help="Path to LoRA adapter",
102
+ )
103
+
104
+ parser.add_argument(
105
+ "--test",
106
+ default=DEFAULT_TEST_FILE,
107
+ help="Path to test JSONL",
108
+ )
109
+
110
+ parser.add_argument(
111
+ "--samples",
112
+ type=int,
113
+ default=DEFAULT_SAMPLES,
114
+ help="Number of examples. 0 = all examples.",
115
+ )
116
+
117
+ parser.add_argument(
118
+ "--output",
119
+ default=DEFAULT_OUTPUT_DIR,
120
+ help="Output directory",
121
+ )
122
+
123
+ parser.add_argument(
124
+ "--debug",
125
+ action="store_true",
126
+ help="Print detailed prediction for every example",
127
+ )
128
+
129
+ args = parser.parse_args()
130
+
131
+
132
+ # ============================================================
133
+ # HEADER
134
+ # ============================================================
135
+
136
+ print("=" * 80)
137
+ print("TELECOM FAST MODEL COMPARISON")
138
+ print("=" * 80)
139
+
140
+ print()
141
+ print("Base model:")
142
+ print(MODEL_NAME)
143
+
144
+ print()
145
+ print("Adapter:")
146
+ print(args.adapter)
147
+
148
+ print()
149
+ print("Test file:")
150
+ print(args.test)
151
+
152
+
153
+ # ============================================================
154
+ # GPU CHECK
155
+ # ============================================================
156
+
157
+ print()
158
+ print("=" * 80)
159
+ print("GPU")
160
+ print("=" * 80)
161
+
162
+ print()
163
+
164
+ if not torch.cuda.is_available():
165
+
166
+ raise RuntimeError(
167
+ "CUDA GPU is required for this evaluation."
168
+ )
169
+
170
+ print(
171
+ "CUDA available:",
172
+ torch.cuda.is_available(),
173
+ )
174
+
175
+ print(
176
+ "GPU:",
177
+ torch.cuda.get_device_name(0),
178
+ )
179
+
180
+ gpu_memory = (
181
+ torch.cuda.get_device_properties(0)
182
+ .total_memory
183
+ / (1024 ** 3)
184
+ )
185
+
186
+ print(
187
+ "VRAM:",
188
+ round(gpu_memory, 2),
189
+ "GB",
190
+ )
191
+
192
+
193
+ # ============================================================
194
+ # DIRECTORY / FILE CHECK
195
+ # ============================================================
196
+
197
+ if not os.path.exists(args.test):
198
+
199
+ raise FileNotFoundError(
200
+ "\nTest file not found:\n"
201
+ + os.path.abspath(args.test)
202
+ )
203
+
204
+
205
+ if not os.path.exists(args.adapter):
206
+
207
+ raise FileNotFoundError(
208
+ "\nAdapter not found:\n"
209
+ + os.path.abspath(args.adapter)
210
+ )
211
+
212
+
213
+ os.makedirs(
214
+ args.output,
215
+ exist_ok=True,
216
+ )
217
+
218
+
219
+ # ============================================================
220
+ # LOAD DATASET
221
+ # ============================================================
222
+
223
+ print()
224
+ print("=" * 80)
225
+ print("LOADING TEST DATA")
226
+ print("=" * 80)
227
+
228
+ dataset = load_dataset(
229
+ "json",
230
+ data_files=args.test,
231
+ split="train",
232
+ cache_dir=CACHE_DIR,
233
+ )
234
+
235
+ print(
236
+ "Total examples:",
237
+ len(dataset),
238
+ )
239
+
240
+ if args.samples > 0:
241
+
242
+ number_to_test = min(
243
+ args.samples,
244
+ len(dataset),
245
+ )
246
+
247
+ dataset = dataset.select(
248
+ range(number_to_test)
249
+ )
250
+
251
+ print(
252
+ "Testing examples:",
253
+ len(dataset),
254
+ )
255
+
256
+
257
+ # ============================================================
258
+ # DATA VALIDATION
259
+ # ============================================================
260
+
261
+ print()
262
+ print("=" * 80)
263
+ print("VALIDATING TEST DATA")
264
+ print("=" * 80)
265
+
266
+ for i, example in enumerate(dataset):
267
+
268
+ if "messages" not in example:
269
+
270
+ raise ValueError(
271
+ f"Example {i} does not contain 'messages'."
272
+ )
273
+
274
+ if not isinstance(
275
+ example["messages"],
276
+ list,
277
+ ):
278
+
279
+ raise ValueError(
280
+ f"Example {i}: messages is not a list."
281
+ )
282
+
283
+ roles = [
284
+ message.get("role")
285
+ for message in example["messages"]
286
+ ]
287
+
288
+ if "user" not in roles:
289
+
290
+ raise ValueError(
291
+ f"Example {i} does not contain a user message."
292
+ )
293
+
294
+ if "assistant" not in roles:
295
+
296
+ raise ValueError(
297
+ f"Example {i} does not contain an assistant reference."
298
+ )
299
+
300
+ print(
301
+ "Test data validation completed."
302
+ )
303
+
304
+
305
+ # ============================================================
306
+ # TOKENIZER
307
+ # ============================================================
308
+
309
+ print()
310
+ print("=" * 80)
311
+ print("LOADING TOKENIZER")
312
+ print("=" * 80)
313
+
314
+ tokenizer = AutoTokenizer.from_pretrained(
315
+ MODEL_NAME,
316
+ trust_remote_code=True,
317
+ cache_dir=CACHE_DIR,
318
+ )
319
+
320
+ if tokenizer.pad_token is None:
321
+
322
+ tokenizer.pad_token = tokenizer.eos_token
323
+
324
+ tokenizer.padding_side = "left"
325
+
326
+
327
+ # ============================================================
328
+ # 4-BIT QUANTIZATION
329
+ # ============================================================
330
+
331
+ bnb_config = BitsAndBytesConfig(
332
+
333
+ load_in_4bit=True,
334
+
335
+ bnb_4bit_quant_type="nf4",
336
+
337
+ bnb_4bit_compute_dtype=torch.float16,
338
+
339
+ bnb_4bit_use_double_quant=True,
340
+ )
341
+
342
+
343
+ # ============================================================
344
+ # LOAD ORIGINAL MODEL
345
+ # ============================================================
346
+
347
+ print()
348
+ print("=" * 80)
349
+ print("LOADING ORIGINAL MODEL")
350
+ print("=" * 80)
351
+
352
+ base_model = AutoModelForCausalLM.from_pretrained(
353
+
354
+ MODEL_NAME,
355
+
356
+ quantization_config=bnb_config,
357
+
358
+ device_map="auto",
359
+
360
+ dtype=torch.float16,
361
+
362
+ trust_remote_code=True,
363
+
364
+ cache_dir=CACHE_DIR,
365
+ )
366
+
367
+ base_model.eval()
368
+
369
+ base_model.config.use_cache = True
370
+
371
+ print(
372
+ "Original model loaded."
373
+ )
374
+
375
+
376
+ # ============================================================
377
+ # LOAD FINE-TUNED MODEL
378
+ # ============================================================
379
+
380
+ print()
381
+ print("=" * 80)
382
+ print("LOADING FINE-TUNED MODEL")
383
+ print("=" * 80)
384
+
385
+ fine_tuned_model = PeftModel.from_pretrained(
386
+
387
+ base_model,
388
+
389
+ args.adapter,
390
+ )
391
+
392
+ fine_tuned_model.eval()
393
+
394
+ print(
395
+ "Fine-tuned adapter loaded."
396
+ )
397
+
398
+
399
+ # ============================================================
400
+ # PROMPT CREATION
401
+ # ============================================================
402
+
403
+ def get_prompt(example):
404
+
405
+ messages = []
406
+
407
+ for message in example["messages"]:
408
+
409
+ if message["role"] != "assistant":
410
+
411
+ messages.append(message)
412
+
413
+ return tokenizer.apply_chat_template(
414
+
415
+ messages,
416
+
417
+ tokenize=False,
418
+
419
+ add_generation_prompt=True,
420
+ )
421
+
422
+
423
+ # ============================================================
424
+ # REFERENCE RESPONSE
425
+ # ============================================================
426
+
427
+ def get_reference(example):
428
+
429
+ for message in example["messages"]:
430
+
431
+ if message["role"] == "assistant":
432
+
433
+ content = message.get(
434
+ "content",
435
+ "",
436
+ )
437
+
438
+ return str(content)
439
+
440
+ return ""
441
+
442
+
443
+ # ============================================================
444
+ # SAFE SECTION EXTRACTION
445
+ # ============================================================
446
+
447
+ def extract_section(
448
+ text,
449
+ section_name,
450
+ next_sections,
451
+ ):
452
+ """
453
+ Safely extracts text between section headings.
454
+
455
+ Example:
456
+
457
+ Probable Root Cause:
458
+ Something happened.
459
+
460
+ Explanation:
461
+ Explanation text.
462
+
463
+ Recommendation:
464
+ Restart equipment.
465
+
466
+ Fault Severity:
467
+ 1
468
+
469
+ This implementation deliberately avoids complicated
470
+ dynamically-generated lookahead regexes.
471
+ """
472
+
473
+ if text is None:
474
+
475
+ return ""
476
+
477
+ text = str(text).strip()
478
+
479
+ if not text:
480
+
481
+ return ""
482
+
483
+ # --------------------------------------------------------
484
+ # Find requested heading
485
+ # --------------------------------------------------------
486
+
487
+ start_pattern = (
488
+ r"(?im)^\s*"
489
+ + re.escape(section_name)
490
+ + r"\s*:?\s*"
491
+ )
492
+
493
+ start_match = re.search(
494
+ start_pattern,
495
+ text,
496
+ )
497
+
498
+ if start_match is None:
499
+
500
+ return ""
501
+
502
+ content_start = start_match.end()
503
+
504
+ remaining = text[
505
+ content_start:
506
+ ]
507
+
508
+ # --------------------------------------------------------
509
+ # Find all possible following section headings
510
+ # --------------------------------------------------------
511
+
512
+ next_positions = []
513
+
514
+ for section in next_sections:
515
+
516
+ pattern = (
517
+ r"(?im)^\s*"
518
+ + re.escape(section)
519
+ + r"\s*:?\s*"
520
+ )
521
+
522
+ match = re.search(
523
+ pattern,
524
+ remaining,
525
+ )
526
+
527
+ if match is not None:
528
+
529
+ next_positions.append(
530
+ match.start()
531
+ )
532
+
533
+ # --------------------------------------------------------
534
+ # Stop at earliest next heading
535
+ # --------------------------------------------------------
536
+
537
+ if next_positions:
538
+
539
+ content_end = min(
540
+ next_positions
541
+ )
542
+
543
+ content = remaining[
544
+ :content_end
545
+ ]
546
+
547
+ else:
548
+
549
+ content = remaining
550
+
551
+ return content.strip()
552
+
553
+
554
+ # ============================================================
555
+ # ROOT CAUSE
556
+ # ============================================================
557
+
558
+ def extract_root_cause(text):
559
+
560
+ return extract_section(
561
+
562
+ text,
563
+
564
+ "Probable Root Cause",
565
+
566
+ [
567
+ "Explanation",
568
+ "Recommendation",
569
+ "Fault Severity",
570
+ ],
571
+ )
572
+
573
+
574
+ # ============================================================
575
+ # EXPLANATION
576
+ # ============================================================
577
+
578
+ def extract_explanation(text):
579
+
580
+ return extract_section(
581
+
582
+ text,
583
+
584
+ "Explanation",
585
+
586
+ [
587
+ "Recommendation",
588
+ "Fault Severity",
589
+ ],
590
+ )
591
+
592
+
593
+ # ============================================================
594
+ # RECOMMENDATION
595
+ # ============================================================
596
+
597
+ def extract_recommendation(text):
598
+
599
+ return extract_section(
600
+
601
+ text,
602
+
603
+ "Recommendation",
604
+
605
+ [
606
+ "Fault Severity",
607
+ ],
608
+ )
609
+
610
+
611
+ # ============================================================
612
+ # SEVERITY
613
+ # ============================================================
614
+
615
+ def extract_severity(text):
616
+
617
+ if not text:
618
+
619
+ return None
620
+
621
+ patterns = [
622
+
623
+ r"(?im)^\s*Fault\s+Severity\s*[:\-]?\s*([012])\b",
624
+
625
+ r"(?im)^\s*fault_severity\s*[:=]\s*([012])\b",
626
+
627
+ r"(?im)^\s*Severity\s*[:\-]?\s*([012])\b",
628
+
629
+ ]
630
+
631
+ for pattern in patterns:
632
+
633
+ match = re.search(
634
+ pattern,
635
+ str(text),
636
+ )
637
+
638
+ if match:
639
+
640
+ return int(
641
+ match.group(1)
642
+ )
643
+
644
+ return None
645
+
646
+
647
+ # ============================================================
648
+ # FOUR-OUTPUT FORMAT
649
+ # ============================================================
650
+
651
+ def format_compliant(text):
652
+
653
+ if not text:
654
+
655
+ return False
656
+
657
+ required_sections = [
658
+
659
+ "Probable Root Cause",
660
+
661
+ "Explanation",
662
+
663
+ "Recommendation",
664
+
665
+ "Fault Severity",
666
+
667
+ ]
668
+
669
+ lower_text = text.lower()
670
+
671
+ for section in required_sections:
672
+
673
+ if section.lower() not in lower_text:
674
+
675
+ return False
676
+
677
+ return True
678
+
679
+
680
+ # ============================================================
681
+ # TOKEN NORMALIZATION
682
+ # ============================================================
683
+
684
+ def normalize_tokens(text):
685
+
686
+ if not text:
687
+
688
+ return []
689
+
690
+ text = str(text).lower()
691
+
692
+ text = re.sub(
693
+ r"[^\w\s]",
694
+ " ",
695
+ text,
696
+ )
697
+
698
+ return text.split()
699
+
700
+
701
+ # ============================================================
702
+ # TOKEN F1
703
+ # ============================================================
704
+
705
+ def token_f1(
706
+ prediction,
707
+ reference,
708
+ ):
709
+
710
+ pred_tokens = normalize_tokens(
711
+ prediction
712
+ )
713
+
714
+ ref_tokens = normalize_tokens(
715
+ reference
716
+ )
717
+
718
+ if (
719
+ not pred_tokens
720
+ and
721
+ not ref_tokens
722
+ ):
723
+
724
+ return 1.0
725
+
726
+ if (
727
+ not pred_tokens
728
+ or
729
+ not ref_tokens
730
+ ):
731
+
732
+ return 0.0
733
+
734
+ pred_counts = Counter(
735
+ pred_tokens
736
+ )
737
+
738
+ ref_counts = Counter(
739
+ ref_tokens
740
+ )
741
+
742
+ common = sum(
743
+ (
744
+ pred_counts
745
+ &
746
+ ref_counts
747
+ ).values()
748
+ )
749
+
750
+ if common == 0:
751
+
752
+ return 0.0
753
+
754
+ precision = (
755
+ common
756
+ /
757
+ len(pred_tokens)
758
+ )
759
+
760
+ recall = (
761
+ common
762
+ /
763
+ len(ref_tokens)
764
+ )
765
+
766
+ if precision + recall == 0:
767
+
768
+ return 0.0
769
+
770
+ return (
771
+
772
+ 2
773
+ *
774
+ precision
775
+ *
776
+ recall
777
+ /
778
+ (
779
+ precision
780
+ +
781
+ recall
782
+ )
783
+
784
+ )
785
+
786
+
787
+ # ============================================================
788
+ # GENERATION
789
+ # ============================================================
790
+
791
+ def generate_response(
792
+ model,
793
+ prompt,
794
+ ):
795
+
796
+ encoded = tokenizer(
797
+
798
+ prompt,
799
+
800
+ return_tensors="pt",
801
+
802
+ truncation=True,
803
+
804
+ max_length=MAX_INPUT_LENGTH,
805
+ )
806
+
807
+ input_tokens = int(
808
+ encoded["input_ids"].shape[1]
809
+ )
810
+
811
+ # --------------------------------------------------------
812
+ # Move tensors to model device
813
+ # --------------------------------------------------------
814
+
815
+ encoded = {
816
+ key: value.to(model.device)
817
+ for key, value in encoded.items()
818
+ }
819
+
820
+ if torch.cuda.is_available():
821
+
822
+ torch.cuda.synchronize()
823
+
824
+ start_time = time.perf_counter()
825
+
826
+ with torch.inference_mode():
827
+
828
+ output = model.generate(
829
+
830
+ **encoded,
831
+
832
+ max_new_tokens=MAX_NEW_TOKENS,
833
+
834
+ do_sample=False,
835
+
836
+ num_beams=1,
837
+
838
+ use_cache=True,
839
+
840
+ pad_token_id=(
841
+ tokenizer.pad_token_id
842
+ ),
843
+
844
+ eos_token_id=(
845
+ tokenizer.eos_token_id
846
+ ),
847
+ )
848
+
849
+ if torch.cuda.is_available():
850
+
851
+ torch.cuda.synchronize()
852
+
853
+ elapsed = (
854
+ time.perf_counter()
855
+ -
856
+ start_time
857
+ )
858
+
859
+ generated_tokens = output[
860
+ 0
861
+ ][
862
+ input_tokens:
863
+ ]
864
+
865
+ output_token_count = int(
866
+ len(generated_tokens)
867
+ )
868
+
869
+ total_tokens = (
870
+ input_tokens
871
+ +
872
+ output_token_count
873
+ )
874
+
875
+ response = tokenizer.decode(
876
+
877
+ generated_tokens,
878
+
879
+ skip_special_tokens=True,
880
+ ).strip()
881
+
882
+ tokens_per_second = (
883
+
884
+ output_token_count
885
+ /
886
+ elapsed
887
+
888
+ if elapsed > 0
889
+
890
+ else 0.0
891
+ )
892
+
893
+ return {
894
+
895
+ "response": response,
896
+
897
+ "input_tokens": input_tokens,
898
+
899
+ "output_tokens": output_token_count,
900
+
901
+ "total_tokens": total_tokens,
902
+
903
+ "generation_time_seconds": elapsed,
904
+
905
+ "tokens_per_second": tokens_per_second,
906
+ }
907
+
908
+
909
+ # ============================================================
910
+ # EVALUATE MODEL
911
+ # ============================================================
912
+
913
+ def evaluate_model(
914
+ model,
915
+ model_name,
916
+ ):
917
+
918
+ print()
919
+ print("=" * 80)
920
+ print(
921
+ "TESTING:",
922
+ model_name,
923
+ )
924
+ print("=" * 80)
925
+
926
+ results = []
927
+
928
+ total_examples = len(
929
+ dataset
930
+ )
931
+
932
+ for index, example in enumerate(
933
+ dataset
934
+ ):
935
+
936
+ prompt = get_prompt(
937
+ example
938
+ )
939
+
940
+ reference = get_reference(
941
+ example
942
+ )
943
+
944
+ generated = generate_response(
945
+
946
+ model,
947
+
948
+ prompt,
949
+ )
950
+
951
+ prediction = generated[
952
+ "response"
953
+ ]
954
+
955
+ # ----------------------------------------------------
956
+ # Reference sections
957
+ # ----------------------------------------------------
958
+
959
+ reference_root = (
960
+ extract_root_cause(
961
+ reference
962
+ )
963
+ )
964
+
965
+ reference_explanation = (
966
+ extract_explanation(
967
+ reference
968
+ )
969
+ )
970
+
971
+ reference_recommendation = (
972
+ extract_recommendation(
973
+ reference
974
+ )
975
+ )
976
+
977
+ reference_severity = (
978
+ extract_severity(
979
+ reference
980
+ )
981
+ )
982
+
983
+ # ----------------------------------------------------
984
+ # Prediction sections
985
+ # ----------------------------------------------------
986
+
987
+ predicted_root = (
988
+ extract_root_cause(
989
+ prediction
990
+ )
991
+ )
992
+
993
+ predicted_explanation = (
994
+ extract_explanation(
995
+ prediction
996
+ )
997
+ )
998
+
999
+ predicted_recommendation = (
1000
+ extract_recommendation(
1001
+ prediction
1002
+ )
1003
+ )
1004
+
1005
+ predicted_severity = (
1006
+ extract_severity(
1007
+ prediction
1008
+ )
1009
+ )
1010
+
1011
+ # ----------------------------------------------------
1012
+ # Similarity
1013
+ # ----------------------------------------------------
1014
+
1015
+ root_score = token_f1(
1016
+
1017
+ predicted_root,
1018
+
1019
+ reference_root,
1020
+ )
1021
+
1022
+ explanation_score = token_f1(
1023
+
1024
+ predicted_explanation,
1025
+
1026
+ reference_explanation,
1027
+ )
1028
+
1029
+ recommendation_score = token_f1(
1030
+
1031
+ predicted_recommendation,
1032
+
1033
+ reference_recommendation,
1034
+ )
1035
+
1036
+ # ----------------------------------------------------
1037
+ # Severity
1038
+ # ----------------------------------------------------
1039
+
1040
+ severity_correct = (
1041
+
1042
+ predicted_severity is not None
1043
+
1044
+ and
1045
+
1046
+ reference_severity is not None
1047
+
1048
+ and
1049
+
1050
+ predicted_severity
1051
+ ==
1052
+ reference_severity
1053
+ )
1054
+
1055
+ # ----------------------------------------------------
1056
+ # Format
1057
+ # ----------------------------------------------------
1058
+
1059
+ format_ok = format_compliant(
1060
+ prediction
1061
+ )
1062
+
1063
+ # ----------------------------------------------------
1064
+ # Result
1065
+ # ----------------------------------------------------
1066
+
1067
+ row = {
1068
+
1069
+ "index": index + 1,
1070
+
1071
+ "model": model_name,
1072
+
1073
+ "reference_severity": (
1074
+ reference_severity
1075
+ ),
1076
+
1077
+ "predicted_severity": (
1078
+ predicted_severity
1079
+ ),
1080
+
1081
+ "severity_correct": (
1082
+ severity_correct
1083
+ ),
1084
+
1085
+ "format_compliant": (
1086
+ format_ok
1087
+ ),
1088
+
1089
+ "root_cause_f1": (
1090
+ root_score
1091
+ ),
1092
+
1093
+ "explanation_f1": (
1094
+ explanation_score
1095
+ ),
1096
+
1097
+ "recommendation_f1": (
1098
+ recommendation_score
1099
+ ),
1100
+
1101
+ "input_tokens": (
1102
+ generated[
1103
+ "input_tokens"
1104
+ ]
1105
+ ),
1106
+
1107
+ "output_tokens": (
1108
+ generated[
1109
+ "output_tokens"
1110
+ ]
1111
+ ),
1112
+
1113
+ "total_tokens": (
1114
+ generated[
1115
+ "total_tokens"
1116
+ ]
1117
+ ),
1118
+
1119
+ "generation_time_seconds": (
1120
+ generated[
1121
+ "generation_time_seconds"
1122
+ ]
1123
+ ),
1124
+
1125
+ "tokens_per_second": (
1126
+ generated[
1127
+ "tokens_per_second"
1128
+ ]
1129
+ ),
1130
+
1131
+ "reference": reference,
1132
+
1133
+ "prediction": prediction,
1134
+
1135
+ "reference_root_cause": (
1136
+ reference_root
1137
+ ),
1138
+
1139
+ "predicted_root_cause": (
1140
+ predicted_root
1141
+ ),
1142
+
1143
+ "reference_explanation": (
1144
+ reference_explanation
1145
+ ),
1146
+
1147
+ "predicted_explanation": (
1148
+ predicted_explanation
1149
+ ),
1150
+
1151
+ "reference_recommendation": (
1152
+ reference_recommendation
1153
+ ),
1154
+
1155
+ "predicted_recommendation": (
1156
+ predicted_recommendation
1157
+ ),
1158
+ }
1159
+
1160
+ results.append(row)
1161
+
1162
+ # ----------------------------------------------------
1163
+ # Debug
1164
+ # ----------------------------------------------------
1165
+
1166
+ if args.debug:
1167
+
1168
+ print()
1169
+ print("-" * 80)
1170
+
1171
+ print(
1172
+ "Example:",
1173
+ index + 1,
1174
+ )
1175
+
1176
+ print()
1177
+ print(
1178
+ "REFERENCE:"
1179
+ )
1180
+
1181
+ print(reference)
1182
+
1183
+ print()
1184
+ print(
1185
+ "PREDICTION:"
1186
+ )
1187
+
1188
+ print(prediction)
1189
+
1190
+ print()
1191
+ print(
1192
+ "Severity:",
1193
+ reference_severity,
1194
+ "->",
1195
+ predicted_severity,
1196
+ )
1197
+
1198
+ print(
1199
+ "Root Cause F1:",
1200
+ f"{root_score:.4f}",
1201
+ )
1202
+
1203
+ print(
1204
+ "Explanation F1:",
1205
+ f"{explanation_score:.4f}",
1206
+ )
1207
+
1208
+ print(
1209
+ "Recommendation F1:",
1210
+ f"{recommendation_score:.4f}",
1211
+ )
1212
+
1213
+ print(
1214
+ "Format:",
1215
+ format_ok,
1216
+ )
1217
+
1218
+ print(
1219
+ "Tokens:",
1220
+ generated[
1221
+ "input_tokens"
1222
+ ],
1223
+ "/",
1224
+ generated[
1225
+ "output_tokens"
1226
+ ],
1227
+ "/",
1228
+ generated[
1229
+ "total_tokens"
1230
+ ],
1231
+ )
1232
+
1233
+ print(
1234
+ "Time:",
1235
+ f"{generated['generation_time_seconds']:.3f}s",
1236
+ )
1237
+
1238
+ else:
1239
+
1240
+ if (
1241
+
1242
+ (index + 1) % 10 == 0
1243
+
1244
+ or
1245
+
1246
+ (index + 1)
1247
+ ==
1248
+ total_examples
1249
+
1250
+ ):
1251
+
1252
+ print(
1253
+
1254
+ f"{model_name}: "
1255
+ f"{index + 1}/"
1256
+ f"{total_examples}"
1257
+
1258
+ )
1259
+
1260
+ return results
1261
+
1262
+
1263
+ # ============================================================
1264
+ # RUN ORIGINAL
1265
+ # ============================================================
1266
+
1267
+ original_results = evaluate_model(
1268
+
1269
+ base_model,
1270
+
1271
+ "Original",
1272
+ )
1273
+
1274
+
1275
+ # ============================================================
1276
+ # RUN FINE-TUNED
1277
+ # ============================================================
1278
+
1279
+ fine_tuned_results = evaluate_model(
1280
+
1281
+ fine_tuned_model,
1282
+
1283
+ "Fine-tuned",
1284
+ )
1285
+
1286
+
1287
+ # ============================================================
1288
+ # AVERAGE
1289
+ # ============================================================
1290
+
1291
+ def average(
1292
+ rows,
1293
+ key,
1294
+ ):
1295
+
1296
+ if not rows:
1297
+
1298
+ return 0.0
1299
+
1300
+ values = [
1301
+
1302
+ float(row[key])
1303
+
1304
+ for row in rows
1305
+
1306
+ if isinstance(
1307
+ row[key],
1308
+ (int, float),
1309
+ )
1310
+
1311
+ ]
1312
+
1313
+ if not values:
1314
+
1315
+ return 0.0
1316
+
1317
+ return (
1318
+ sum(values)
1319
+ /
1320
+ len(values)
1321
+ )
1322
+
1323
+
1324
+ # ============================================================
1325
+ # ACCURACY
1326
+ # ============================================================
1327
+
1328
+ def severity_accuracy(
1329
+ rows,
1330
+ ):
1331
+
1332
+ if not rows:
1333
+
1334
+ return 0.0
1335
+
1336
+ correct = sum(
1337
+
1338
+ 1
1339
+
1340
+ for row in rows
1341
+
1342
+ if row[
1343
+ "severity_correct"
1344
+ ]
1345
+
1346
+ )
1347
+
1348
+ return (
1349
+ correct
1350
+ /
1351
+ len(rows)
1352
+ )
1353
+
1354
+
1355
+ # ============================================================
1356
+ # FORMAT ACCURACY
1357
+ # ============================================================
1358
+
1359
+ def format_accuracy(
1360
+ rows,
1361
+ ):
1362
+
1363
+ if not rows:
1364
+
1365
+ return 0.0
1366
+
1367
+ correct = sum(
1368
+
1369
+ 1
1370
+
1371
+ for row in rows
1372
+
1373
+ if row[
1374
+ "format_compliant"
1375
+ ]
1376
+
1377
+ )
1378
+
1379
+ return (
1380
+ correct
1381
+ /
1382
+ len(rows)
1383
+ )
1384
+
1385
+
1386
+ # ============================================================
1387
+ # CLASSIFICATION METRICS
1388
+ # ============================================================
1389
+
1390
+ def classification_metrics(
1391
+ rows,
1392
+ ):
1393
+
1394
+ labels = [0, 1, 2]
1395
+
1396
+ matrix = {
1397
+
1398
+ actual: {
1399
+
1400
+ predicted: 0
1401
+
1402
+ for predicted in labels
1403
+
1404
+ }
1405
+
1406
+ for actual in labels
1407
+ }
1408
+
1409
+ for row in rows:
1410
+
1411
+ actual = row[
1412
+ "reference_severity"
1413
+ ]
1414
+
1415
+ predicted = row[
1416
+ "predicted_severity"
1417
+ ]
1418
+
1419
+ if (
1420
+
1421
+ actual in labels
1422
+
1423
+ and
1424
+
1425
+ predicted in labels
1426
+
1427
+ ):
1428
+
1429
+ matrix[
1430
+ actual
1431
+ ][
1432
+ predicted
1433
+ ] += 1
1434
+
1435
+ metrics = {}
1436
+
1437
+ for label in labels:
1438
+
1439
+ true_positive = matrix[
1440
+ label
1441
+ ][
1442
+ label
1443
+ ]
1444
+
1445
+ false_positive = sum(
1446
+
1447
+ matrix[
1448
+ actual
1449
+ ][
1450
+ label
1451
+ ]
1452
+
1453
+ for actual in labels
1454
+
1455
+ if actual != label
1456
+ )
1457
+
1458
+ false_negative = sum(
1459
+
1460
+ matrix[
1461
+ label
1462
+ ][
1463
+ predicted
1464
+ ]
1465
+
1466
+ for predicted in labels
1467
+
1468
+ if predicted != label
1469
+ )
1470
+
1471
+ support = sum(
1472
+ matrix[
1473
+ label
1474
+ ].values()
1475
+ )
1476
+
1477
+ precision = (
1478
+
1479
+ true_positive
1480
+ /
1481
+ (
1482
+ true_positive
1483
+ +
1484
+ false_positive
1485
+ )
1486
+
1487
+ if (
1488
+ true_positive
1489
+ +
1490
+ false_positive
1491
+ ) > 0
1492
+
1493
+ else 0.0
1494
+ )
1495
+
1496
+ recall = (
1497
+
1498
+ true_positive
1499
+ /
1500
+ (
1501
+ true_positive
1502
+ +
1503
+ false_negative
1504
+ )
1505
+
1506
+ if (
1507
+ true_positive
1508
+ +
1509
+ false_negative
1510
+ ) > 0
1511
+
1512
+ else 0.0
1513
+ )
1514
+
1515
+ f1 = (
1516
+
1517
+ 2
1518
+ *
1519
+ precision
1520
+ *
1521
+ recall
1522
+ /
1523
+ (
1524
+ precision
1525
+ +
1526
+ recall
1527
+ )
1528
+
1529
+ if (
1530
+ precision
1531
+ +
1532
+ recall
1533
+ ) > 0
1534
+
1535
+ else 0.0
1536
+ )
1537
+
1538
+ metrics[label] = {
1539
+
1540
+ "precision": precision,
1541
+
1542
+ "recall": recall,
1543
+
1544
+ "f1": f1,
1545
+
1546
+ "support": support,
1547
+ }
1548
+
1549
+ valid_f1 = [
1550
+
1551
+ metrics[label]["f1"]
1552
+
1553
+ for label in labels
1554
+
1555
+ if metrics[label]["support"] > 0
1556
+ ]
1557
+
1558
+ macro_f1 = (
1559
+
1560
+ sum(valid_f1)
1561
+ /
1562
+ len(valid_f1)
1563
+
1564
+ if valid_f1
1565
+
1566
+ else 0.0
1567
+ )
1568
+
1569
+ total_support = sum(
1570
+
1571
+ metrics[label]["support"]
1572
+
1573
+ for label in labels
1574
+ )
1575
+
1576
+ weighted_f1 = (
1577
+
1578
+ sum(
1579
+
1580
+ metrics[label]["f1"]
1581
+ *
1582
+ metrics[label]["support"]
1583
+
1584
+ for label in labels
1585
+ )
1586
+
1587
+ /
1588
+ total_support
1589
+
1590
+ if total_support > 0
1591
+
1592
+ else 0.0
1593
+ )
1594
+
1595
+ return (
1596
+
1597
+ metrics,
1598
+
1599
+ matrix,
1600
+
1601
+ macro_f1,
1602
+
1603
+ weighted_f1,
1604
+ )
1605
+
1606
+
1607
+ # ============================================================
1608
+ # SUMMARY VALUES
1609
+ # ============================================================
1610
+
1611
+ original_accuracy = severity_accuracy(
1612
+ original_results
1613
+ )
1614
+
1615
+ fine_tuned_accuracy = severity_accuracy(
1616
+ fine_tuned_results
1617
+ )
1618
+
1619
+ original_format = format_accuracy(
1620
+ original_results
1621
+ )
1622
+
1623
+ fine_tuned_format = format_accuracy(
1624
+ fine_tuned_results
1625
+ )
1626
+
1627
+ original_root = average(
1628
+ original_results,
1629
+ "root_cause_f1",
1630
+ )
1631
+
1632
+ fine_tuned_root = average(
1633
+ fine_tuned_results,
1634
+ "root_cause_f1",
1635
+ )
1636
+
1637
+ original_explanation = average(
1638
+ original_results,
1639
+ "explanation_f1",
1640
+ )
1641
+
1642
+ fine_tuned_explanation = average(
1643
+ fine_tuned_results,
1644
+ "explanation_f1",
1645
+ )
1646
+
1647
+ original_recommendation = average(
1648
+ original_results,
1649
+ "recommendation_f1",
1650
+ )
1651
+
1652
+ fine_tuned_recommendation = average(
1653
+ fine_tuned_results,
1654
+ "recommendation_f1",
1655
+ )
1656
+
1657
+ original_input = average(
1658
+ original_results,
1659
+ "input_tokens",
1660
+ )
1661
+
1662
+ fine_tuned_input = average(
1663
+ fine_tuned_results,
1664
+ "input_tokens",
1665
+ )
1666
+
1667
+ original_output = average(
1668
+ original_results,
1669
+ "output_tokens",
1670
+ )
1671
+
1672
+ fine_tuned_output = average(
1673
+ fine_tuned_results,
1674
+ "output_tokens",
1675
+ )
1676
+
1677
+ original_total = average(
1678
+ original_results,
1679
+ "total_tokens",
1680
+ )
1681
+
1682
+ fine_tuned_total = average(
1683
+ fine_tuned_results,
1684
+ "total_tokens",
1685
+ )
1686
+
1687
+ original_time = average(
1688
+ original_results,
1689
+ "generation_time_seconds",
1690
+ )
1691
+
1692
+ fine_tuned_time = average(
1693
+ fine_tuned_results,
1694
+ "generation_time_seconds",
1695
+ )
1696
+
1697
+ original_speed = average(
1698
+ original_results,
1699
+ "tokens_per_second",
1700
+ )
1701
+
1702
+ fine_tuned_speed = average(
1703
+ fine_tuned_results,
1704
+ "tokens_per_second",
1705
+ )
1706
+
1707
+
1708
+ (
1709
+ original_classes,
1710
+ original_matrix,
1711
+ original_macro_f1,
1712
+ original_weighted_f1,
1713
+ ) = classification_metrics(
1714
+ original_results
1715
+ )
1716
+
1717
+
1718
+ (
1719
+ fine_tuned_classes,
1720
+ fine_tuned_matrix,
1721
+ fine_tuned_macro_f1,
1722
+ fine_tuned_weighted_f1,
1723
+ ) = classification_metrics(
1724
+ fine_tuned_results
1725
+ )
1726
+
1727
+
1728
+ # ============================================================
1729
+ # PRINT QUALITY COMPARISON
1730
+ # ============================================================
1731
+
1732
+ print()
1733
+ print("=" * 80)
1734
+ print("FAST QUALITY COMPARISON")
1735
+ print("=" * 80)
1736
+
1737
+ print()
1738
+
1739
+ print(
1740
+
1741
+ f"{'Metric':<32}"
1742
+ f"{'Original':>15}"
1743
+ f"{'Fine-tuned':>15}"
1744
+ f"{'Change':>15}"
1745
+
1746
+ )
1747
+
1748
+ print("-" * 80)
1749
+
1750
+
1751
+ def print_metric(
1752
+ name,
1753
+ original,
1754
+ fine_tuned,
1755
+ percent=False,
1756
+ ):
1757
+
1758
+ change = (
1759
+ fine_tuned
1760
+ -
1761
+ original
1762
+ )
1763
+
1764
+ if percent:
1765
+
1766
+ print(
1767
+
1768
+ f"{name:<32}"
1769
+ f"{original * 100:>14.2f}%"
1770
+ f"{fine_tuned * 100:>14.2f}%"
1771
+ f"{change * 100:>+14.2f}%"
1772
+
1773
+ )
1774
+
1775
+ else:
1776
+
1777
+ print(
1778
+
1779
+ f"{name:<32}"
1780
+ f"{original:>15.4f}"
1781
+ f"{fine_tuned:>15.4f}"
1782
+ f"{change:>+15.4f}"
1783
+
1784
+ )
1785
+
1786
+
1787
+ print_metric(
1788
+
1789
+ "Severity Accuracy",
1790
+
1791
+ original_accuracy,
1792
+
1793
+ fine_tuned_accuracy,
1794
+
1795
+ percent=True,
1796
+ )
1797
+
1798
+ print_metric(
1799
+
1800
+ "Severity Macro F1",
1801
+
1802
+ original_macro_f1,
1803
+
1804
+ fine_tuned_macro_f1,
1805
+ )
1806
+
1807
+ print_metric(
1808
+
1809
+ "Severity Weighted F1",
1810
+
1811
+ original_weighted_f1,
1812
+
1813
+ fine_tuned_weighted_f1,
1814
+ )
1815
+
1816
+ print_metric(
1817
+
1818
+ "Root Cause Token-F1",
1819
+
1820
+ original_root,
1821
+
1822
+ fine_tuned_root,
1823
+ )
1824
+
1825
+ print_metric(
1826
+
1827
+ "Explanation Token-F1",
1828
+
1829
+ original_explanation,
1830
+
1831
+ fine_tuned_explanation,
1832
+ )
1833
+
1834
+ print_metric(
1835
+
1836
+ "Recommendation Token-F1",
1837
+
1838
+ original_recommendation,
1839
+
1840
+ fine_tuned_recommendation,
1841
+ )
1842
+
1843
+ print_metric(
1844
+
1845
+ "Four-output Format",
1846
+
1847
+ original_format,
1848
+
1849
+ fine_tuned_format,
1850
+
1851
+ percent=True,
1852
+ )
1853
+
1854
+
1855
+ # ============================================================
1856
+ # TOKEN USAGE
1857
+ # ============================================================
1858
+
1859
+ print()
1860
+ print("=" * 80)
1861
+ print("TOKEN USAGE AND SPEED")
1862
+ print("=" * 80)
1863
+
1864
+ print()
1865
+
1866
+ print_metric(
1867
+
1868
+ "Average Input Tokens",
1869
+
1870
+ original_input,
1871
+
1872
+ fine_tuned_input,
1873
+ )
1874
+
1875
+ print_metric(
1876
+
1877
+ "Average Output Tokens",
1878
+
1879
+ original_output,
1880
+
1881
+ fine_tuned_output,
1882
+ )
1883
+
1884
+ print_metric(
1885
+
1886
+ "Average Total Tokens",
1887
+
1888
+ original_total,
1889
+
1890
+ fine_tuned_total,
1891
+ )
1892
+
1893
+ print_metric(
1894
+
1895
+ "Average Generation Time",
1896
+
1897
+ original_time,
1898
+
1899
+ fine_tuned_time,
1900
+ )
1901
+
1902
+ print_metric(
1903
+
1904
+ "Average Tokens / Second",
1905
+
1906
+ original_speed,
1907
+
1908
+ fine_tuned_speed,
1909
+ )
1910
+
1911
+
1912
+ # ============================================================
1913
+ # CLASS METRICS
1914
+ # ============================================================
1915
+
1916
+ print()
1917
+ print("=" * 80)
1918
+ print("FAULT SEVERITY CLASS METRICS")
1919
+ print("=" * 80)
1920
+
1921
+ for label in [0, 1, 2]:
1922
+
1923
+ print()
1924
+ print(
1925
+ f"CLASS {label}"
1926
+ )
1927
+
1928
+ print()
1929
+
1930
+ print(
1931
+ "Original:"
1932
+ )
1933
+
1934
+ print(
1935
+
1936
+ f" Precision = "
1937
+ f"{original_classes[label]['precision']:.4f}"
1938
+
1939
+ )
1940
+
1941
+ print(
1942
+
1943
+ f" Recall = "
1944
+ f"{original_classes[label]['recall']:.4f}"
1945
+
1946
+ )
1947
+
1948
+ print(
1949
+
1950
+ f" F1 = "
1951
+ f"{original_classes[label]['f1']:.4f}"
1952
+
1953
+ )
1954
+
1955
+ print(
1956
+
1957
+ f" Support = "
1958
+ f"{original_classes[label]['support']}"
1959
+
1960
+ )
1961
+
1962
+ print()
1963
+
1964
+ print(
1965
+ "Fine-tuned:"
1966
+ )
1967
+
1968
+ print(
1969
+
1970
+ f" Precision = "
1971
+ f"{fine_tuned_classes[label]['precision']:.4f}"
1972
+
1973
+ )
1974
+
1975
+ print(
1976
+
1977
+ f" Recall = "
1978
+ f"{fine_tuned_classes[label]['recall']:.4f}"
1979
+
1980
+ )
1981
+
1982
+ print(
1983
+
1984
+ f" F1 = "
1985
+ f"{fine_tuned_classes[label]['f1']:.4f}"
1986
+
1987
+ )
1988
+
1989
+ print(
1990
+
1991
+ f" Support = "
1992
+ f"{fine_tuned_classes[label]['support']}"
1993
+
1994
+ )
1995
+
1996
+
1997
+ # ============================================================
1998
+ # CONFUSION MATRIX
1999
+ # ============================================================
2000
+
2001
+ def print_confusion_matrix(
2002
+ matrix,
2003
+ title,
2004
+ ):
2005
+
2006
+ print()
2007
+ print(title)
2008
+
2009
+ print()
2010
+
2011
+ print(
2012
+ " Pred 0 Pred 1 Pred 2"
2013
+ )
2014
+
2015
+ for actual in [0, 1, 2]:
2016
+
2017
+ print(
2018
+
2019
+ f"Actual {actual}"
2020
+ f"{matrix[actual][0]:>12}"
2021
+ f"{matrix[actual][1]:>10}"
2022
+ f"{matrix[actual][2]:>10}"
2023
+
2024
+ )
2025
+
2026
+
2027
+ print_confusion_matrix(
2028
+
2029
+ original_matrix,
2030
+
2031
+ "Original confusion matrix:",
2032
+ )
2033
+
2034
+ print_confusion_matrix(
2035
+
2036
+ fine_tuned_matrix,
2037
+
2038
+ "Fine-tuned confusion matrix:",
2039
+ )
2040
+
2041
+
2042
+ # ============================================================
2043
+ # TOKEN RANGES
2044
+ # ============================================================
2045
+
2046
+ def token_range(
2047
+ rows,
2048
+ key,
2049
+ ):
2050
+
2051
+ values = [
2052
+
2053
+ row[key]
2054
+
2055
+ for row in rows
2056
+
2057
+ ]
2058
+
2059
+ if not values:
2060
+
2061
+ return 0, 0
2062
+
2063
+ return (
2064
+ min(values),
2065
+ max(values),
2066
+ )
2067
+
2068
+
2069
+ print()
2070
+ print("=" * 80)
2071
+ print("TOKEN RANGE")
2072
+ print("=" * 80)
2073
+
2074
+ for key in [
2075
+
2076
+ "input_tokens",
2077
+
2078
+ "output_tokens",
2079
+
2080
+ "total_tokens",
2081
+
2082
+ ]:
2083
+
2084
+ original_min, original_max = (
2085
+ token_range(
2086
+ original_results,
2087
+ key,
2088
+ )
2089
+ )
2090
+
2091
+ fine_tuned_min, fine_tuned_max = (
2092
+ token_range(
2093
+ fine_tuned_results,
2094
+ key,
2095
+ )
2096
+ )
2097
+
2098
+ print()
2099
+ print(key)
2100
+
2101
+ print(
2102
+
2103
+ " Original: "
2104
+ f"{original_min} - "
2105
+ f"{original_max}"
2106
+
2107
+ )
2108
+
2109
+ print(
2110
+
2111
+ " Fine-tuned: "
2112
+ f"{fine_tuned_min} - "
2113
+ f"{fine_tuned_max}"
2114
+
2115
+ )
2116
+
2117
+
2118
+ # ============================================================
2119
+ # SAVE PATHS
2120
+ # ============================================================
2121
+
2122
+ json_path = os.path.join(
2123
+
2124
+ args.output,
2125
+
2126
+ "fast_comparison_results.json",
2127
+ )
2128
+
2129
+ csv_path = os.path.join(
2130
+
2131
+ args.output,
2132
+
2133
+ "fast_comparison_predictions.csv",
2134
+ )
2135
+
2136
+ summary_path = os.path.join(
2137
+
2138
+ args.output,
2139
+
2140
+ "fast_comparison_summary.csv",
2141
+ )
2142
+
2143
+
2144
+ # ============================================================
2145
+ # SAVE JSON
2146
+ # ============================================================
2147
+
2148
+ json_output = {
2149
+
2150
+ "base_model": MODEL_NAME,
2151
+
2152
+ "adapter": os.path.abspath(
2153
+ args.adapter
2154
+ ),
2155
+
2156
+ "test_file": os.path.abspath(
2157
+ args.test
2158
+ ),
2159
+
2160
+ "number_of_examples": len(
2161
+ dataset
2162
+ ),
2163
+
2164
+ "metrics": {
2165
+
2166
+ "severity_accuracy": {
2167
+
2168
+ "original":
2169
+ original_accuracy,
2170
+
2171
+ "fine_tuned":
2172
+ fine_tuned_accuracy,
2173
+
2174
+ "change":
2175
+ fine_tuned_accuracy
2176
+ -
2177
+ original_accuracy,
2178
+ },
2179
+
2180
+ "severity_macro_f1": {
2181
+
2182
+ "original":
2183
+ original_macro_f1,
2184
+
2185
+ "fine_tuned":
2186
+ fine_tuned_macro_f1,
2187
+
2188
+ "change":
2189
+ fine_tuned_macro_f1
2190
+ -
2191
+ original_macro_f1,
2192
+ },
2193
+
2194
+ "severity_weighted_f1": {
2195
+
2196
+ "original":
2197
+ original_weighted_f1,
2198
+
2199
+ "fine_tuned":
2200
+ fine_tuned_weighted_f1,
2201
+
2202
+ "change":
2203
+ fine_tuned_weighted_f1
2204
+ -
2205
+ original_weighted_f1,
2206
+ },
2207
+
2208
+ "root_cause_token_f1": {
2209
+
2210
+ "original":
2211
+ original_root,
2212
+
2213
+ "fine_tuned":
2214
+ fine_tuned_root,
2215
+
2216
+ "change":
2217
+ fine_tuned_root
2218
+ -
2219
+ original_root,
2220
+ },
2221
+
2222
+ "explanation_token_f1": {
2223
+
2224
+ "original":
2225
+ original_explanation,
2226
+
2227
+ "fine_tuned":
2228
+ fine_tuned_explanation,
2229
+
2230
+ "change":
2231
+ fine_tuned_explanation
2232
+ -
2233
+ original_explanation,
2234
+ },
2235
+
2236
+ "recommendation_token_f1": {
2237
+
2238
+ "original":
2239
+ original_recommendation,
2240
+
2241
+ "fine_tuned":
2242
+ fine_tuned_recommendation,
2243
+
2244
+ "change":
2245
+ fine_tuned_recommendation
2246
+ -
2247
+ original_recommendation,
2248
+ },
2249
+
2250
+ "format_compliance": {
2251
+
2252
+ "original":
2253
+ original_format,
2254
+
2255
+ "fine_tuned":
2256
+ fine_tuned_format,
2257
+
2258
+ "change":
2259
+ fine_tuned_format
2260
+ -
2261
+ original_format,
2262
+ },
2263
+ },
2264
+
2265
+ "token_usage": {
2266
+
2267
+ "input_tokens": {
2268
+
2269
+ "original":
2270
+ original_input,
2271
+
2272
+ "fine_tuned":
2273
+ fine_tuned_input,
2274
+ },
2275
+
2276
+ "output_tokens": {
2277
+
2278
+ "original":
2279
+ original_output,
2280
+
2281
+ "fine_tuned":
2282
+ fine_tuned_output,
2283
+ },
2284
+
2285
+ "total_tokens": {
2286
+
2287
+ "original":
2288
+ original_total,
2289
+
2290
+ "fine_tuned":
2291
+ fine_tuned_total,
2292
+ },
2293
+
2294
+ "generation_time_seconds": {
2295
+
2296
+ "original":
2297
+ original_time,
2298
+
2299
+ "fine_tuned":
2300
+ fine_tuned_time,
2301
+ },
2302
+
2303
+ "tokens_per_second": {
2304
+
2305
+ "original":
2306
+ original_speed,
2307
+
2308
+ "fine_tuned":
2309
+ fine_tuned_speed,
2310
+ },
2311
+ },
2312
+
2313
+ "class_metrics": {
2314
+
2315
+ "original":
2316
+ original_classes,
2317
+
2318
+ "fine_tuned":
2319
+ fine_tuned_classes,
2320
+ },
2321
+
2322
+ "confusion_matrix": {
2323
+
2324
+ "original":
2325
+ original_matrix,
2326
+
2327
+ "fine_tuned":
2328
+ fine_tuned_matrix,
2329
+ },
2330
+
2331
+ "predictions": {
2332
+
2333
+ "original":
2334
+ original_results,
2335
+
2336
+ "fine_tuned":
2337
+ fine_tuned_results,
2338
+ },
2339
+ }
2340
+
2341
+
2342
+ with open(
2343
+
2344
+ json_path,
2345
+
2346
+ "w",
2347
+
2348
+ encoding="utf-8",
2349
+
2350
+ ) as file:
2351
+
2352
+ json.dump(
2353
+
2354
+ json_output,
2355
+
2356
+ file,
2357
+
2358
+ indent=2,
2359
+
2360
+ ensure_ascii=False,
2361
+ )
2362
+
2363
+
2364
+ # ============================================================
2365
+ # SAVE PREDICTIONS CSV
2366
+ # ============================================================
2367
+
2368
+ combined_rows = []
2369
+
2370
+ for original, fine_tuned in zip(
2371
+
2372
+ original_results,
2373
+
2374
+ fine_tuned_results,
2375
+
2376
+ ):
2377
+
2378
+ combined_rows.append({
2379
+
2380
+ "index":
2381
+ original["index"],
2382
+
2383
+ "reference_severity":
2384
+ original[
2385
+ "reference_severity"
2386
+ ],
2387
+
2388
+ "original_severity":
2389
+ original[
2390
+ "predicted_severity"
2391
+ ],
2392
+
2393
+ "fine_tuned_severity":
2394
+ fine_tuned[
2395
+ "predicted_severity"
2396
+ ],
2397
+
2398
+ "original_correct":
2399
+ original[
2400
+ "severity_correct"
2401
+ ],
2402
+
2403
+ "fine_tuned_correct":
2404
+ fine_tuned[
2405
+ "severity_correct"
2406
+ ],
2407
+
2408
+ "original_format":
2409
+ original[
2410
+ "format_compliant"
2411
+ ],
2412
+
2413
+ "fine_tuned_format":
2414
+ fine_tuned[
2415
+ "format_compliant"
2416
+ ],
2417
+
2418
+ "original_root_f1":
2419
+ original[
2420
+ "root_cause_f1"
2421
+ ],
2422
+
2423
+ "fine_tuned_root_f1":
2424
+ fine_tuned[
2425
+ "root_cause_f1"
2426
+ ],
2427
+
2428
+ "original_explanation_f1":
2429
+ original[
2430
+ "explanation_f1"
2431
+ ],
2432
+
2433
+ "fine_tuned_explanation_f1":
2434
+ fine_tuned[
2435
+ "explanation_f1"
2436
+ ],
2437
+
2438
+ "original_recommendation_f1":
2439
+ original[
2440
+ "recommendation_f1"
2441
+ ],
2442
+
2443
+ "fine_tuned_recommendation_f1":
2444
+ fine_tuned[
2445
+ "recommendation_f1"
2446
+ ],
2447
+
2448
+ "original_input_tokens":
2449
+ original[
2450
+ "input_tokens"
2451
+ ],
2452
+
2453
+ "fine_tuned_input_tokens":
2454
+ fine_tuned[
2455
+ "input_tokens"
2456
+ ],
2457
+
2458
+ "original_output_tokens":
2459
+ original[
2460
+ "output_tokens"
2461
+ ],
2462
+
2463
+ "fine_tuned_output_tokens":
2464
+ fine_tuned[
2465
+ "output_tokens"
2466
+ ],
2467
+
2468
+ "original_total_tokens":
2469
+ original[
2470
+ "total_tokens"
2471
+ ],
2472
+
2473
+ "fine_tuned_total_tokens":
2474
+ fine_tuned[
2475
+ "total_tokens"
2476
+ ],
2477
+
2478
+ "original_time_seconds":
2479
+ original[
2480
+ "generation_time_seconds"
2481
+ ],
2482
+
2483
+ "fine_tuned_time_seconds":
2484
+ fine_tuned[
2485
+ "generation_time_seconds"
2486
+ ],
2487
+
2488
+ "original_tokens_per_second":
2489
+ original[
2490
+ "tokens_per_second"
2491
+ ],
2492
+
2493
+ "fine_tuned_tokens_per_second":
2494
+ fine_tuned[
2495
+ "tokens_per_second"
2496
+ ],
2497
+
2498
+ "reference":
2499
+ original[
2500
+ "reference"
2501
+ ],
2502
+
2503
+ "original_prediction":
2504
+ original[
2505
+ "prediction"
2506
+ ],
2507
+
2508
+ "fine_tuned_prediction":
2509
+ fine_tuned[
2510
+ "prediction"
2511
+ ],
2512
+ })
2513
+
2514
+
2515
+ if combined_rows:
2516
+
2517
+ with open(
2518
+
2519
+ csv_path,
2520
+
2521
+ "w",
2522
+
2523
+ newline="",
2524
+
2525
+ encoding="utf-8",
2526
+
2527
+ ) as file:
2528
+
2529
+ writer = csv.DictWriter(
2530
+
2531
+ file,
2532
+
2533
+ fieldnames=list(
2534
+ combined_rows[0].keys()
2535
+ ),
2536
+ )
2537
+
2538
+ writer.writeheader()
2539
+
2540
+ writer.writerows(
2541
+ combined_rows
2542
+ )
2543
+
2544
+
2545
+ # ============================================================
2546
+ # SUMMARY CSV
2547
+ # ============================================================
2548
+
2549
+ summary_rows = [
2550
+
2551
+ [
2552
+ "Severity Accuracy",
2553
+ original_accuracy,
2554
+ fine_tuned_accuracy,
2555
+ fine_tuned_accuracy
2556
+ -
2557
+ original_accuracy,
2558
+ ],
2559
+
2560
+ [
2561
+ "Severity Macro F1",
2562
+ original_macro_f1,
2563
+ fine_tuned_macro_f1,
2564
+ fine_tuned_macro_f1
2565
+ -
2566
+ original_macro_f1,
2567
+ ],
2568
+
2569
+ [
2570
+ "Severity Weighted F1",
2571
+ original_weighted_f1,
2572
+ fine_tuned_weighted_f1,
2573
+ fine_tuned_weighted_f1
2574
+ -
2575
+ original_weighted_f1,
2576
+ ],
2577
+
2578
+ [
2579
+ "Root Cause Token-F1",
2580
+ original_root,
2581
+ fine_tuned_root,
2582
+ fine_tuned_root
2583
+ -
2584
+ original_root,
2585
+ ],
2586
+
2587
+ [
2588
+ "Explanation Token-F1",
2589
+ original_explanation,
2590
+ fine_tuned_explanation,
2591
+ fine_tuned_explanation
2592
+ -
2593
+ original_explanation,
2594
+ ],
2595
+
2596
+ [
2597
+ "Recommendation Token-F1",
2598
+ original_recommendation,
2599
+ fine_tuned_recommendation,
2600
+ fine_tuned_recommendation
2601
+ -
2602
+ original_recommendation,
2603
+ ],
2604
+
2605
+ [
2606
+ "Format Compliance",
2607
+ original_format,
2608
+ fine_tuned_format,
2609
+ fine_tuned_format
2610
+ -
2611
+ original_format,
2612
+ ],
2613
+
2614
+ [
2615
+ "Average Input Tokens",
2616
+ original_input,
2617
+ fine_tuned_input,
2618
+ fine_tuned_input
2619
+ -
2620
+ original_input,
2621
+ ],
2622
+
2623
+ [
2624
+ "Average Output Tokens",
2625
+ original_output,
2626
+ fine_tuned_output,
2627
+ fine_tuned_output
2628
+ -
2629
+ original_output,
2630
+ ],
2631
+
2632
+ [
2633
+ "Average Total Tokens",
2634
+ original_total,
2635
+ fine_tuned_total,
2636
+ fine_tuned_total
2637
+ -
2638
+ original_total,
2639
+ ],
2640
+
2641
+ [
2642
+ "Average Generation Time",
2643
+ original_time,
2644
+ fine_tuned_time,
2645
+ fine_tuned_time
2646
+ -
2647
+ original_time,
2648
+ ],
2649
+
2650
+ [
2651
+ "Average Tokens / Second",
2652
+ original_speed,
2653
+ fine_tuned_speed,
2654
+ fine_tuned_speed
2655
+ -
2656
+ original_speed,
2657
+ ],
2658
+ ]
2659
+
2660
+
2661
+ with open(
2662
+
2663
+ summary_path,
2664
+
2665
+ "w",
2666
+
2667
+ newline="",
2668
+
2669
+ encoding="utf-8",
2670
+
2671
+ ) as file:
2672
+
2673
+ writer = csv.writer(
2674
+ file
2675
+ )
2676
+
2677
+ writer.writerow([
2678
+
2679
+ "Metric",
2680
+
2681
+ "Original",
2682
+
2683
+ "Fine-tuned",
2684
+
2685
+ "Change",
2686
+
2687
+ ])
2688
+
2689
+ writer.writerows(
2690
+ summary_rows
2691
+ )
2692
+
2693
+
2694
+ # ============================================================
2695
+ # FINAL MESSAGE
2696
+ # ============================================================
2697
+
2698
+ print()
2699
+ print("=" * 80)
2700
+ print("COMPARISON COMPLETE")
2701
+ print("=" * 80)
2702
+
2703
+ print()
2704
+
2705
+ print(
2706
+ "Examples tested:",
2707
+ len(dataset),
2708
+ )
2709
+
2710
+ print()
2711
+
2712
+ print(
2713
+ "Detailed predictions:"
2714
+ )
2715
+
2716
+ print(
2717
+ os.path.abspath(
2718
+ csv_path
2719
+ )
2720
+ )
2721
+
2722
+ print()
2723
+
2724
+ print(
2725
+ "Summary:"
2726
+ )
2727
+
2728
+ print(
2729
+ os.path.abspath(
2730
+ summary_path
2731
+ )
2732
+ )
2733
+
2734
+ print()
2735
+
2736
+ print(
2737
+ "JSON:"
2738
+ )
2739
+
2740
+ print(
2741
+ os.path.abspath(
2742
+ json_path
2743
+ )
2744
+ )
2745
+
2746
+ print()
2747
+ print("=" * 80)
2748
+ print("IMPORTANT")
2749
+ print("=" * 80)
2750
+
2751
+ print(
2752
+ "This is an objective reference-based evaluation."
2753
+ )
2754
+
2755
+ print()
2756
+
2757
+ print(
2758
+ "Token-F1 measures similarity to the "
2759
+ "reference response. It does not prove "
2760
+ "real-world telecom engineering correctness."
2761
+ )
2762
+
2763
+ print()
2764
+
2765
+ print(
2766
+ "Relevance, Coherence, Faithfulness and "
2767
+ "Helpfulness are intentionally not estimated "
2768
+ "by the 1.5B model itself."
2769
+ )
2770
+
2771
+ print()
2772
+
2773
+ print(
2774
+ "For those qualities, use engineer validation "
2775
+ "or a separate stronger evaluation model."
2776
+ )
2777
+
2778
+ print("=" * 80)
2779
+
2780
+
2781
+ # ============================================================
2782
+ # CLEANUP
2783
+ # ============================================================
2784
+
2785
+ try:
2786
+
2787
+ del fine_tuned_model
2788
+
2789
+ except Exception:
2790
+
2791
+ pass
2792
+
2793
+ try:
2794
+
2795
+ del base_model
2796
+
2797
+ except Exception:
2798
+
2799
+ pass
2800
+
2801
+ gc.collect()
2802
+
2803
+ if torch.cuda.is_available():
2804
+
2805
+ torch.cuda.empty_cache()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ torch
2
+ transformers
3
+ datasets
4
+ peft
5
+ trl
6
+ bitsandbytes
7
+ accelerate
8
+ scikit-learn
run_all.bat ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ @echo off
2
+ python train.py
3
+ python test.py --adapter "models/telecom-qwen-four-output" --test "sample/data/test_four_output.jsonl" --samples 0
run_all.sh ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -e
3
+ python train.py
4
+ python test.py --adapter "models/telecom-qwen-four-output" --test "sample/data/test_four_output.jsonl" --samples 0
test.py ADDED
@@ -0,0 +1,1353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # TELECOM QLoRA TEST / EVALUATION
3
+ # FOUR-OUTPUT TELECOM DIAGNOSIS
4
+ # ============================================================
5
+
6
+ import os
7
+ import re
8
+ import json
9
+ import argparse
10
+ from collections import Counter
11
+
12
+ import torch
13
+
14
+ from datasets import load_dataset
15
+
16
+ from transformers import (
17
+ AutoTokenizer,
18
+ AutoModelForCausalLM,
19
+ BitsAndBytesConfig,
20
+ )
21
+
22
+ from peft import PeftModel
23
+
24
+ from sklearn.metrics import (
25
+ accuracy_score,
26
+ precision_recall_fscore_support,
27
+ confusion_matrix,
28
+ )
29
+
30
+
31
+ # ============================================================
32
+ # CONFIGURATION
33
+ # ============================================================
34
+
35
+ MODEL_NAME = "C:\\Users\\aadhi\\Downloads\\telecom_four_output_complete_workspace\\models\\telecom-qwen-four-output"
36
+
37
+ CACHE_DIR = "sample/.cache/huggingface"
38
+
39
+ DEFAULT_TEST_FILE = (
40
+ "sample/data/test_four_output.jsonl"
41
+ )
42
+
43
+
44
+ # ============================================================
45
+ # REQUIRED OUTPUT SECTIONS
46
+ # ============================================================
47
+
48
+ REQUIRED_SECTIONS = [
49
+
50
+ "Probable Root Cause:",
51
+
52
+ "Explanation:",
53
+
54
+ "Recommendation:",
55
+
56
+ "Fault Severity:",
57
+ ]
58
+
59
+
60
+ # ============================================================
61
+ # COMMAND-LINE ARGUMENTS
62
+ # ============================================================
63
+
64
+ parser = argparse.ArgumentParser(
65
+
66
+ description=(
67
+ "Evaluate telecom QLoRA four-output model."
68
+ )
69
+ )
70
+
71
+
72
+ parser.add_argument(
73
+
74
+ "--adapter",
75
+
76
+ required=True,
77
+
78
+ help=(
79
+ "Path to trained LoRA adapter."
80
+ ),
81
+ )
82
+
83
+
84
+ parser.add_argument(
85
+
86
+ "--test",
87
+
88
+ default=DEFAULT_TEST_FILE,
89
+
90
+ help=(
91
+ "Path to test JSONL dataset."
92
+ ),
93
+ )
94
+
95
+
96
+ parser.add_argument(
97
+
98
+ "--samples",
99
+
100
+ type=int,
101
+
102
+ default=0,
103
+
104
+ help=(
105
+ "Number of test samples. "
106
+ "0 = all samples."
107
+ ),
108
+ )
109
+
110
+
111
+ parser.add_argument(
112
+
113
+ "--debug",
114
+
115
+ action="store_true",
116
+
117
+ help=(
118
+ "Print generated responses."
119
+ ),
120
+ )
121
+
122
+
123
+ args = parser.parse_args()
124
+
125
+
126
+ # ============================================================
127
+ # HELPERS
128
+ # ============================================================
129
+
130
+ def extract_fault_severity(text):
131
+
132
+ matches = re.findall(
133
+
134
+ r"fault[_\s-]*severity\s*[:=]\s*([012])",
135
+
136
+ text,
137
+
138
+ re.IGNORECASE,
139
+ )
140
+
141
+ if not matches:
142
+
143
+ return None
144
+
145
+ return int(
146
+ matches[-1]
147
+ )
148
+
149
+
150
+ def get_assistant_message(example):
151
+
152
+ for message in example["messages"]:
153
+
154
+ if message["role"] == "assistant":
155
+
156
+ return message["content"]
157
+
158
+ return ""
159
+
160
+
161
+ def extract_section(
162
+ text,
163
+ section_name,
164
+ next_sections,
165
+ ):
166
+
167
+ if section_name not in text:
168
+
169
+ return ""
170
+
171
+ content = text.split(
172
+ section_name,
173
+ 1
174
+ )[1]
175
+
176
+ end_positions = []
177
+
178
+ for section in next_sections:
179
+
180
+ position = content.find(
181
+ section
182
+ )
183
+
184
+ if position >= 0:
185
+
186
+ end_positions.append(
187
+ position
188
+ )
189
+
190
+ if end_positions:
191
+
192
+ content = content[
193
+ :min(end_positions)
194
+ ]
195
+
196
+ return content.strip()
197
+
198
+
199
+ def tokenize_for_overlap(text):
200
+
201
+ return set(
202
+ re.findall(
203
+ r"[a-z0-9_]+",
204
+ text.lower()
205
+ )
206
+ )
207
+
208
+
209
+ def token_f1(
210
+ reference,
211
+ prediction,
212
+ ):
213
+
214
+ reference_tokens = (
215
+ tokenize_for_overlap(
216
+ reference
217
+ )
218
+ )
219
+
220
+ prediction_tokens = (
221
+ tokenize_for_overlap(
222
+ prediction
223
+ )
224
+ )
225
+
226
+ if not reference_tokens:
227
+
228
+ return 0.0
229
+
230
+ if not prediction_tokens:
231
+
232
+ return 0.0
233
+
234
+ intersection = (
235
+ reference_tokens
236
+ &
237
+ prediction_tokens
238
+ )
239
+
240
+ precision = (
241
+ len(intersection)
242
+ /
243
+ len(prediction_tokens)
244
+ )
245
+
246
+ recall = (
247
+ len(intersection)
248
+ /
249
+ len(reference_tokens)
250
+ )
251
+
252
+ if precision + recall == 0:
253
+
254
+ return 0.0
255
+
256
+ return (
257
+ 2
258
+ * precision
259
+ * recall
260
+ /
261
+ (precision + recall)
262
+ )
263
+
264
+
265
+ # ============================================================
266
+ # GPU CHECK
267
+ # ============================================================
268
+
269
+ print("=" * 80)
270
+
271
+ print(
272
+ "TELECOM FOUR-OUTPUT MODEL EVALUATION"
273
+ )
274
+
275
+ print("=" * 80)
276
+
277
+
278
+ print()
279
+
280
+ print(
281
+ "CUDA available:",
282
+ torch.cuda.is_available()
283
+ )
284
+
285
+
286
+ if not torch.cuda.is_available():
287
+
288
+ raise RuntimeError(
289
+ "CUDA GPU is required."
290
+ )
291
+
292
+
293
+ print(
294
+ "GPU:",
295
+ torch.cuda.get_device_name(0)
296
+ )
297
+
298
+
299
+ print(
300
+ "VRAM:",
301
+ round(
302
+ torch.cuda.get_device_properties(
303
+ 0
304
+ ).total_memory
305
+ / (1024 ** 3),
306
+ 2,
307
+ ),
308
+ "GB",
309
+ )
310
+
311
+
312
+ # ============================================================
313
+ # CHECK FILES
314
+ # ============================================================
315
+
316
+ if not os.path.exists(
317
+ args.adapter
318
+ ):
319
+
320
+ raise FileNotFoundError(
321
+
322
+ "Adapter directory not found:\n"
323
+ f"{args.adapter}"
324
+ )
325
+
326
+
327
+ if not os.path.exists(
328
+ args.test
329
+ ):
330
+
331
+ raise FileNotFoundError(
332
+
333
+ "Test dataset not found:\n"
334
+ f"{args.test}"
335
+ )
336
+
337
+
338
+ # ============================================================
339
+ # LOAD TEST DATA
340
+ # ============================================================
341
+
342
+ print()
343
+
344
+ print(
345
+ "Loading test dataset..."
346
+ )
347
+
348
+
349
+ test_dataset = load_dataset(
350
+
351
+ "json",
352
+
353
+ data_files=args.test,
354
+
355
+ split="train",
356
+
357
+ cache_dir=CACHE_DIR,
358
+ )
359
+
360
+
361
+ print(
362
+ "Total test examples:",
363
+ len(test_dataset)
364
+ )
365
+
366
+
367
+ if args.samples > 0:
368
+
369
+ number = min(
370
+ args.samples,
371
+ len(test_dataset)
372
+ )
373
+
374
+ test_dataset = (
375
+ test_dataset.select(
376
+ range(number)
377
+ )
378
+ )
379
+
380
+
381
+ print(
382
+ "Examples to evaluate:",
383
+ len(test_dataset)
384
+ )
385
+
386
+
387
+ # ============================================================
388
+ # LOAD TOKENIZER
389
+ # ============================================================
390
+
391
+ print()
392
+
393
+ print(
394
+ "Loading tokenizer..."
395
+ )
396
+
397
+
398
+ tokenizer = AutoTokenizer.from_pretrained(
399
+
400
+ args.adapter,
401
+
402
+ trust_remote_code=True,
403
+
404
+ cache_dir=CACHE_DIR,
405
+ )
406
+
407
+
408
+ if tokenizer.pad_token is None:
409
+
410
+ tokenizer.pad_token = (
411
+ tokenizer.eos_token
412
+ )
413
+
414
+
415
+ # ============================================================
416
+ # QUANTIZATION
417
+ # ============================================================
418
+
419
+ bnb_config = BitsAndBytesConfig(
420
+
421
+ load_in_4bit=True,
422
+
423
+ bnb_4bit_quant_type="nf4",
424
+
425
+ bnb_4bit_compute_dtype=torch.float16,
426
+
427
+ bnb_4bit_use_double_quant=True,
428
+ )
429
+
430
+
431
+ # ============================================================
432
+ # LOAD BASE MODEL
433
+ # ============================================================
434
+
435
+ print()
436
+
437
+ print(
438
+ "Loading base Qwen model..."
439
+ )
440
+
441
+
442
+ base_model = (
443
+ AutoModelForCausalLM.from_pretrained(
444
+
445
+ MODEL_NAME,
446
+
447
+ quantization_config=bnb_config,
448
+
449
+ device_map="auto",
450
+
451
+ dtype=torch.float16,
452
+
453
+ trust_remote_code=True,
454
+
455
+ cache_dir=CACHE_DIR,
456
+ )
457
+ )
458
+
459
+
460
+ # ============================================================
461
+ # LOAD LORA ADAPTER
462
+ # ============================================================
463
+
464
+ print()
465
+
466
+ print(
467
+ "Loading LoRA adapter..."
468
+ )
469
+
470
+
471
+ model = PeftModel.from_pretrained(
472
+
473
+ base_model,
474
+
475
+ args.adapter,
476
+ )
477
+
478
+
479
+ model.eval()
480
+
481
+
482
+ print(
483
+ "Model ready."
484
+ )
485
+
486
+
487
+ # ============================================================
488
+ # EVALUATION STORAGE
489
+ # ============================================================
490
+
491
+ predictions = []
492
+
493
+ y_true = []
494
+
495
+ y_pred = []
496
+
497
+ root_scores = []
498
+
499
+ explanation_scores = []
500
+
501
+ recommendation_scores = []
502
+
503
+
504
+ # ============================================================
505
+ # GENERATE RESPONSES
506
+ # ============================================================
507
+
508
+ print()
509
+
510
+ print("=" * 80)
511
+
512
+ print(
513
+ "GENERATING TEST RESPONSES"
514
+ )
515
+
516
+ print("=" * 80)
517
+
518
+
519
+ for index, example in enumerate(
520
+ test_dataset
521
+ ):
522
+
523
+ # --------------------------------------------------------
524
+ # Get messages
525
+ # --------------------------------------------------------
526
+
527
+ messages = example[
528
+ "messages"
529
+ ]
530
+
531
+
532
+ # --------------------------------------------------------
533
+ # Remove assistant answer
534
+ # --------------------------------------------------------
535
+
536
+ prompt_messages = [
537
+
538
+ message
539
+
540
+ for message in messages
541
+
542
+ if message["role"]
543
+ != "assistant"
544
+
545
+ ]
546
+
547
+
548
+ # --------------------------------------------------------
549
+ # Reference answer
550
+ # --------------------------------------------------------
551
+
552
+ reference = (
553
+ get_assistant_message(
554
+ example
555
+ )
556
+ )
557
+
558
+
559
+ # --------------------------------------------------------
560
+ # Build prompt
561
+ # --------------------------------------------------------
562
+
563
+ prompt = (
564
+ tokenizer.apply_chat_template(
565
+
566
+ prompt_messages,
567
+
568
+ tokenize=False,
569
+
570
+ add_generation_prompt=True,
571
+ )
572
+ )
573
+
574
+
575
+ # --------------------------------------------------------
576
+ # Tokenize
577
+ # --------------------------------------------------------
578
+
579
+ inputs = tokenizer(
580
+
581
+ prompt,
582
+
583
+ return_tensors="pt",
584
+
585
+ )
586
+
587
+
588
+ inputs = {
589
+
590
+ key: value.to(
591
+ model.device
592
+ )
593
+
594
+ for key, value
595
+ in inputs.items()
596
+
597
+ }
598
+
599
+
600
+ # --------------------------------------------------------
601
+ # Generate
602
+ # --------------------------------------------------------
603
+
604
+ with torch.no_grad():
605
+
606
+ output = model.generate(
607
+
608
+ **inputs,
609
+
610
+ max_new_tokens=350,
611
+
612
+ do_sample=False,
613
+
614
+ pad_token_id=(
615
+ tokenizer.pad_token_id
616
+ ),
617
+
618
+ eos_token_id=(
619
+ tokenizer.eos_token_id
620
+ ),
621
+ )
622
+
623
+
624
+ # --------------------------------------------------------
625
+ # Decode ONLY generated tokens
626
+ # --------------------------------------------------------
627
+
628
+ generated_tokens = output[
629
+
630
+ 0
631
+
632
+ ][
633
+
634
+ inputs["input_ids"].shape[1]:
635
+
636
+ ]
637
+
638
+
639
+ generated = tokenizer.decode(
640
+
641
+ generated_tokens,
642
+
643
+ skip_special_tokens=True,
644
+ ).strip()
645
+
646
+
647
+ # --------------------------------------------------------
648
+ # Severity
649
+ # --------------------------------------------------------
650
+
651
+ true_label = (
652
+ extract_fault_severity(
653
+ reference
654
+ )
655
+ )
656
+
657
+
658
+ predicted_label = (
659
+ extract_fault_severity(
660
+ generated
661
+ )
662
+ )
663
+
664
+
665
+ y_true.append(
666
+ true_label
667
+ )
668
+
669
+ y_pred.append(
670
+ predicted_label
671
+ )
672
+
673
+
674
+ # --------------------------------------------------------
675
+ # Root Cause
676
+ # --------------------------------------------------------
677
+
678
+ root_reference = extract_section(
679
+
680
+ reference,
681
+
682
+ "Probable Root Cause:",
683
+
684
+ [
685
+ "Explanation:",
686
+ "Recommendation:",
687
+ "Fault Severity:",
688
+ ],
689
+ )
690
+
691
+
692
+ root_prediction = extract_section(
693
+
694
+ generated,
695
+
696
+ "Probable Root Cause:",
697
+
698
+ [
699
+ "Explanation:",
700
+ "Recommendation:",
701
+ "Fault Severity:",
702
+ ],
703
+ )
704
+
705
+
706
+ root_f1 = token_f1(
707
+
708
+ root_reference,
709
+
710
+ root_prediction,
711
+ )
712
+
713
+
714
+ root_scores.append(
715
+ root_f1
716
+ )
717
+
718
+
719
+ # --------------------------------------------------------
720
+ # Explanation
721
+ # --------------------------------------------------------
722
+
723
+ explanation_reference = extract_section(
724
+
725
+ reference,
726
+
727
+ "Explanation:",
728
+
729
+ [
730
+ "Recommendation:",
731
+ "Fault Severity:",
732
+ ],
733
+ )
734
+
735
+
736
+ explanation_prediction = extract_section(
737
+
738
+ generated,
739
+
740
+ "Explanation:",
741
+
742
+ [
743
+ "Recommendation:",
744
+ "Fault Severity:",
745
+ ],
746
+ )
747
+
748
+
749
+ explanation_f1 = token_f1(
750
+
751
+ explanation_reference,
752
+
753
+ explanation_prediction,
754
+ )
755
+
756
+
757
+ explanation_scores.append(
758
+ explanation_f1
759
+ )
760
+
761
+
762
+ # --------------------------------------------------------
763
+ # Recommendation
764
+ # --------------------------------------------------------
765
+
766
+ recommendation_reference = extract_section(
767
+
768
+ reference,
769
+
770
+ "Recommendation:",
771
+
772
+ [
773
+ "Fault Severity:",
774
+ ],
775
+ )
776
+
777
+
778
+ recommendation_prediction = extract_section(
779
+
780
+ generated,
781
+
782
+ "Recommendation:",
783
+
784
+ [
785
+ "Fault Severity:",
786
+ ],
787
+ )
788
+
789
+
790
+ recommendation_f1 = token_f1(
791
+
792
+ recommendation_reference,
793
+
794
+ recommendation_prediction,
795
+ )
796
+
797
+
798
+ recommendation_scores.append(
799
+ recommendation_f1
800
+ )
801
+
802
+
803
+ # --------------------------------------------------------
804
+ # Format check
805
+ # --------------------------------------------------------
806
+
807
+ all_sections_present = all(
808
+
809
+ section in generated
810
+
811
+ for section
812
+ in REQUIRED_SECTIONS
813
+
814
+ )
815
+
816
+
817
+ # --------------------------------------------------------
818
+ # Save result
819
+ # --------------------------------------------------------
820
+
821
+ predictions.append({
822
+
823
+ "index": index,
824
+
825
+ "true_fault_severity": (
826
+ true_label
827
+ ),
828
+
829
+ "predicted_fault_severity": (
830
+ predicted_label
831
+ ),
832
+
833
+ "severity_correct": (
834
+
835
+ true_label
836
+ ==
837
+ predicted_label
838
+
839
+ ),
840
+
841
+ "all_sections_present": (
842
+ all_sections_present
843
+ ),
844
+
845
+ "root_cause_token_f1": (
846
+ root_f1
847
+ ),
848
+
849
+ "explanation_token_f1": (
850
+ explanation_f1
851
+ ),
852
+
853
+ "recommendation_token_f1": (
854
+ recommendation_f1
855
+ ),
856
+
857
+ "model_response": (
858
+ generated
859
+ ),
860
+
861
+ "reference_response": (
862
+ reference
863
+ ),
864
+
865
+ })
866
+
867
+
868
+ # --------------------------------------------------------
869
+ # Debug output
870
+ # --------------------------------------------------------
871
+
872
+ if args.debug:
873
+
874
+ print()
875
+
876
+ print("-" * 80)
877
+
878
+ print(
879
+ "Example:",
880
+ index + 1
881
+ )
882
+
883
+ print(
884
+ "Expected severity:",
885
+ true_label
886
+ )
887
+
888
+ print(
889
+ "Predicted severity:",
890
+ predicted_label
891
+ )
892
+
893
+ print()
894
+
895
+ print(
896
+ "MODEL RESPONSE:"
897
+ )
898
+
899
+ print()
900
+
901
+ print(
902
+ generated
903
+ )
904
+
905
+
906
+ # --------------------------------------------------------
907
+ # Progress
908
+ # --------------------------------------------------------
909
+
910
+ if not args.debug:
911
+
912
+ if (
913
+ (index + 1) % 10 == 0
914
+ or
915
+ (index + 1)
916
+ == len(test_dataset)
917
+ ):
918
+
919
+ print(
920
+
921
+ f"Processed "
922
+ f"{index + 1}/"
923
+ f"{len(test_dataset)}"
924
+
925
+ )
926
+
927
+
928
+ # ============================================================
929
+ # SAVE PREDICTIONS
930
+ # ============================================================
931
+
932
+ prediction_file = os.path.join(
933
+
934
+ args.adapter,
935
+
936
+ "test_four_output_predictions.jsonl",
937
+ )
938
+
939
+
940
+ with open(
941
+
942
+ prediction_file,
943
+
944
+ "w",
945
+
946
+ encoding="utf-8",
947
+
948
+ ) as file:
949
+
950
+ for row in predictions:
951
+
952
+ file.write(
953
+
954
+ json.dumps(
955
+
956
+ row,
957
+
958
+ ensure_ascii=False,
959
+
960
+ )
961
+
962
+ + "\n"
963
+
964
+ )
965
+
966
+
967
+ # ============================================================
968
+ # VALID SEVERITY PREDICTIONS
969
+ # ============================================================
970
+
971
+ valid_pairs = [
972
+
973
+ (
974
+ true,
975
+ pred
976
+ )
977
+
978
+ for true, pred
979
+
980
+ in zip(
981
+ y_true,
982
+ y_pred
983
+ )
984
+
985
+ if true in [0, 1, 2]
986
+ and pred in [0, 1, 2]
987
+
988
+ ]
989
+
990
+
991
+ if not valid_pairs:
992
+
993
+ print()
994
+
995
+ print(
996
+ "ERROR: Model did not produce"
997
+ " valid fault_severity values."
998
+ )
999
+
1000
+ print(
1001
+ "Check the generated responses."
1002
+ )
1003
+
1004
+ raise RuntimeError(
1005
+ "No valid severity predictions."
1006
+ )
1007
+
1008
+
1009
+ valid_true = [
1010
+
1011
+ pair[0]
1012
+
1013
+ for pair in valid_pairs
1014
+
1015
+ ]
1016
+
1017
+
1018
+ valid_pred = [
1019
+
1020
+ pair[1]
1021
+
1022
+ for pair in valid_pairs
1023
+
1024
+ ]
1025
+
1026
+
1027
+ # ============================================================
1028
+ # SEVERITY METRICS
1029
+ # ============================================================
1030
+
1031
+ accuracy = accuracy_score(
1032
+
1033
+ valid_true,
1034
+
1035
+ valid_pred,
1036
+ )
1037
+
1038
+
1039
+ precision, recall, f1, support = (
1040
+ precision_recall_fscore_support(
1041
+
1042
+ valid_true,
1043
+
1044
+ valid_pred,
1045
+
1046
+ labels=[
1047
+ 0,
1048
+ 1,
1049
+ 2
1050
+ ],
1051
+
1052
+ zero_division=0,
1053
+
1054
+ )
1055
+ )
1056
+
1057
+
1058
+ matrix = confusion_matrix(
1059
+
1060
+ valid_true,
1061
+
1062
+ valid_pred,
1063
+
1064
+ labels=[
1065
+ 0,
1066
+ 1,
1067
+ 2
1068
+ ],
1069
+
1070
+ )
1071
+
1072
+
1073
+ # ============================================================
1074
+ # FORMAT COMPLIANCE
1075
+ # ============================================================
1076
+
1077
+ format_compliance = (
1078
+
1079
+ sum(
1080
+
1081
+ row[
1082
+ "all_sections_present"
1083
+ ]
1084
+
1085
+ for row
1086
+ in predictions
1087
+
1088
+ )
1089
+
1090
+ /
1091
+
1092
+ len(predictions)
1093
+
1094
+ )
1095
+
1096
+
1097
+ # ============================================================
1098
+ # AVERAGE TEXT SCORES
1099
+ # ============================================================
1100
+
1101
+ average_root_f1 = (
1102
+
1103
+ sum(root_scores)
1104
+ /
1105
+ len(root_scores)
1106
+
1107
+ )
1108
+
1109
+
1110
+ average_explanation_f1 = (
1111
+
1112
+ sum(explanation_scores)
1113
+ /
1114
+ len(explanation_scores)
1115
+
1116
+ )
1117
+
1118
+
1119
+ average_recommendation_f1 = (
1120
+
1121
+ sum(recommendation_scores)
1122
+ /
1123
+ len(recommendation_scores)
1124
+
1125
+ )
1126
+
1127
+
1128
+ # ============================================================
1129
+ # RESULTS
1130
+ # ============================================================
1131
+
1132
+ print()
1133
+
1134
+ print("=" * 80)
1135
+
1136
+ print(
1137
+ "FOUR-OUTPUT EVALUATION RESULTS"
1138
+ )
1139
+
1140
+ print("=" * 80)
1141
+
1142
+
1143
+ print()
1144
+
1145
+ print(
1146
+ f"Fault Severity Accuracy: "
1147
+ f"{accuracy:.4f}"
1148
+ )
1149
+
1150
+
1151
+ print(
1152
+ f"Fault Severity Accuracy: "
1153
+ f"{accuracy * 100:.2f}%"
1154
+ )
1155
+
1156
+
1157
+ print()
1158
+
1159
+ print(
1160
+ f"Four-section format compliance: "
1161
+ f"{format_compliance * 100:.2f}%"
1162
+ )
1163
+
1164
+
1165
+ print()
1166
+
1167
+ print(
1168
+ f"Average Root Cause token-F1: "
1169
+ f"{average_root_f1:.4f}"
1170
+ )
1171
+
1172
+
1173
+ print(
1174
+ f"Average Explanation token-F1: "
1175
+ f"{average_explanation_f1:.4f}"
1176
+ )
1177
+
1178
+
1179
+ print(
1180
+ f"Average Recommendation token-F1: "
1181
+ f"{average_recommendation_f1:.4f}"
1182
+ )
1183
+
1184
+
1185
+ # ============================================================
1186
+ # PER-CLASS METRICS
1187
+ # ============================================================
1188
+
1189
+ print()
1190
+
1191
+ print(
1192
+ "Per-class fault severity metrics:"
1193
+ )
1194
+
1195
+
1196
+ for index, severity in enumerate(
1197
+ [0, 1, 2]
1198
+ ):
1199
+
1200
+ print(
1201
+
1202
+ f"Class {severity}: "
1203
+
1204
+ f"precision={precision[index]:.4f}, "
1205
+
1206
+ f"recall={recall[index]:.4f}, "
1207
+
1208
+ f"f1={f1[index]:.4f}, "
1209
+
1210
+ f"support={support[index]}"
1211
+
1212
+ )
1213
+
1214
+
1215
+ # ============================================================
1216
+ # CONFUSION MATRIX
1217
+ # ============================================================
1218
+
1219
+ print()
1220
+
1221
+ print(
1222
+ "Confusion matrix:"
1223
+ )
1224
+
1225
+ print()
1226
+
1227
+ print(
1228
+ " Predicted"
1229
+ )
1230
+
1231
+ print(
1232
+ " 0 1 2"
1233
+ )
1234
+
1235
+
1236
+ for index, row in enumerate(
1237
+ matrix
1238
+ ):
1239
+
1240
+ print(
1241
+
1242
+ f"Actual {index} "
1243
+
1244
+ f"{row[0]:6d} "
1245
+
1246
+ f"{row[1]:6d} "
1247
+
1248
+ f"{row[2]:6d}"
1249
+
1250
+ )
1251
+
1252
+
1253
+ # ============================================================
1254
+ # MAJORITY BASELINE
1255
+ # ============================================================
1256
+
1257
+ counter = Counter(
1258
+ valid_true
1259
+ )
1260
+
1261
+
1262
+ majority_class = (
1263
+ counter.most_common(1)[0][0]
1264
+ )
1265
+
1266
+
1267
+ majority_accuracy = (
1268
+
1269
+ sum(
1270
+
1271
+ value
1272
+ == majority_class
1273
+
1274
+ for value
1275
+ in valid_true
1276
+
1277
+ )
1278
+
1279
+ /
1280
+
1281
+ len(valid_true)
1282
+
1283
+ )
1284
+
1285
+
1286
+ print()
1287
+
1288
+ print(
1289
+ "Majority-class baseline:"
1290
+ )
1291
+
1292
+ print(
1293
+ "Majority class:",
1294
+ majority_class
1295
+ )
1296
+
1297
+ print(
1298
+ f"Baseline accuracy: "
1299
+ f"{majority_accuracy:.4f}"
1300
+ )
1301
+
1302
+
1303
+ # ============================================================
1304
+ # OUTPUT FILE
1305
+ # ============================================================
1306
+
1307
+ print()
1308
+
1309
+ print(
1310
+ "Detailed predictions saved to:"
1311
+ )
1312
+
1313
+ print(
1314
+ os.path.abspath(
1315
+ prediction_file
1316
+ )
1317
+ )
1318
+
1319
+
1320
+ # ============================================================
1321
+ # WARNING
1322
+ # ============================================================
1323
+
1324
+ print()
1325
+
1326
+ print("=" * 80)
1327
+
1328
+ print(
1329
+ "IMPORTANT"
1330
+ )
1331
+
1332
+ print("=" * 80)
1333
+
1334
+ print(
1335
+
1336
+ "Root Cause, Explanation and Recommendation "
1337
+ "token-F1 are similarity metrics against the "
1338
+ "structured reference responses. They are NOT "
1339
+ "proof of real-world telecom engineering correctness."
1340
+
1341
+ )
1342
+
1343
+ print()
1344
+
1345
+ print(
1346
+
1347
+ "For production deployment, replace synthetic "
1348
+ "root-cause/recommendation targets with "
1349
+ "engineer-validated annotations."
1350
+
1351
+ )
1352
+
1353
+ print("=" * 80)
train.py ADDED
@@ -0,0 +1,848 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ============================================================
2
+ # TELECOM QLoRA FINE-TUNING
3
+ # FOUR-OUTPUT TELECOM DIAGNOSIS
4
+ #
5
+ # Model:
6
+ # Qwen/Qwen2.5-1.5B-Instruct
7
+ #
8
+ # Output:
9
+ # Probable Root Cause
10
+ # Explanation
11
+ # Recommendation
12
+ # Fault Severity
13
+ # ============================================================
14
+
15
+ import os
16
+ import re
17
+ import torch
18
+
19
+ from datasets import load_dataset
20
+
21
+ from transformers import (
22
+ AutoTokenizer,
23
+ AutoModelForCausalLM,
24
+ BitsAndBytesConfig,
25
+ )
26
+
27
+ from peft import (
28
+ LoraConfig,
29
+ prepare_model_for_kbit_training,
30
+ )
31
+
32
+ from trl import (
33
+ SFTTrainer,
34
+ SFTConfig,
35
+ )
36
+
37
+
38
+ # ============================================================
39
+ # CONFIGURATION
40
+ # ============================================================
41
+
42
+ MODEL_NAME = "Qwen/Qwen2.5-1.5B-Instruct"
43
+
44
+ TRAIN_FILE = "sample/data/train_four_output.jsonl"
45
+ VALIDATION_FILE = "sample/data/validation_four_output.jsonl"
46
+
47
+ OUTPUT_DIR = "models/telecom-qwen-four-output"
48
+
49
+ CACHE_DIR = "sample/.cache/huggingface"
50
+
51
+ EPOCHS = 3
52
+
53
+ MAX_LENGTH = 1024
54
+
55
+ TRAIN_BATCH_SIZE = 1
56
+
57
+ EVAL_BATCH_SIZE = 1
58
+
59
+ GRADIENT_ACCUMULATION = 8
60
+
61
+ LEARNING_RATE = 2e-4
62
+
63
+ SEED = 42
64
+
65
+
66
+ # ============================================================
67
+ # REQUIRED OUTPUT FORMAT
68
+ # ============================================================
69
+
70
+ REQUIRED_SECTIONS = [
71
+ "Probable Root Cause:",
72
+ "Explanation:",
73
+ "Recommendation:",
74
+ "Fault Severity:",
75
+ ]
76
+
77
+
78
+ # ============================================================
79
+ # HELPER FUNCTIONS
80
+ # ============================================================
81
+
82
+ def get_assistant_message(example):
83
+
84
+ for message in example["messages"]:
85
+
86
+ if message["role"] == "assistant":
87
+
88
+ return message["content"]
89
+
90
+ raise ValueError(
91
+ "Assistant message not found."
92
+ )
93
+
94
+
95
+ def extract_fault_severity(text):
96
+
97
+ matches = re.findall(
98
+ r"fault[_\s-]*severity\s*[:=]\s*([012])",
99
+ text,
100
+ re.IGNORECASE,
101
+ )
102
+
103
+ if not matches:
104
+
105
+ return None
106
+
107
+ return int(matches[-1])
108
+
109
+
110
+ def verify_example(example):
111
+
112
+ # --------------------------------------------------------
113
+ # Check messages
114
+ # --------------------------------------------------------
115
+
116
+ if "messages" not in example:
117
+
118
+ raise ValueError(
119
+ "Dataset example does not contain 'messages'."
120
+ )
121
+
122
+ roles = [
123
+ message["role"]
124
+ for message in example["messages"]
125
+ ]
126
+
127
+ required_roles = {
128
+ "system",
129
+ "user",
130
+ "assistant",
131
+ }
132
+
133
+ if not required_roles.issubset(set(roles)):
134
+
135
+ raise ValueError(
136
+ "Example must contain system, user and assistant messages."
137
+ )
138
+
139
+ # --------------------------------------------------------
140
+ # Check assistant response
141
+ # --------------------------------------------------------
142
+
143
+ assistant = get_assistant_message(example)
144
+
145
+ for section in REQUIRED_SECTIONS:
146
+
147
+ if section not in assistant:
148
+
149
+ raise ValueError(
150
+ f"Missing required section: {section}"
151
+ )
152
+
153
+ # --------------------------------------------------------
154
+ # Check severity
155
+ # --------------------------------------------------------
156
+
157
+ severity = extract_fault_severity(
158
+ assistant
159
+ )
160
+
161
+ if severity not in [0, 1, 2]:
162
+
163
+ raise ValueError(
164
+ f"Invalid fault severity: {severity}"
165
+ )
166
+
167
+ return example
168
+
169
+
170
+ def print_distribution(
171
+ dataset,
172
+ name,
173
+ ):
174
+
175
+ counts = {
176
+ 0: 0,
177
+ 1: 0,
178
+ 2: 0,
179
+ }
180
+
181
+ for example in dataset:
182
+
183
+ assistant = get_assistant_message(
184
+ example
185
+ )
186
+
187
+ severity = extract_fault_severity(
188
+ assistant
189
+ )
190
+
191
+ if severity in counts:
192
+
193
+ counts[severity] += 1
194
+
195
+ total = len(dataset)
196
+
197
+ print()
198
+ print(
199
+ f"{name} fault_severity distribution:"
200
+ )
201
+
202
+ for severity in [0, 1, 2]:
203
+
204
+ percentage = (
205
+ counts[severity] / total * 100
206
+ )
207
+
208
+ print(
209
+ f" {severity}: "
210
+ f"{counts[severity]} "
211
+ f"({percentage:.2f}%)"
212
+ )
213
+
214
+
215
+ # ============================================================
216
+ # START
217
+ # ============================================================
218
+
219
+ print("=" * 80)
220
+
221
+ print(
222
+ "TELECOM QLoRA FINE-TUNING"
223
+ )
224
+
225
+ print(
226
+ "FOUR-OUTPUT TELECOM DIAGNOSIS"
227
+ )
228
+
229
+ print("=" * 80)
230
+
231
+
232
+ # ============================================================
233
+ # GPU CHECK
234
+ # ============================================================
235
+
236
+ print()
237
+
238
+ print(
239
+ "CUDA available:",
240
+ torch.cuda.is_available()
241
+ )
242
+
243
+ if not torch.cuda.is_available():
244
+
245
+ raise RuntimeError(
246
+ "CUDA GPU is required for this training configuration."
247
+ )
248
+
249
+
250
+ gpu_name = torch.cuda.get_device_name(0)
251
+
252
+ gpu_memory = (
253
+ torch.cuda.get_device_properties(0)
254
+ .total_memory
255
+ / (1024 ** 3)
256
+ )
257
+
258
+
259
+ print(
260
+ "GPU:",
261
+ gpu_name
262
+ )
263
+
264
+ print(
265
+ "VRAM:",
266
+ round(gpu_memory, 2),
267
+ "GB"
268
+ )
269
+
270
+
271
+ # ============================================================
272
+ # DIRECTORIES
273
+ # ============================================================
274
+
275
+ os.makedirs(
276
+ CACHE_DIR,
277
+ exist_ok=True
278
+ )
279
+
280
+ os.makedirs(
281
+ OUTPUT_DIR,
282
+ exist_ok=True
283
+ )
284
+
285
+
286
+ # ============================================================
287
+ # CHECK DATA FILES
288
+ # ============================================================
289
+
290
+ if not os.path.exists(TRAIN_FILE):
291
+
292
+ raise FileNotFoundError(
293
+ f"Training dataset not found:\n{TRAIN_FILE}"
294
+ )
295
+
296
+
297
+ if not os.path.exists(
298
+ VALIDATION_FILE
299
+ ):
300
+
301
+ raise FileNotFoundError(
302
+ f"Validation dataset not found:\n"
303
+ f"{VALIDATION_FILE}"
304
+ )
305
+
306
+
307
+ # ============================================================
308
+ # LOAD DATA
309
+ # ============================================================
310
+
311
+ print()
312
+
313
+ print("=" * 80)
314
+
315
+ print(
316
+ "LOADING DATASETS"
317
+ )
318
+
319
+ print("=" * 80)
320
+
321
+
322
+ train_dataset = load_dataset(
323
+ "json",
324
+ data_files=TRAIN_FILE,
325
+ split="train",
326
+ cache_dir=CACHE_DIR,
327
+ )
328
+
329
+
330
+ validation_dataset = load_dataset(
331
+ "json",
332
+ data_files=VALIDATION_FILE,
333
+ split="train",
334
+ cache_dir=CACHE_DIR,
335
+ )
336
+
337
+
338
+ print(
339
+ "Training examples:",
340
+ len(train_dataset)
341
+ )
342
+
343
+ print(
344
+ "Validation examples:",
345
+ len(validation_dataset)
346
+ )
347
+
348
+
349
+ # ============================================================
350
+ # VERIFY DATA
351
+ # ============================================================
352
+
353
+ print()
354
+
355
+ print(
356
+ "Verifying four-output format..."
357
+ )
358
+
359
+
360
+ train_dataset = train_dataset.map(
361
+ verify_example
362
+ )
363
+
364
+
365
+ validation_dataset = validation_dataset.map(
366
+ verify_example
367
+ )
368
+
369
+
370
+ print(
371
+ "Dataset verification completed."
372
+ )
373
+
374
+
375
+ # ============================================================
376
+ # PRINT LABEL DISTRIBUTION
377
+ # ============================================================
378
+
379
+ print_distribution(
380
+ train_dataset,
381
+ "Training"
382
+ )
383
+
384
+
385
+ print_distribution(
386
+ validation_dataset,
387
+ "Validation"
388
+ )
389
+
390
+
391
+ # ============================================================
392
+ # TOKENIZER
393
+ # ============================================================
394
+
395
+ print()
396
+
397
+ print("=" * 80)
398
+
399
+ print(
400
+ "LOADING TOKENIZER"
401
+ )
402
+
403
+ print("=" * 80)
404
+
405
+
406
+ tokenizer = AutoTokenizer.from_pretrained(
407
+ MODEL_NAME,
408
+ trust_remote_code=True,
409
+ cache_dir=CACHE_DIR,
410
+ )
411
+
412
+
413
+ if tokenizer.pad_token is None:
414
+
415
+ tokenizer.pad_token = tokenizer.eos_token
416
+
417
+
418
+ tokenizer.padding_side = "right"
419
+
420
+
421
+ # ============================================================
422
+ # 4-BIT QUANTIZATION
423
+ # ============================================================
424
+
425
+ print()
426
+
427
+ print("=" * 80)
428
+
429
+ print(
430
+ "CONFIGURING 4-BIT QUANTIZATION"
431
+ )
432
+
433
+ print("=" * 80)
434
+
435
+
436
+ bnb_config = BitsAndBytesConfig(
437
+
438
+ load_in_4bit=True,
439
+
440
+ bnb_4bit_quant_type="nf4",
441
+
442
+ bnb_4bit_compute_dtype=torch.float16,
443
+
444
+ bnb_4bit_use_double_quant=True,
445
+ )
446
+
447
+
448
+ # ============================================================
449
+ # LOAD BASE MODEL
450
+ # ============================================================
451
+
452
+ print()
453
+
454
+ print("=" * 80)
455
+
456
+ print(
457
+ "LOADING BASE MODEL"
458
+ )
459
+
460
+ print("=" * 80)
461
+
462
+
463
+ model = AutoModelForCausalLM.from_pretrained(
464
+
465
+ MODEL_NAME,
466
+
467
+ quantization_config=bnb_config,
468
+
469
+ device_map="auto",
470
+
471
+ dtype=torch.float16,
472
+
473
+ trust_remote_code=True,
474
+
475
+ cache_dir=CACHE_DIR,
476
+ )
477
+
478
+
479
+ print(
480
+ "Base model loaded."
481
+ )
482
+
483
+
484
+ # ============================================================
485
+ # PREPARE QLORA
486
+ # ============================================================
487
+
488
+ print()
489
+
490
+ print(
491
+ "Preparing model for QLoRA..."
492
+ )
493
+
494
+
495
+ model = prepare_model_for_kbit_training(
496
+ model
497
+ )
498
+
499
+
500
+ model.config.use_cache = False
501
+
502
+
503
+ # ============================================================
504
+ # LORA CONFIGURATION
505
+ # ============================================================
506
+
507
+ print()
508
+
509
+ print("=" * 80)
510
+
511
+ print(
512
+ "CONFIGURING LoRA"
513
+ )
514
+
515
+ print("=" * 80)
516
+
517
+
518
+ lora_config = LoraConfig(
519
+
520
+ r=8,
521
+
522
+ lora_alpha=16,
523
+
524
+ lora_dropout=0.05,
525
+
526
+ target_modules=[
527
+ "q_proj",
528
+ "k_proj",
529
+ "v_proj",
530
+ "o_proj",
531
+ ],
532
+
533
+ bias="none",
534
+
535
+ task_type="CAUSAL_LM",
536
+ )
537
+
538
+
539
+ # ============================================================
540
+ # CHAT FORMAT
541
+ # ============================================================
542
+
543
+ def formatting_func(example):
544
+
545
+ return tokenizer.apply_chat_template(
546
+
547
+ example["messages"],
548
+
549
+ tokenize=False,
550
+
551
+ add_generation_prompt=False,
552
+ )
553
+
554
+
555
+ # ============================================================
556
+ # TRAINING CONFIGURATION
557
+ # ============================================================
558
+
559
+ print()
560
+
561
+ print("=" * 80)
562
+
563
+ print(
564
+ "CONFIGURING TRAINING"
565
+ )
566
+
567
+ print("=" * 80)
568
+
569
+
570
+ # IMPORTANT:
571
+ # max_length belongs to SFTConfig, not SFTTrainer.
572
+
573
+ training_args = SFTConfig(
574
+
575
+ output_dir=OUTPUT_DIR,
576
+
577
+ seed=SEED,
578
+
579
+ data_seed=SEED,
580
+
581
+ per_device_train_batch_size=TRAIN_BATCH_SIZE,
582
+
583
+ per_device_eval_batch_size=EVAL_BATCH_SIZE,
584
+
585
+ gradient_accumulation_steps=GRADIENT_ACCUMULATION,
586
+
587
+ num_train_epochs=EPOCHS,
588
+
589
+ learning_rate=LEARNING_RATE,
590
+
591
+ fp16=False,
592
+
593
+ bf16=False,
594
+
595
+ gradient_checkpointing=True,
596
+
597
+ gradient_checkpointing_kwargs={
598
+ "use_reentrant": False
599
+ },
600
+
601
+ optim="paged_adamw_8bit",
602
+
603
+ logging_steps=10,
604
+
605
+ eval_strategy="epoch",
606
+
607
+ save_strategy="epoch",
608
+
609
+ save_total_limit=2,
610
+
611
+ load_best_model_at_end=True,
612
+
613
+ metric_for_best_model="eval_loss",
614
+
615
+ greater_is_better=False,
616
+
617
+ report_to="none",
618
+
619
+ remove_unused_columns=False,
620
+
621
+ max_length=MAX_LENGTH,
622
+
623
+ packing=False,
624
+ )
625
+
626
+
627
+ # ============================================================
628
+ # CREATE SFT TRAINER
629
+ # ============================================================
630
+
631
+ print()
632
+
633
+ print("=" * 80)
634
+
635
+ print(
636
+ "CREATING SFT TRAINER"
637
+ )
638
+
639
+ print("=" * 80)
640
+
641
+
642
+ trainer = SFTTrainer(
643
+
644
+ model=model,
645
+
646
+ train_dataset=train_dataset,
647
+
648
+ eval_dataset=validation_dataset,
649
+
650
+ peft_config=lora_config,
651
+
652
+ formatting_func=formatting_func,
653
+
654
+ processing_class=tokenizer,
655
+
656
+ args=training_args,
657
+ )
658
+
659
+
660
+ # ============================================================
661
+ # TRAIN
662
+ # ============================================================
663
+
664
+ print()
665
+
666
+ print("=" * 80)
667
+
668
+ print(
669
+ "STARTING TRAINING"
670
+ )
671
+
672
+ print("=" * 80)
673
+
674
+
675
+ print(
676
+ "Training examples:",
677
+ len(train_dataset)
678
+ )
679
+
680
+ print(
681
+ "Validation examples:",
682
+ len(validation_dataset)
683
+ )
684
+
685
+ print(
686
+ "Epochs:",
687
+ EPOCHS
688
+ )
689
+
690
+ print(
691
+ "Batch size:",
692
+ TRAIN_BATCH_SIZE
693
+ )
694
+
695
+ print(
696
+ "Gradient accumulation:",
697
+ GRADIENT_ACCUMULATION
698
+ )
699
+
700
+ print(
701
+ "Effective batch size:",
702
+ TRAIN_BATCH_SIZE
703
+ * GRADIENT_ACCUMULATION
704
+ )
705
+
706
+ print(
707
+ "Learning rate:",
708
+ LEARNING_RATE
709
+ )
710
+
711
+ print(
712
+ "Maximum sequence length:",
713
+ MAX_LENGTH
714
+ )
715
+
716
+ print("=" * 80)
717
+
718
+
719
+ try:
720
+
721
+ result = trainer.train()
722
+
723
+ except KeyboardInterrupt:
724
+
725
+ print()
726
+
727
+ print(
728
+ "Training interrupted."
729
+ )
730
+
731
+ print(
732
+ "Saving current adapter..."
733
+ )
734
+
735
+ trainer.save_model(
736
+ OUTPUT_DIR
737
+ )
738
+
739
+ tokenizer.save_pretrained(
740
+ OUTPUT_DIR
741
+ )
742
+
743
+ trainer.save_state()
744
+
745
+ raise
746
+
747
+
748
+ # ============================================================
749
+ # SAVE MODEL
750
+ # ============================================================
751
+
752
+ print()
753
+
754
+ print("=" * 80)
755
+
756
+ print(
757
+ "SAVING MODEL"
758
+ )
759
+
760
+ print("=" * 80)
761
+
762
+
763
+ trainer.save_model(
764
+ OUTPUT_DIR
765
+ )
766
+
767
+
768
+ tokenizer.save_pretrained(
769
+ OUTPUT_DIR
770
+ )
771
+
772
+
773
+ trainer.save_state()
774
+
775
+
776
+ # ============================================================
777
+ # RESULTS
778
+ # ============================================================
779
+
780
+ print()
781
+
782
+ print("=" * 80)
783
+
784
+ print(
785
+ "TRAINING COMPLETE"
786
+ )
787
+
788
+ print("=" * 80)
789
+
790
+
791
+ print(
792
+ "Adapter saved to:"
793
+ )
794
+
795
+ print(
796
+ os.path.abspath(
797
+ OUTPUT_DIR
798
+ )
799
+ )
800
+
801
+
802
+ if result is not None:
803
+
804
+ print()
805
+
806
+ print(
807
+ "Training metrics:"
808
+ )
809
+
810
+ for key, value in result.metrics.items():
811
+
812
+ print(
813
+ f"{key}: {value}"
814
+ )
815
+
816
+
817
+ # ============================================================
818
+ # EXPECTED OUTPUT
819
+ # ============================================================
820
+
821
+ print()
822
+
823
+ print("=" * 80)
824
+
825
+ print(
826
+ "EXPECTED MODEL RESPONSE FORMAT"
827
+ )
828
+
829
+ print("=" * 80)
830
+
831
+ print(
832
+ """Probable Root Cause:
833
+ <probable root cause based only on supplied evidence>
834
+
835
+ Explanation:
836
+ <technical explanation>
837
+
838
+ Recommendation:
839
+ 1. <recommended action>
840
+ 2. <recommended action>
841
+ 3. <recommended action>
842
+
843
+ Fault Severity:
844
+ fault_severity=0|1|2
845
+ """
846
+ )
847
+
848
+ print("=" * 80)