File size: 25,628 Bytes
adfb728
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
"""

ULTIMATE LoRA Fine-Tuning Demo - Covers ALL Project Requirements

Group 6: Model Adaptation, Efficient Fine-Tuning & Deployment of LLMs

"""

import streamlit as st
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
from peft import PeftModel
import time
import psutil
import os

# Page configuration
st.set_page_config(
    page_title="LoRA Fine-Tuning Complete Demo",
    page_icon="๐Ÿค–",
    layout="wide",
    initial_sidebar_state="expanded"
)

# Custom CSS
st.markdown("""

<style>

    .main-header {

        font-size: 2.5rem;

        font-weight: bold;

        text-align: center;

        background: linear-gradient(120deg, #1f77b4, #00cc88);

        -webkit-background-clip: text;

        -webkit-text-fill-color: transparent;

        margin-bottom: 0.5rem;

    }

    .sub-header {

        text-align: center;

        color: #666;

        margin-bottom: 2rem;

        font-size: 1.1rem;

    }

    .metric-card {

        background: #f0f2f6;

        padding: 1rem;

        border-radius: 10px;

        border-left: 4px solid #1f77b4;

    }

    .model-box {

        padding: 1.5rem;

        border-radius: 10px;

        margin: 1rem 0;

        box-shadow: 0 2px 4px rgba(0,0,0,0.1);

    }

    .base-model {

        background-color: #fff5f5;

        border-left: 4px solid #ff4b4b;

    }

    .finetuned-model {

        background-color: #f0fff4;

        border-left: 4px solid #00cc88;

    }

    .theory-box {

        background: #e8f4f8;

        padding: 1.5rem;

        border-radius: 10px;

        margin: 1rem 0;

        border-left: 4px solid #1f77b4;

    }

</style>

""", unsafe_allow_html=True)

# Title
st.markdown('<div class="main-header">๐Ÿš€ Complete LoRA Fine-Tuning Demo</div>', unsafe_allow_html=True)
st.markdown('<div class="sub-header">Parameter-Efficient Fine-Tuning & Deployment Showcase</div>',
            unsafe_allow_html=True)

# Sidebar Navigation
with st.sidebar:
    st.header("๐Ÿ“š Navigation")
    page = st.radio(
        "Select Section:",
        ["๐ŸŽฏ Live Demo", "๐Ÿ“Š Theory & Concepts", "โš™๏ธ Technical Details", "๐Ÿš€ Deployment Info"],
        label_visibility="collapsed"
    )

    st.divider()

    if page == "๐ŸŽฏ Live Demo":
        st.header("โš™๏ธ Model Settings")

        device_option = st.selectbox(
            "Inference Device",
            ["Auto (GPU if available)", "Force CPU", "Force GPU"],
            help="Compare CPU vs GPU inference speed"
        )

        use_quantization = st.checkbox(
            "Use 8-bit Quantization",
            value=False,
            help="Reduces memory usage, slightly slower"
        )

        temperature = st.slider("Temperature", 0.1, 1.0, 0.3, 0.1)
        max_length = st.slider("Max Length", 50, 400, 200, 10)
        top_p = st.slider("Top P", 0.1, 1.0, 0.95, 0.05)

        st.divider()

        st.header("๐Ÿ“Š Quick Stats")
        col1, col2 = st.columns(2)
        with col1:
            st.metric("Base Model", "82M params")
            st.metric("Adapter Size", "~3 MB")
        with col2:
            st.metric("Trainable", "0.4%")
            st.metric("Training Time", "~30 min")


# Cache model loading
@st.cache_resource
def load_models(use_quantization=False, device_option="Auto"):
    """Load base model and fine-tuned model"""

    base_model_name = "distilgpt2"
    adapter_path = "./models/lora_adapters"

    # Determine device
    if device_option == "Force CPU":
        device = "cpu"
    elif device_option == "Force GPU":
        device = "cuda" if torch.cuda.is_available() else "cpu"
    else:
        device = "cuda" if torch.cuda.is_available() else "cpu"

    with st.spinner("๐Ÿ”„ Loading models..."):
        # Load tokenizer
        tokenizer = AutoTokenizer.from_pretrained(base_model_name)
        tokenizer.pad_token = tokenizer.eos_token

        # Quantization config
        if use_quantization and device == "cuda":
            quantization_config = BitsAndBytesConfig(
                load_in_8bit=True,
                llm_int8_threshold=6.0
            )
            base_model = AutoModelForCausalLM.from_pretrained(
                base_model_name,
                quantization_config=quantization_config,
                device_map="auto"
            )
            finetuned_model = AutoModelForCausalLM.from_pretrained(
                base_model_name,
                quantization_config=quantization_config,
                device_map="auto"
            )
            finetuned_model = PeftModel.from_pretrained(finetuned_model, adapter_path)
        else:
            # Standard loading
            base_model = AutoModelForCausalLM.from_pretrained(base_model_name)
            finetuned_model = AutoModelForCausalLM.from_pretrained(base_model_name)
            finetuned_model = PeftModel.from_pretrained(finetuned_model, adapter_path)

            base_model.to(device)
            finetuned_model.to(device)

    return tokenizer, base_model, finetuned_model, device


def get_model_size_mb(model):
    """Calculate model size in MB"""
    param_size = sum(p.nelement() * p.element_size() for p in model.parameters())
    buffer_size = sum(b.nelement() * b.element_size() for b in model.buffers())
    return (param_size + buffer_size) / (1024 ** 2)


def generate_response(model, tokenizer, prompt, device, temperature, max_length, top_p):
    """Generate response from a model"""
    formatted_input = f"### Instruction:\n{prompt}\n\n### Code:\n"
    inputs = tokenizer(formatted_input, return_tensors="pt", padding=True)
    inputs = {k: v.to(device) for k, v in inputs.items()}

    with torch.no_grad():
        outputs = model.generate(
            **inputs,
            max_length=max_length,
            temperature=temperature,
            top_p=top_p,
            do_sample=True,
            num_return_sequences=1,
            pad_token_id=tokenizer.eos_token_id,
            eos_token_id=tokenizer.eos_token_id
        )

    response = tokenizer.decode(outputs[0], skip_special_tokens=True)
    return response


# =============================================================================
# PAGE 1: LIVE DEMO
# =============================================================================
if page == "๐ŸŽฏ Live Demo":
    # Load models
    try:
        tokenizer, base_model, finetuned_model, device = load_models(
            use_quantization=use_quantization if 'use_quantization' in dir() else False,
            device_option=device_option if 'device_option' in dir() else "Auto"
        )

        # Show device info
        device_emoji = "๐Ÿš€" if device == "cuda" else "๐Ÿข"
        if device == "cuda":
            st.success(f"{device_emoji} Running on GPU: {torch.cuda.get_device_name(0)}")
        else:
            st.info(f"{device_emoji} Running on CPU (slower but works!)")

        # Show quantization status
        if use_quantization and device == "cuda":
            st.info("โšก 8-bit quantization enabled - Lower memory usage!")

    except Exception as e:
        st.error(f"โŒ Error loading models: {str(e)}")
        st.stop()

    # Sample prompts
    st.header("๐Ÿ’ฌ Try the Demo")

    sample_prompts = [
        "Write a Python function to calculate factorial",
        "Create a function to check if a string is palindrome",
        "Write code to merge two sorted lists",
        "Implement a function to find the largest element in a list",
        "Create a Python function to check if a number is prime",
        "Write code to reverse a linked list",
        "Implement binary search algorithm in Python"
    ]

    col1, col2 = st.columns([3, 1])
    with col1:
        use_sample = st.selectbox("Select prompt or write custom:", ["Custom"] + sample_prompts)
    with col2:
        st.write("")
        st.write("")

    if use_sample == "Custom":
        user_instruction = st.text_area(
            "Enter your instruction:",
            height=100,
            placeholder="e.g., Write a Python function to sort a dictionary by values"
        )
    else:
        user_instruction = use_sample
        st.info(f"๐Ÿ’ก Prompt: {user_instruction}")

    # Generate button
    if st.button("๐Ÿš€ Generate Responses", type="primary", use_container_width=True):
        if user_instruction.strip():

            col_base, col_finetuned = st.columns(2)

            with col_base:
                st.markdown('<div class="model-box base-model">', unsafe_allow_html=True)
                st.subheader("๐Ÿ”ด Base Model (Untrained)")

                with st.spinner("Generating..."):
                    start_time = time.time()
                    base_response = generate_response(
                        base_model, tokenizer, user_instruction, device,
                        temperature, max_length, top_p
                    )
                    base_time = time.time() - start_time

                st.code(base_response, language="python")
                st.caption(f"โฑ๏ธ Generation time: {base_time:.3f}s")
                st.markdown('</div>', unsafe_allow_html=True)

            with col_finetuned:
                st.markdown('<div class="model-box finetuned-model">', unsafe_allow_html=True)
                st.subheader("๐ŸŸข Fine-tuned Model (+ LoRA)")

                with st.spinner("Generating..."):
                    start_time = time.time()
                    finetuned_response = generate_response(
                        finetuned_model, tokenizer, user_instruction, device,
                        temperature, max_length, top_p
                    )
                    finetuned_time = time.time() - start_time

                st.code(finetuned_response, language="python")
                st.caption(f"โฑ๏ธ Generation time: {finetuned_time:.3f}s")
                st.markdown('</div>', unsafe_allow_html=True)

            # Performance Analysis
            st.divider()
            st.subheader("๐Ÿ“Š Performance Analysis")

            col1, col2, col3, col4 = st.columns(4)

            with col1:
                st.metric("Base Response", f"{len(base_response.split())} words")
            with col2:
                st.metric("Fine-tuned Response", f"{len(finetuned_response.split())} words")
            with col3:
                speed_diff = ((base_time - finetuned_time) / base_time) * 100
                st.metric("Speed Difference", f"{speed_diff:+.1f}%")
            with col4:
                st.metric("Device", device.upper())

            st.success("โœ… Notice: Base model produces gibberish, fine-tuned generates actual Python code!")

        else:
            st.warning("โš ๏ธ Please enter an instruction!")

# =============================================================================
# PAGE 2: THEORY & CONCEPTS
# =============================================================================
elif page == "๐Ÿ“Š Theory & Concepts":
    st.header("๐Ÿ“š Theory & Key Concepts")

    tab1, tab2, tab3, tab4 = st.tabs([
        "๐ŸŽ“ Pre-training vs Fine-tuning",
        "๐Ÿ”ง LoRA & PEFT",
        "โšก Training vs Inference",
        "๐Ÿ“ Trade-offs"
    ])

    with tab1:
        st.markdown('<div class="theory-box">', unsafe_allow_html=True)
        st.subheader("Pre-training vs Fine-tuning")

        col1, col2 = st.columns(2)

        with col1:
            st.markdown("### ๐Ÿ—๏ธ Pre-training")
            st.markdown("""

            - **Task**: Learn general language understanding

            - **Data**: Massive unlabeled text (billions of tokens)

            - **Cost**: Extremely expensive ($$$$$)

            - **Time**: Weeks to months

            - **Example**: GPT, BERT, LLaMA training

            - **Goal**: General purpose model

            """)

        with col2:
            st.markdown("### ๐ŸŽฏ Fine-tuning")
            st.markdown("""

            - **Task**: Adapt to specific domain/task

            - **Data**: Smaller labeled dataset (thousands)

            - **Cost**: Much cheaper ($$)

            - **Time**: Hours to days

            - **Example**: Code generation, Q&A, summarization

            - **Goal**: Specialized model

            """)

        st.divider()

        st.markdown("### ๐Ÿ“Š Our Project: Transfer Learning")
        st.info("""

        **We started with**: Pre-trained `distilgpt2` (general language model)  

        **We fine-tuned on**: Python code instructions (5000 samples)  

        **Result**: Model now generates Python code instead of general text!



        This is **Transfer Learning** - leveraging pre-trained knowledge for new tasks.

        """)
        st.markdown('</div>', unsafe_allow_html=True)

    with tab2:
        st.markdown('<div class="theory-box">', unsafe_allow_html=True)
        st.subheader("LoRA: Low-Rank Adaptation")

        col1, col2 = st.columns([1, 1])

        with col1:
            st.markdown("### ๐Ÿ”ด Full Fine-tuning (Expensive)")
            st.markdown("""

            ```

            Total Parameters: 82M

            Trainable: 82M (100%)

            Memory: High

            Time: Long

            GPU: Required (expensive)

            Checkpoint: 320 MB

            ```

            **Problems**:

            - โŒ Expensive GPUs needed

            - โŒ Long training time

            - โŒ Large model checkpoints

            - โŒ Risk of catastrophic forgetting

            """)

        with col2:
            st.markdown("### ๐ŸŸข LoRA Fine-tuning (Efficient)")
            st.markdown("""

            ```

            Total Parameters: 82M

            Trainable: 295K (0.36%)

            Memory: Low

            Time: Fast

            GPU: Optional (Colab free tier OK)

            Checkpoint: 3 MB

            ```

            **Advantages**:

            - โœ… Train on free GPUs

            - โœ… Fast training (~30 min)

            - โœ… Tiny adapter files

            - โœ… Preserve base model knowledge

            """)

        st.divider()

        st.markdown("### ๐Ÿงฎ How LoRA Works")
        st.markdown("""

        Instead of updating all weights `W`, LoRA adds small adapter matrices:



        ```

        W_new = W_frozen + ฮ”W

        where ฮ”W = B ร— A  (low-rank decomposition)

        ```



        **Our Configuration**:

        - `r = 16` (rank - controls adapter capacity)

        - `alpha = 32` (scaling factor)

        - Target modules: Attention layers only

        - Result: 99.6% fewer trainable parameters!

        """)
        st.markdown('</div>', unsafe_allow_html=True)

    with tab3:
        st.markdown('<div class="theory-box">', unsafe_allow_html=True)
        st.subheader("Training vs Inference")

        col1, col2 = st.columns(2)

        with col1:
            st.markdown("### ๐Ÿ‹๏ธ Training Phase")
            st.markdown("""

            **What happens**:

            - Forward pass through model

            - Calculate loss (prediction error)

            - Backward propagation (gradients)

            - Update weights (only LoRA adapters)



            **Requirements**:

            - GPU highly recommended

            - More memory needed

            - Longer time

            - Batch processing



            **Our Training**:

            - Dataset: 5000 Python code examples

            - Time: ~30 minutes (Colab T4 GPU)

            - Memory: ~8 GB VRAM

            - Output: 3 MB adapter file

            """)

        with col2:
            st.markdown("### ๐Ÿš€ Inference Phase")
            st.markdown("""

            **What happens**:

            - Load base model + adapters

            - Forward pass only (no backprop)

            - Generate predictions

            - No weight updates



            **Requirements**:

            - CPU works (slower)

            - GPU faster (optional)

            - Less memory

            - Real-time response



            **Our Deployment**:

            - Works on: CPU or GPU

            - Load time: ~10-30 seconds

            - Inference: ~1-3 seconds per response

            - Memory: ~2 GB RAM

            """)

        st.markdown('</div>', unsafe_allow_html=True)

    with tab4:
        st.markdown('<div class="theory-box">', unsafe_allow_html=True)
        st.subheader("Trade-offs & Optimization")

        st.markdown("### โš–๏ธ Key Trade-offs")

        col1, col2 = st.columns(2)

        with col1:
            st.markdown("#### ๐Ÿ“ Model Size vs Accuracy")
            st.markdown("""

            **Larger models**:

            - โœ… Better accuracy

            - โœ… More capacity

            - โŒ Slower inference

            - โŒ More memory



            **Smaller models**:

            - โœ… Faster inference

            - โœ… Less memory

            - โŒ Lower accuracy

            - โŒ Less capacity

            """)

        with col2:
            st.markdown("#### โšก Speed vs Quality")
            st.markdown("""

            **Higher quality**:

            - More parameters

            - Longer sequences

            - Lower temperature

            - โŒ Slower



            **Higher speed**:

            - Fewer parameters

            - Shorter sequences

            - Quantization

            - โŒ Potentially lower quality

            """)

        st.divider()

        st.markdown("### ๐Ÿ”ข Quantization")
        st.markdown("""

        **What**: Reduce precision of model weights (32-bit โ†’ 8-bit)



        **Benefits**:

        - 75% less memory usage

        - Faster inference on some hardware

        - Enables larger models on limited hardware



        **Cost**:

        - Slight accuracy loss (~1-2%)

        - Requires calibration



        **Try it**: Enable "8-bit quantization" in the sidebar on Demo page!

        """)

        st.markdown('</div>', unsafe_allow_html=True)

# =============================================================================
# PAGE 3: TECHNICAL DETAILS
# =============================================================================
elif page == "โš™๏ธ Technical Details":
    st.header("โš™๏ธ Technical Implementation")

    col1, col2 = st.columns(2)

    with col1:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.markdown("### ๐Ÿ“ฆ Model Architecture")
        st.markdown("""

        **Base Model**: distilgpt2

        - Type: Causal Language Model

        - Parameters: 82M

        - Layers: 6 transformer blocks

        - Hidden size: 768

        - Attention heads: 12

        - Vocabulary: 50,257 tokens

        """)
        st.markdown('</div>', unsafe_allow_html=True)

        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.markdown("### ๐Ÿ”ง LoRA Configuration")
        st.markdown("""

        ```python

        LoraConfig(

            r=16,                    # Rank

            lora_alpha=32,           # Scaling

            target_modules=["c_attn"], # Attention only

            lora_dropout=0.05,

            task_type="CAUSAL_LM"

        )

        ```



        **Trainable Parameters**: 294,912 (0.36%)

        **Adapter Size**: ~3 MB

        """)
        st.markdown('</div>', unsafe_allow_html=True)

    with col2:
        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.markdown("### ๐Ÿ“Š Dataset")
        st.markdown("""

        **Name**: Python Code Instructions (18k Alpaca)

        **Source**: `iamtarun/python_code_instructions_18k_alpaca`

        **Used**: 5000 samples

        - Training: 4500 samples

        - Validation: 500 samples



        **Format**:

        ```

        Instruction: Write Python code for X

        Code: def function()...

        ```

        """)
        st.markdown('</div>', unsafe_allow_html=True)

        st.markdown('<div class="metric-card">', unsafe_allow_html=True)
        st.markdown("### ๐Ÿ‹๏ธ Training Hyperparameters")
        st.markdown("""

        ```python

        Epochs: 4

        Batch size: 2 (per device)

        Gradient accumulation: 4

        Learning rate: 3e-4

        Max sequence length: 512

        Optimizer: AdamW

        Scheduler: Linear warmup

        ```



        **Training Time**: ~30 minutes (T4 GPU)

        **Final Loss**: ~2.5

        """)
        st.markdown('</div>', unsafe_allow_html=True)

    st.divider()

    st.markdown("### ๐Ÿ› ๏ธ Tools & Libraries Used")

    col1, col2, col3 = st.columns(3)

    with col1:
        st.markdown("""

        **Training**:

        - ๐Ÿค— Transformers

        - ๐ŸŽฏ PEFT (LoRA)

        - ๐Ÿš€ Accelerate

        - ๐Ÿ“Š Datasets

        - ๐Ÿ”ฅ PyTorch

        """)

    with col2:
        st.markdown("""

        **Deployment**:

        - ๐ŸŒ Streamlit

        - ๐Ÿค— Hugging Face Hub

        - โšก bitsandbytes (quantization)

        - ๐Ÿ’พ safetensors

        """)

    with col3:
        st.markdown("""

        **Infrastructure**:

        - ๐Ÿ““ Google Colab (training)

        - ๐Ÿ’ป Local deployment

        - โ˜๏ธ Hugging Face Spaces (optional)

        - ๐Ÿ”’ Git LFS (model versioning)

        """)

# =============================================================================
# PAGE 4: DEPLOYMENT INFO
# =============================================================================
else:  # Deployment Info
    st.header("๐Ÿš€ Deployment Options")

    tab1, tab2, tab3 = st.tabs(["๐Ÿ’ป Local", "โ˜๏ธ Cloud", "๐Ÿ“Š Comparison"])

    with tab1:
        st.markdown('<div class="theory-box">', unsafe_allow_html=True)
        st.markdown("### ๐Ÿ’ป Local Deployment (Current)")

        st.markdown("""

        **Advantages**:

        - โœ… Full control

        - โœ… No API costs

        - โœ… Data privacy

        - โœ… Works offline

        - โœ… Fast iteration



        **Requirements**:

        - Python 3.8+

        - 2-4 GB RAM

        - Optional: NVIDIA GPU



        **Setup**:

        ```bash

        pip install streamlit transformers peft torch

        streamlit run app.py

        ```



        **Best for**: Development, testing, demos

        """)
        st.markdown('</div>', unsafe_allow_html=True)

    with tab2:
        st.markdown('<div class="theory-box">', unsafe_allow_html=True)
        st.markdown("### โ˜๏ธ Cloud Deployment")

        st.markdown("#### ๐Ÿค— Hugging Face Spaces (Recommended)")
        st.markdown("""

        **Features**:

        - โœ… Free tier available

        - โœ… Auto-deploys from Git

        - โœ… Public URL

        - โœ… No server management

        - โœ… Built-in CI/CD



        **Setup**:

        1. Create account on huggingface.co

        2. Create new Space (Streamlit)

        3. Upload: app.py, requirements.txt, models/

        4. Auto-deploys!



        **URL**: `https://huggingface.co/spaces/YOUR_USERNAME/lora-demo`

        """)

        st.divider()

        st.markdown("#### Other Options")

        col1, col2 = st.columns(2)

        with col1:
            st.markdown("""

            **Streamlit Cloud**:

            - Free for public apps

            - GitHub integration

            - Easy deployment

            - Resource limits

            """)

        with col2:
            st.markdown("""

            **AWS/GCP/Azure**:

            - Full control

            - Scalable

            - More expensive

            - Requires devops

            """)

        st.markdown('</div>', unsafe_allow_html=True)

    with tab3:
        st.markdown('<div class="theory-box">', unsafe_allow_html=True)
        st.markdown("### ๐Ÿ“Š Deployment Comparison")

        comparison_data = {
            "Feature": ["Cost", "Setup Time", "Control", "Scalability", "Maintenance", "Best For"],
            "Local": ["Free", "5 mins", "Full", "Limited", "Manual", "Development"],
            "HF Spaces": ["Free", "10 mins", "Medium", "Auto", "Minimal", "Demos"],
            "Cloud (AWS)": ["$$$", "1-2 hours", "Full", "High", "Manual", "Production"]
        }

        st.table(comparison_data)

        st.divider()

        st.markdown("### ๐ŸŽฏ CPU vs GPU Inference")

        col1, col2 = st.columns(2)

        with col1:
            st.markdown("""

            **CPU Inference**:

            - Speed: 2-5 seconds/response

            - Cost: $0 (uses existing hardware)

            - Memory: ~2 GB RAM

            - Best for: Low-traffic apps, development

            """)

        with col2:
            st.markdown("""

            **GPU Inference**:

            - Speed: 0.5-2 seconds/response

            - Cost: $0.50-2/hour (cloud)

            - Memory: ~4-8 GB VRAM

            - Best for: High-traffic, real-time apps

            """)

        st.info("๐Ÿ’ก **Tip**: Start with CPU deployment, upgrade to GPU only if needed!")

        st.markdown('</div>', unsafe_allow_html=True)

# Footer
st.divider()
st.markdown("""

<div style="text-align: center; color: #666; padding: 1rem;">

    <p><strong>๐ŸŽ“ Group 6: Model Adaptation, Efficient Fine-Tuning & Deployment of LLMs</strong></p>

    <p>Built with Streamlit โ€ข Transformers โ€ข PEFT โ€ข PyTorch</p>

</div>

""", unsafe_allow_html=True)