
FILE sources/0183/CYFang6__FedPHA__316004f77b98/trainers/GL_SVDMSE_HE.py
SHA256 6c8d5262e12b3383dd0ea1321cc60b330f468ff9a25707a1f9719d97b4f73f83

38: class TextEncoder(nn.Module):
39:     def __init__(self, clip_model):
40:         super().__init__()
41:         self.transformer = clip_model.transformer
42:         self.positional_embedding = clip_model.positional_embedding
43:         self.ln_final = clip_model.ln_final
44:         self.text_projection = clip_model.text_projection
45:         self.dtype = clip_model.dtype
46: 
47:     def forward(self, prompts, tokenized_prompts):
48: 
49:         x = prompts + self.positional_embedding.type(self.dtype)
50:         
51:         x = x.permute(1, 0, 2)  # NLD -> LND
52:         x = self.transformer(x)
53:         x = x.permute(1, 0, 2)  # LND -> NLD
54:         x = self.ln_final(x).type(self.dtype)
55:         
56:         x = x[torch.arange(x.shape[0]), tokenized_prompts.argmax(dim=-1)] @ self.text_projection
57: 
58:         return x

103:                     nn.init.normal_(param, std=0.02)
104:             
105:             max_prompt_length = max(self.n_ctx_global, max(self.user_prompt_lengths))
106:             prompt_prefix = " ".join(["X"] * max_prompt_length)    
107: 
108:         print(f'Initial context (local/global): "{prompt_prefix}"')
109:         print(f"Number of context words (tokens) -> global: {self.n_ctx_global}, per client local lengths: {self.user_prompt_lengths}")
110: 
111:         classnames = [name.replace("_", " ") for name in classnames]   
112:         name_lens = [len(_tokenizer.encode(name)) for name in classnames]
113:         prompts = [prompt_prefix + " " + name + "." for name in classnames]
114: 
115:         tokenized_prompts = torch.cat([clip.tokenize(p) for p in prompts])   
116:         tokenized_prompts = tokenized_prompts.repeat(self.N, 1) 
117: 
118:         with torch.no_grad():
119:             embedding = clip_model.token_embedding(tokenized_prompts).type(dtype) 
120: 
121:         # These token vectors will be saved when in save_model(),
122:         # but they should be ignored in load_model() as we want to use
123:         # those computed using the current class names
124:         self.register_buffer("token_prefix", embedding[:, :1, :])  # SOS
125:         self.register_buffer("token_suffix", embedding[:, 1 + max_prompt_length:, :])  # CLS, EOS
126: 
127:         self.n_cls = n_cls
128:         self.tokenized_prompts = tokenized_prompts  # torch.Tensor
129:         self.name_lens = name_lens
130:         self.class_token_position = cfg.TRAINER.GL_SVDMSE_HE.CLASS_TOKEN_POSITION
131: 
132:     def compute_null_space(self, global_ctx, ratio=0.8):
133:         global_ctx = global_ctx.view(-1, global_ctx.shape[-1]) 
134:         global_ctx = global_ctx.to(torch.float32)
135:         
136:         try:
137:             U, S, V = torch.svd(global_ctx)   
138:             # U = [len, len]
139:             # S = [len]
140:             # V = [dim, len]
141:         except RuntimeError as e:
142:             print(f"SVD failed on GPU: {e}")
143:             global_ctx_cpu = global_ctx.cpu()
144:             U, S, V = torch.svd(global_ctx_cpu)
145:             V = V.to(global_ctx.device)
146:         cutoff = int(S.shape[0] * (1 - ratio))
147:         V2 = V[:, cutoff:]
148:         return V2.to(global_ctx.dtype)

150:     def forward(self, idx):
151:         if idx < 0 or idx >= len(self.user_prompt_lengths):
152:             raise ValueError(f"Invalid idx: {idx}")
153: 
154:         n_ctx_local = self.user_prompt_lengths[idx]
155:         n_ctx_global = self.n_ctx_global
156: 
157:         for i, param in enumerate(self.ctx_local_list):
158:             param.requires_grad_(False)
159: 
160:         self.ctx_local_list[idx].requires_grad_(True)
161:         
162:         ctx_local = self.ctx_local_list[idx]    # [n_ctx_local, dim]
163:         ctx_global = self.ctx_global            # [n_ctx_global, dim]
164:         null_space = self.compute_null_space(ctx_global, self.ratio)  # [dim, len(1-ratio)]
165: 
166:         ctx_flat = ctx_local.view(-1, ctx_local.shape[-1])  # [n_ctx_local, dim]
167:         null_space = null_space.to(ctx_flat.dtype)
168: 
169:         projected_ctx = torch.mm(ctx_flat, torch.mm(null_space, null_space.T))  # [n_ctx_local, dim]
170:         projected_ctx_local = projected_ctx.view(ctx_local.shape)  # [n_ctx_local, dim]
171:         
172:         ctx_local = ctx_local.unsqueeze(0).expand(self.n_cls, -1, -1)                                       # [n_cls, n_ctx_local, dim]
173:         ctx_local = ctx_local.contiguous().view(self.n_cls * self.N, n_ctx_local, -1)                       # [N*n_cls, n_ctx_local, dim]
174:         ctx_global = ctx_global.unsqueeze(0).expand(self.n_cls, -1, -1)                                     # [n_cls, n_ctx_global_local, dim]
175:         ctx_global = ctx_global.contiguous().view(self.n_cls * self.N, n_ctx_global, -1)                    # [N*n_cls, n_ctx_global, dim]
176:         projected_ctx_local = projected_ctx_local.unsqueeze(0).expand(self.n_cls, -1, -1)                   # [n_cls, n_ctx_local, dim]
177:         projected_ctx_local = projected_ctx_local.contiguous().view(self.n_cls * self.N, n_ctx_local, -1)   # [N*n_cls, n_ctx_local, dim]
178:         
179:         prefix = self.token_prefix
180:         suffix = self.token_suffix
181: 
182:         if self.class_token_position == "end":
183:             prompts = torch.cat(
184:                 [
185:                     prefix,  # (n_cls, 1, dim)
186:                     ctx_local,     # (n_cls, n_ctx, dim)
187:                     suffix,  # (n_cls, *, dim)
188:                 ],
189:                 dim=1,
190:             )
191:             prompts_global = torch.cat(
192:                 [
193:                     prefix,  # (n_cls, 1, dim)
194:                     ctx_global,  # (n_cls, n_ctx, dim)
195:                     suffix,  # (n_cls, *, dim)
196:                 ],
197:                 dim=1,
198:             )
199:             prompts_projected_local = torch.cat(
200:                 [
201:                     prefix,  # (n_cls, 1, dim)
202:                     projected_ctx_local,  # (n_cls, n_ctx, dim)
203:                     suffix,  # (n_cls, *, dim)
204:                 ],
205:                 dim=1,

253: 
254:         prompts = self.pad_to_77(prompts)
255:         prompts_global = self.pad_to_77(prompts_global)
256:         prompts_projected_local = self.pad_to_77(prompts_projected_local)
257:         
258:         return prompts, prompts_global, prompts_projected_local
259:     
260:     def pad_to_77(self, prompts):
261:         cur_len = prompts.shape[1]
262:         if cur_len < 77:
263:             pad_len = 77 - cur_len
264:             pad_zeros = torch.zeros(
265:                 prompts.size(0), pad_len, prompts.size(2),
266:                 dtype=prompts.dtype, device=prompts.device
267:             )
268:             prompts = torch.cat([prompts, pad_zeros], dim=1)
269:         elif cur_len > 77:
270:             prompts = prompts[:, :77, :]
271:         return prompts
272: 
273: class CustomCLIP(nn.Module):
274:     def __init__(self, cfg, classnames, clip_model):
275:         super().__init__()
276:         self.n_cls = len(classnames)
277:         self.prompt_learner = PromptLearner(cfg, classnames, clip_model)
278:         self.tokenized_prompts = self.prompt_learner.tokenized_prompts
279:         self.image_encoder = clip_model.visual
280:         self.text_encoder = TextEncoder(clip_model)
281:         self.logit_scale = clip_model.logit_scale
282:         self.dtype = clip_model.dtype
283:         self.N = cfg.TRAINER.GL_SVDMSE_HE.N
284: 
285:     def forward(self, image, idx):
286:         tokenized_prompts = self.tokenized_prompts
287:         prompts, prompts_global, prompts_projected_local = self.prompt_learner(idx)
288:         # Compute the prompted image and text features
289:         text_features = self.text_encoder(prompts, tokenized_prompts)
290:         text_features = text_features / text_features.norm(dim=-1, keepdim=True)
291:         image_features = self.image_encoder(image.type(self.dtype))
292:         image_features = image_features / image_features.norm(dim=-1, keepdim=True)
293: 
294:         # Compute the prompted logits
295:         logit_scale = self.logit_scale.exp()
296:         logits = logit_scale * image_features @ text_features.t()  
297:         
298:         if self.training == True:
299:             text_features_global = self.text_encoder(prompts_global, tokenized_prompts)
300:             text_features_global = text_features_global / text_features_global.norm(dim=-1, keepdim=True)
301:             text_features_projected_local = self.text_encoder(prompts_projected_local, tokenized_prompts)
302:             text_features_projected_local = text_features_projected_local / text_features_projected_local.norm(dim=-1, keepdim=True)
303:             logits_global = logit_scale * image_features @ text_features_global.t()  
304:             return logits, text_features_global, text_features, text_features_projected_local, logits_global
305:         
306:         return logits

349:         else:
350:             self.model.to(self.device)
351:         
352:         # NOTE: only give prompt_learner to the optimizer
353:         self.optim = build_optimizer(self.model.prompt_learner, cfg.OPTIM)
354:         self.sched = build_lr_scheduler(self.optim, cfg.OPTIM)
355:         self.register_model("prompt_learner", self.model.prompt_learner, self.optim, self.sched)
356: 
357:         self.scaler = GradScaler() if cfg.TRAINER.GL_SVDMSE_HE.PREC == "amp" else None
358: 
359: 
360:     def forward_backward(self, batch_idx, batch, idx=-1, **kwargs):
361:         image, label = self.parse_batch_train(batch)
362:         prec = self.cfg.TRAINER.GL_SVDMSE_HE.PREC
363: 
364:         if prec == "amp":
365:             with autocast():
366:                 output = self.model(image)
367:                 loss = F.cross_entropy(output, label)
368:             self.optim.zero_grad()
369:             self.scaler.scale(loss).backward()
370:             self.scaler.step(self.optim)
371:             self.scaler.update()
372:         else:
373:             output, global_features, local_features, projected_local_features, output_global= self.model(image, idx)
374: 
375:             pull_loss = F.mse_loss(local_features, projected_local_features)
376:             alpha = self.alpha  
377:             push_loss = F.relu(alpha - torch.norm(local_features - global_features, dim=-1)).mean() 
378:             
379:             loss = F.cross_entropy(output, label)
380:             loss1 = F.cross_entropy(output_global, label)
381:             loss += loss1
382:             loss += pull_loss + push_loss
383:             self.model_backward_and_update(loss)
384: 
385:         loss_summary = {
386:             "loss": loss.item(),
387:             "acc": compute_accuracy(output, label)[0].item(),
388:         }
389: 

FILE sources/0183/CYFang6__FedPHA__316004f77b98/trainers/GL_SVDMSE.py
SHA256 33f013c18bbd5b18c4eaa09ccb3c1e0ecee3b2ff93081ce3aae614b7ecdc9d80

129:     def compute_null_space(self, global_ctx, ratio=0.8):
130:         global_ctx = global_ctx.view(-1, global_ctx.shape[-1])  # Flatten: (N * n_ctx, ctx_dim)
131:         global_ctx = global_ctx.to(torch.float32)
132:         
133:         try:
134:             U, S, V = torch.svd(global_ctx)           
135:             # U = [len, len]
136:             # S = [len]
137:             # V = [dim, dim]
138:         except RuntimeError as e:
139:             print(f"SVD failed on GPU: {e}")
140:             global_ctx_cpu = global_ctx.cpu()
141:             U, S, V = torch.svd(global_ctx_cpu)
142:             V = V.to(global_ctx.device)
143: 
144:         cutoff = int(S.shape[0] * (1 - ratio))
145:         V2 = V[:, cutoff:]
146: 
147:         return V2.to(global_ctx.dtype)
148: 
149:     def forward(self):
150:         ctx = self.ctx_local
151: 
152:         ctx = ctx.unsqueeze(0).expand(self.n_cls, -1, -1, -1)
153:         ctx = ctx.permute(1, 0, 2, 3).contiguous().view(self.N * self.n_cls, self.n_ctx, ctx.shape[-1])
154:         
155:         ctx_global = self.ctx_global
156:         null_space = self.compute_null_space(ctx_global, self.ratio)  
157:         
158:         ctx_global = ctx_global.unsqueeze(0).expand(self.n_cls, -1, -1, -1)
159:         ctx_global = ctx_global.permute(1, 0, 2, 3).contiguous().view(self.N * self.n_cls, self.n_ctx, ctx_global.shape[-1])
160: 
161:         ctx_flat = self.ctx_local.view(-1, self.ctx_local.shape[-1])  # Flatten [ctx, 512]
162:         null_space = null_space.to(ctx_flat.dtype)
163: 
164:         projected_ctx = torch.mm(ctx_flat, torch.mm(null_space, null_space.T))
165:         projected_ctx_local = projected_ctx.view(self.ctx_local.shape)

252:         self.tokenized_prompts = self.prompt_learner.tokenized_prompts
253:         self.image_encoder = clip_model.visual
254:         self.text_encoder = TextEncoder(clip_model)
255:         self.logit_scale = clip_model.logit_scale
256:         self.dtype = clip_model.dtype
257:         self.N = cfg.TRAINER.GL_SVDMSE.N
258: 
259:     def forward(self, image, idx=None):
260:         tokenized_prompts = self.tokenized_prompts
261:         # tokenized_prompts_half = self.tokenized_prompts_half
262:         prompts, prompts_global, prompts_projected_local = self.prompt_learner()
263:         # Compute the prompted image and text features
264:         text_features = self.text_encoder(prompts, tokenized_prompts)
265:         text_features = text_features / text_features.norm(dim=-1, keepdim=True)
266:         image_features = self.image_encoder(image.type(self.dtype))
267:         image_features = image_features / image_features.norm(dim=-1, keepdim=True)
268:                 
269:         # Compute the prompted logits
270:         logit_scale = self.logit_scale.exp()
271:         logits = logit_scale * image_features @ text_features.t()  
272:         
273:         if self.training == True:
274:             text_features_global = self.text_encoder(prompts_global, tokenized_prompts)
275:             text_features_global = text_features_global / text_features_global.norm(dim=-1, keepdim=True)
276:             text_features_projected_local = self.text_encoder(prompts_projected_local, tokenized_prompts)
277:             text_features_projected_local = text_features_projected_local / text_features_projected_local.norm(dim=-1, keepdim=True)
278:             logits_global = logit_scale * image_features @ text_features_global.t()  
279:             return logits, text_features_global, text_features, text_features_projected_local, logits_global
280:         
281:         return logits
282: 
283: 

345:             self.scaler.step(self.optim)
346:             self.scaler.update()
347:         else:
348:             output, global_features, local_features, projected_local_features, output_global= self.model(image)
349: 
350:             pull_loss = F.mse_loss(local_features, projected_local_features)
351: 
352:             alpha = self.alpha 
353:             push_loss = F.relu(alpha - torch.norm(local_features - global_features, dim=-1)).mean()
354:             lambda_pull = 1.0
355:             lambda_push = 1.0
356:             
357:             loss = F.cross_entropy(output, label)
358:             loss2 = F.cross_entropy(output_global, label)
359:             loss += loss2
360:             loss += lambda_pull * pull_loss + lambda_push * push_loss
361:             self.model_backward_and_update(loss)
362: 
363:         loss_summary = {
364:             "loss": loss.item(),
365:             "acc": compute_accuracy(output, label)[0].item(),
366:         }
367: 
368:         if (self.batch_idx + 1) == self.num_batches:
369:             self.update_lr()
370: 
371:         return loss_summary
372: 
373:     def parse_batch_train(self, batch):
374:         input = batch["img"]
375:         label = batch["label"]

FILE sources/0183/CYFang6__FedPHA__316004f77b98/federated_main.py
SHA256 199349613e635b3553708b18ec1106f014c920019633507c8c7d6fbaad4e2a26

296:             # global prompt + local prompt
297: 
298:             idxs_users = list(range(0, cfg.DATASET.USERS))
299:             print("idxs_users", idxs_users)
300: 
301:             print("------------local train start epoch:", epoch, "-------------")
302:             for idx in idxs_users:
303:                 if epoch == 0:
304:                     local_trainer.model.load_state_dict(global_weights, strict=False)
305:                 else:
306:                     local_trainer.model.load_state_dict(local_weights_per[idx], strict=False)
307:                 local_trainer.train(idx=idx, global_epoch=epoch, is_fed=True)
308:                 local_weight = local_trainer.model.state_dict()
309:                 local_weights_0[idx] = copy.deepcopy(local_weight['prompt_learner.ctx_global'])
310:                 local_weights_1[idx] = copy.deepcopy(local_weight['prompt_learner.ctx_local'])
311: 
312:             print("------------local train finish epoch:", epoch, "-------------")
313: 
314:             global_weights = average_weights(local_weights_0, idxs_users, datanumber_client, islist=True)
315: 
316:             print("------------local test start-------------")
317:             results = []
318:             all_users = list(range(0, cfg.DATASET.USERS))
319: 
320:             for idx in all_users:
321:                 local_weights_per[idx]['prompt_learner.ctx_global'] = global_weights
322:                 local_weights_per[idx]['prompt_learner.ctx_local'] = local_weights_1[idx]
323: 
324:             for idx in all_users:
325:                 local_trainer.model.load_state_dict(local_weights_per[idx], strict=False)
326:                 results.append(local_trainer.test(idx=idx))
327:             # global_test_acc = show_results(cfg, results, epoch)
328:             global_test_acc, global_test_acc_dict = show_results(cfg, results, epoch, global_test_acc_dict)
329:             global_time_list.append(time.time() - start)
330:             print("------------local test finish-------------")
331:             
332:         elif args.trainer == 'GL_SVDMSE_HE':
333:             # global prompt + local prompt
334: 
335:             idxs_users = list(range(0, cfg.DATASET.USERS))
336:             print("idxs_users", idxs_users)
337: 
338:             print("------------local train start epoch:", epoch, "-------------")
339:             for idx in idxs_users:
340:                 if epoch == 0:
341:                     local_trainer.model.load_state_dict(global_weights, strict=False)
342:                 else:
343:                     local_trainer.model.load_state_dict(local_weights_per[idx], strict=False)
344:                 local_trainer.train(idx=idx, global_epoch=epoch, is_fed=True)
345:                 local_weight = local_trainer.model.state_dict()
346:                 local_weights_0[idx] = copy.deepcopy(local_weight['prompt_learner.ctx_global'])
347:                 local_weights_1[idx] = {}
348:                 for i, param_name in enumerate([f'prompt_learner.ctx_local_list.{i}' for i in range(len(local_trainer.model.prompt_learner.ctx_local_list))]):
349:                     local_weights_1[idx][i] = copy.deepcopy(local_weight[param_name])
350: 
351:             print("------------local train finish epoch:", epoch, "-------------")
352: 
353:             global_weights = average_weights(local_weights_0, idxs_users, datanumber_client, islist=True)
354: 
355:             print("------------local test start-------------")
356:             results = []
357:             all_users = list(range(0, cfg.DATASET.USERS))
358: 
359:             for idx in all_users:
360:                 local_weights_per[idx]['prompt_learner.ctx_global'] = global_weights
361:                 for i, param_name in enumerate([f'prompt_learner.ctx_local_list.{i}' for i in range(len(local_trainer.model.prompt_learner.ctx_local_list))]):
362:                     local_weights_per[idx][param_name] = local_weights_1[idx][i]
363: 
364:             for idx in all_users:
365:                 local_trainer.model.load_state_dict(local_weights_per[idx], strict=False)
366:                 results.append(local_trainer.test(idx=idx))
367:             # global_test_acc = show_results(cfg, results, epoch)

FILE sources/0183/CYFang6__FedPHA__316004f77b98/utils/fed_utils.py
SHA256 1d57b33e59e83be34bab87e0f990400e1f4eb9bdc19132401d4c2c7043c1c909

1: import torch
2: import copy
3: from prettytable import PrettyTable
4: import numpy as np
5: from torch.nn import functional as F
6: 
7: def show_results(cfg, results, epoch,global_test_acc_dict):
8: 
9:     global_test_acc = []
10:     global_test_error = []
11:     global_test_f1 = []
12:     for k, result in enumerate(results):
13:         global_test_acc.append(results[k]['accuracy'])
14:         global_test_error.append(results[k]['error_rate'])
15:         global_test_f1.append(results[k]['macro_f1'])
16: 
17:         if k in global_test_acc_dict:
18:             global_test_acc_dict[k].append(results[k]['accuracy'])
19:         else:
20:             global_test_acc_dict[k] = [results[k]['accuracy']]
21: 
22:         print(k, "--Local test acc:", results[k]['accuracy'])
23: 
24:     print("--Global test acc:", sum(global_test_acc) / len(global_test_acc))
25: 
26:     print(f"Epoch:{epoch}")
27:     return global_test_acc,global_test_acc_dict
28: 
29: def average_weights(w, idxs_users, datanumber_client, islist=False):
30:     """
31:     Returns the average of the weights.
32:     """
33:     total_data_points = sum([datanumber_client[r] for r in idxs_users])
34: 
35:     w_avg = copy.deepcopy(w[idxs_users[0]])
36:     for idx in range(len(idxs_users)):
37:         fed_avg_freqs = datanumber_client[idxs_users[idx]] / total_data_points
38: 
39:         if islist:
40:             if idx == 0:
41:                 w_avg = w_avg * fed_avg_freqs
42:             else:
43:                 w_avg += w[idxs_users[idx]] * fed_avg_freqs
44:         else:
45:             if idx == 0:
46:                 for key in w_avg:
47:                     w_avg[key] = w_avg[key] * fed_avg_freqs
48:             else:
49:                 for key in w_avg:
50:                     w_avg[key] += w[idxs_users[idx]][key] * fed_avg_freqs
51: 
52:     return w_avg
53: 
54: def moment_aggre_weights(w_prompt,w_key, global_key, global_group_prompt,cluster_size ,idxs_users, datanumber_client, moment = 0.5):
55:     
56:     total_data_points = sum([datanumber_client[r] for r in idxs_users])
57:     total_cluster_size = sum([cluster_size[r] for r in idxs_users])
58: 