File size: 11,559 Bytes
16c29a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50b1857
 
16c29a6
 
 
 
50b1857
16c29a6
 
 
 
 
 
 
 
50b1857
16c29a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50b1857
16c29a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50b1857
 
 
 
 
 
 
 
 
 
 
 
 
 
16c29a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50b1857
 
 
 
 
 
 
 
 
 
 
 
 
 
16c29a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import subprocess
import os
import shutil

def clone_dataset_scenario(repo_url, model_repo_dir="./LWM", scenarios_dir="scenarios"):
    """

    Clones all scenarios from a repository, ensuring all files (small and large) are downloaded.



    Args:

        repo_url (str): URL of the Git repository

        model_repo_dir (str): Path to the model repository

        scenarios_dir (str): Directory name for storing scenarios

    """
    current_dir = os.path.basename(os.getcwd())
    if current_dir == "LWM":
        model_repo_dir = "."

    scenarios_path = os.path.join(model_repo_dir, scenarios_dir)
    os.makedirs(scenarios_path, exist_ok=True)

    original_dir = os.getcwd()

    try:
        if os.path.exists(scenarios_path):
            shutil.rmtree(scenarios_path)

        print("Cloning entire repository into temporary directory ...")
        subprocess.run([
            "git", "clone",
            repo_url,
            scenarios_path
        ], check=True)

        os.chdir(scenarios_path)

        print("Pulling all files using Git LFS ...")
        subprocess.run(["git", "lfs", "install"], check=True) 
        subprocess.run(["git", "lfs", "pull"], check=True) 

        print(f"Successfully cloned all scenarios into {scenarios_path}")

    except subprocess.CalledProcessError as e:
        print(f"Error cloning scenarios: {str(e)}")
    finally:
        if os.path.exists(scenarios_path):
            shutil.rmtree(scenarios_path)
        os.chdir(original_dir)
#%%
model_repo_url = "https://huggingface.co/wi-lab/lwm"
model_repo_dir = "./LWM"

if not os.path.exists(model_repo_dir):
    print(f"Cloning model repository from {model_repo_url}...")
    subprocess.run(["git", "clone", model_repo_url, model_repo_dir], check=True)
#%%
import numpy as np
dataset_repo_url = "https://huggingface.co/datasets/wi-lab/lwm" 
clone_dataset_scenario(dataset_repo_url, model_repo_dir)
#%%
if os.path.exists(model_repo_dir):
    os.chdir(model_repo_dir)
    print(f"Changed working directory to {os.getcwd()}")
else:
    print(f"Directory {model_repo_dir} does not exist. Please check if the repository is cloned properly.")
#%%
from input_preprocess import tokenizer
from lwm_model import lwm
import torch

scenario_names = np.array([
    "city_18_denver", "city_15_indianapolis", "city_19_oklahoma", 
    "city_12_fortworth", "city_11_santaclara", "city_7_sandiego"
])
scenario_idxs = np.array([0, 1, 2, 3, 4, 5])[3] 
selected_scenario_names = scenario_names[scenario_idxs]

snr_db = None

preprocessed_chs = tokenizer(
    selected_scenario_names=selected_scenario_names,
    manual_data=None,
    gen_raw=True,
    snr_db=snr_db
)

device = 'cuda' if torch.cuda.is_available() else 'cpu'
print(f"Loading the LWM model on {device} ...")
model = lwm.from_pretrained(device=device)
#%%
from inference import lwm_inference, create_raw_dataset
input_types = ['cls_emb', 'channel_emb', 'raw']
selected_input_type = input_types[1] 

if selected_input_type in ['cls_emb', 'channel_emb']:
    dataset = lwm_inference(preprocessed_chs, selected_input_type, model, device)
else:
    dataset = create_raw_dataset(preprocessed_chs, device)
#%%
from input_preprocess import create_labels
n_beams = 16
tasks = ['LoS/NLoS Classification', 'Beam Prediction']
task = tasks[0]
labels = create_labels(task, selected_scenario_names, n_beams=n_beams) 
# %% Dimensionality Reduction Visualization

# Import the dimensionality reduction plotting function
from utils import plot_dimensionality_reduction

# Iterate over tasks (e.g., LoS/NLoS Classification, Beam Prediction)
for task in tasks:
    
    # Create labels for the current task
    labels = create_labels(task, selected_scenario_names, n_beams=n_beams)
    
    # Iterate over input types (e.g., raw data or embeddings)
    for input_type_idx, input_type in enumerate(input_types):
        
        # Select the current input type
        selected_input_type = input_types[input_type_idx]
        
        # Prepare dataset based on input type
        if selected_input_type in ['cls_emb', 'channel_emb']:
            dataset = lwm_inference(
                preprocessed_chs, 
                selected_input_type, 
                model, 
                device
            )
        else:
            dataset = create_raw_dataset(preprocessed_chs, device)
        
        # Plot dimensionality reduction for the dataset
        plot_dimensionality_reduction(
            dataset, 
            method='all',  # Use all available dimensionality reduction methods
            labels=labels,  # Labels for visualization
            task=task,  # Current task (for title or labeling)
            input_type=input_type  # Current input type (for title or labeling)
        )
        
#%% TRAINING
#%% TRAINING PARAMETERS
task = ['LoS/NLoS Classification', 'Beam Prediction'][0] # Select the task
n_trials = 1  # Number of trials for each configuration
num_classes = 2 if task == 'LoS/NLoS Classification' else n_beams  # Set number of classes based on the task
input_types = ['raw', 'cls_emb']  # Types of input data
split_ratios = np.array([.005, .0075, .01, .015, .02, .03, 
                         .05, .1, .25, .5, .8])  # Dataset split ratios
f1_scores = np.zeros((n_trials, len(input_types), len(split_ratios)))  # Store F1 scores for each trial, input type, and split ratio
labels = create_labels(task, selected_scenario_names, n_beams=n_beams)  # Create labels for the selected task

#%% TRAINING
from utils import get_data_loaders, FCN, train_model, plot_metrics

# Iterate over input types (e.g., raw data or embeddings)
for input_type_idx, input_type in enumerate(input_types):
    
    # Prepare dataset based on input type
    if input_type in ['cls_emb', 'channel_emb']:
        dataset = lwm_inference(preprocessed_chs, input_type, model, device)
    else:
        dataset = create_raw_dataset(preprocessed_chs, device)
    
    # Reshape dataset for training
    dataset = dataset.view(dataset.size(0), -1)
    input_dim = dataset.shape[-1]  # Get input dimension for the model
    
    # Iterate over different dataset split ratios
    for split_ratio_idx, split_ratio in enumerate(split_ratios):
        
        n_train = int(split_ratio * dataset.shape[0])  # Calculate number of training samples
        
        # Run multiple trials for each split ratio
        for trial in range(n_trials):
            
            print(f"\ninput type: {input_type}, \nnumber of training samples: {int(split_ratio*len(dataset))}, \ntrial: {trial}\n")
            
            torch.manual_seed(trial)  # Set seed for reproducibility
            
            if snr_db is not None:
                preprocessed_chs = tokenizer(
                    selected_scenario_names=selected_scenario_names,
                    manual_data=None,
                    gen_raw=True,
                    snr_db=snr_db
                )
                if input_type in ['cls_emb', 'channel_emb']:
                    dataset = lwm_inference(preprocessed_chs, input_type, model, device)
                else:
                    dataset = create_raw_dataset(preprocessed_chs, device)
                dataset = dataset.view(dataset.size(0), -1)
                
            train_loader, test_loader = get_data_loaders(
                dataset, 
                labels, 
                batch_size=128, 
                split_ratio=split_ratio
            )
            
            # Initialize the Fully Connected Network (FCN) model
            FCN_model = FCN(input_dim=input_dim, num_classes=num_classes)
            
            # Train the model and retrieve losses and F1 scores
            train_losses, test_f1_scores = train_model(
                FCN_model, 
                train_loader, 
                test_loader, 
                epochs=120, 
                lr=0.0001 if input_type == "raw" else 0.001,  # Learning rate depends on input type
                device=device, 
                decay_step=30, 
                decay_rate=0.5
            )
            
            # Store the final F1 score for this trial
            f1_scores[trial, input_type_idx, split_ratio_idx] = test_f1_scores[0, -1]
            
            # Plot metrics for the current trial
            # plot_metrics(test_f1_scores, [input_type])

# Plot average F1 scores across all trials for each input type and split ratio
plot_metrics(
    np.mean(f1_scores, axis=0),  # Average F1 scores across trials
    input_types, 
    np.asarray(split_ratios * dataset.shape[0], dtype=int),  # Convert split ratios to actual sample counts
    flag=1
)

# %% Few-Shot Learning with Pretrained Embeddings

# Initialize array to store F1 scores for KNN classification
f1_scores_knn = np.zeros((n_trials, len(input_types), len(split_ratios)))

# Import the classification function
from utils import classify_by_euclidean_distance

# Iterate over input types (e.g., raw data or embeddings)
for input_type_idx, input_type in enumerate(input_types):
    
    # Prepare dataset based on input type
    if input_type in ['cls_emb', 'channel_emb']:
        dataset = lwm_inference(preprocessed_chs, input_type, model, device)
    else:
        dataset = create_raw_dataset(preprocessed_chs, device)
    
    # Reshape dataset for compatibility
    dataset = dataset.view(dataset.size(0), -1)
    input_dim = dataset.shape[-1]  # Get input dimension
    
    # Iterate over different dataset split ratios
    for split_ratio_idx, split_ratio in enumerate(split_ratios):
        
        n_train = int(split_ratio * dataset.shape[0])  # Calculate number of training samples
        
        # Run multiple trials for each split ratio
        for trial in range(n_trials):
            
            torch.manual_seed(trial)  # Set seed for reproducibility
            
            if snr_db is not None:
                preprocessed_chs = tokenizer(
                    selected_scenario_names=selected_scenario_names,
                    manual_data=None,
                    gen_raw=True,
                    snr_db=snr_db
                )
                if input_type in ['cls_emb', 'channel_emb']:
                    dataset = lwm_inference(preprocessed_chs, input_type, model, device)
                else:
                    dataset = create_raw_dataset(preprocessed_chs, device)
                dataset = dataset.view(dataset.size(0), -1)
            
            train_loader, test_loader = get_data_loaders(
                dataset, 
                labels, 
                batch_size=128, 
                split_ratio=split_ratio
            )
            
            # Perform classification using Euclidean distance
            f1 = classify_by_euclidean_distance(
                train_loader, 
                test_loader, 
                device="cpu"
            )
            
            # Store the F1 score for this trial
            f1_scores_knn[trial, input_type_idx, split_ratio_idx] = f1

# Plot average F1 scores across all trials for each input type and split ratio
plot_metrics(
    np.mean(f1_scores_knn, axis=0),  # Average F1 scores across trials
    input_types, 
    np.asarray(split_ratios * dataset.shape[0], dtype=int),  # Convert split ratios to actual sample counts
    flag=1
)