Source records 81 mismatches 0
{'repository_url': 'https://github.com/abhmul/general-misfit-gain', 'commit': 'd14451439ef4ffdee2c2ced23af6fa2bb4fcf7c9', 'status': 'acquired'}
ARCHIVE sources\0257\r01\a.zip SHA256 7bdf5c41a4f7747b837c7bd5570854042be4f0ecab78f253fc0812c51308d5cb
MEMBER general-misfit-gain-d14451439ef4ffdee2c2ced23af6fa2bb4fcf7c9/README.md SHA256 98673c4ec7e2be980c566e9c63ea49e849f8263d4d2f61412526c1771cf7ae9a
1: # general-misfit-gain
2: This project contains code for implementing our paper on [connecting misfit to generalization gain in weak-to-strong learning](https://arxiv.org/abs/2501.19105)
MEMBER general-misfit-gain-d14451439ef4ffdee2c2ced23af6fa2bb4fcf7c9/vision/README.md SHA256 cbba22d8e4db393acb18cafca2a4055d8dbb9dce3f2ce7270ffb5d52e2e18a37
1: # Pythagoras AGI New
NOTEBOOK general-misfit-gain-d14451439ef4ffdee2c2ced23af6fa2bb4fcf7c9/vision/notebooks/11-am-read_results_vision_icml.ipynb SHA256 5a84e0a3794c7d6b9597cd03f460bbe2d4441a6d4c9f9304394f5dcd2958462c
CELL_INDEX 5 SOURCE from collections import defaultdict

# Should be 2
print(f"Num Results: {len(filtered_results)}")

# Check that there is 1 of each type for model
model_count = defaultdict(int)
for result in filtered_results:
    model_count[result["settings"]["strong_model"]] += 1

print(model_count)
STORED_OUTPUT Num Results: 3
defaultdict(<class 'int'>, {'vitb8_dino': 3})

CELL_INDEX 6 SOURCE import numpy as np


def display_results_for_w_to_s(results_list):
    metrics = [
        "wk<-gt_cross_entropy__mean",
        "wk<-gt_accuracy__mean",
        "st<-gt_cross_entropy__mean",
        "st<-wk_kl_divergence__mean",
        "st<-gt_accuracy__mean",

        # "stgt<-gt_cross_entropy__mean",
        # "stgt<-gt_accuracy__mean",        
        # "stgt<-wk_kl_divergence__mean",
        # "stgt<-wk_accuracy__mean",
        # "stgt<-st_kl_divergence__mean",
        # "stgt<-st_accuracy__mean",

        "wk<-st_kl_divergence__mean",
        "wk<-st_cross_entropy__mean",
    ]
    # Weak model loss
    # Weak model acc
    # Strong model loss  
    # Strong model misfit  
    # Strong model test acc  
    # Discrepancy
    # Test r acc
    # Test r loss
    # Weak model loss r
    # Weak model acc r
    # Strong model loss r
    # Strong model test acc r
    # Discrepancy r

    metric_values = defaultdict(lambda: defaultdict(list))
    for res in results_list:
        for metric in metrics:
            metric_values[res["settings"]["strong_model"]][metric].append(res["results"][metric])
    
    # Take mean and std of each metric
    for _, metric_dict in metric_values.items():
        for metric, values in metric_dict.items():
            mean = np.mean(values)
            std = np.std(values)
            metric_dict[metric] = (mean, std)
    
    # Print the results in the desired form
    for strong_model, metric_dict in sorted(metric_values.items(), key=lambda x: x[0]):
        print(f"{strong_model}")
        print(f"Weak model loss\t{metric_dict['wk<-gt_cross_entropy__mean'][0]}\t{metric_dict['wk<-gt_cross_entropy__mean'][1]}")
        print(f"Weak model acc\t{metric_dict['wk<-gt_accuracy__mean'][0]}\t{metric_dict['wk<-gt_accuracy__mean'][1]}")
        print(f"Strong model loss\t{metric_dict['st<-gt_cross_entropy__mean'][0]}\t{metric_dict['st<-gt_cross_entropy__mean'][1]}")
        print(f"Forward-trained Reverse KL misfit\t{metric_dict['st<-wk_kl_divergence__mean'][0]}\t{metric_dict['st<-wk_kl_divergence__mean'][1]}")
        print(f"Strong model test acc\t{metric_dict['st<-gt_accuracy__mean'][0]}\t{metric_dict['st<-gt_accuracy__mean'][1]}")
        # discrepancy = metric_dict['wk<-gt_cross_entropy__mean'][0] - metric_dict['st<-wk_kl_divergence__mean'][0]- metric_dict['st<-gt_cross_entropy__mean'][0]
        # print(f"Discrepancy\t{discrepancy}\t")

        print(f"Forward KL Misfit\t{metric_dict['wk<-st_kl_divergence__mean'][0]}\t{metric_dict['wk<-st_kl_divergence__mean'][1]}")
        print(f"Forward KL Misfit XE\t{metric_dict['wk<-st_cross_entropy__mean'][0]}\t{metric_dict['wk<-st_cross_entropy__mean'][1]}")

display_results_for_w_to_s(filtered_results)
STORED_OUTPUT vitb8_dino
Weak model loss	0.5824153621991476	1.2247590229846988e-07
Weak model acc	0.796300212542216	7.434005313662571e-08
Strong model loss	0.40521153807640076	0.0021192049083189287
Forward-trained Reverse KL misfit	0.3681456645329793	0.0017983313355465205
Strong model test acc	0.8981336355209351	0.0011556690588221707
Forward KL Misfit	0.26816285649935406	0.00034359007508725554
Forward KL Misfit XE	1.1024143695831299	0.004544285036629746

CELL_INDEX 7 SOURCE # Tests for w-to-s
results = load_results()

filters = {
    "dataset": DatasetName.CIFAR10.value,
    "strong_model": ModelName.VITB8_DINO.value,
    "num_heads": "100",
    "exp_id": "w-to-s-new",
    "weight_decay_fixed": True,
}

filtered_results = filter_results(results, filters)
CELL_INDEX 8 SOURCE from collections import defaultdict

# Should be 2
print(f"Num Results: {len(filtered_results)}")

# Check that there is 1 of each type for model
model_count = defaultdict(int)
for result in filtered_results:
    model_count[result["settings"]["strong_model"]] += 1

print(model_count)
STORED_OUTPUT Num Results: 3
defaultdict(<class 'int'>, {'vitb8_dino': 3})

MEMBER general-misfit-gain-d14451439ef4ffdee2c2ced23af6fa2bb4fcf7c9/vision/src/measurements/estimate_losses.py SHA256 843a101a5cc7c67ed0520bbeaa0e7bce4285e08e067da723b2306a8082686391
1: from typing import Callable, Generic, Literal, Sequence, TypeVar
2: from dataclasses import dataclass
3: import itertools as it
4: 
5: import torch
6: 
7: from ..params import Dataset, DEFAULT_DEVICE
8: from ..datasets import DataBatch, LabeledDataBatch, StrongWeakDataBatch
9: from ..metrics import LossFunction, Stat, Accuracy, CrossEntropy, KLDivergence
10: from .monte_carlo import MonteCarloEstimation
11: from ..torch_utils import ModuleEnhanced
12: from ..py_utils import peek
13: 
14: 
15: @dataclass
16: class LossSpec:
17:     name1: str
18:     name2: str
19:     loss_fn: LossFunction
20: 
21: 
22: @dataclass
23: class StatSpec:
24:     name: str
25:     stat_fn: Stat
26: 
27: 
28: @dataclass
29: class ModuleSpec:
30:     name: str
31:     model: ModuleEnhanced
32: 
33: 
34: T = TypeVar("T", bound=DataBatch)
35: 
36: 
37: class EstimateModelLosses(MonteCarloEstimation, Generic[T]):
38: 
39:     def __init__(
40:         self,
41:         dataset: Dataset,
42:         data_batch_type: type[T],
43:         apply_model_dict: dict[str, Callable[[T], torch.Tensor | None]],
44:         losses: list[LossSpec] | None = None,
45:         stats: list[StatSpec] | None = None,
46:         device: torch.device = DEFAULT_DEVICE,
47:     ):
48:         if losses is None:
49:             losses = []
50:         if stats is None:
51:             stats = []
52: 
53:         # Check the names in the provided dictionaries
54:         model_names = set(apply_model_dict.keys())
55:         for loss_spec in losses:
56:             assert loss_spec.name1 in model_names
57:             assert loss_spec.name2 in model_names
58:         for stat_spec in stats:
59:             assert stat_spec.name in model_names
60: 
61:         self.dataset = dataset
62:         self.data_batch_type = data_batch_type
63:         self.apply_model_dict = apply_model_dict
64:         self.losses = losses
65:         self.stats = stats
66:         self._device = device
67: 
68:         print(f"Using device: {self._device} for estimating losses between models")
69: 
70:     @property
71:     def device(self) -> torch.device:
72:         return self._device
73: 
74:     @torch.no_grad()
75:     def estimate_batch(
76:         self,
77:         tensors: Sequence[torch.Tensor],
78:     ) -> dict[str, torch.Tensor]:
79:         data_batch = self.data_batch_type.read_data_batch(tensors, device=self.device)
80:         model_outputs = {
81:             name: model_func(data_batch)
82:             for name, model_func in self.apply_model_dict.items()
83:         }
84: 
85:         metrics_dict: dict[str, torch.Tensor] = {}
86:         for loss_spec in self.losses:
87:             outputs1 = model_outputs[loss_spec.name1]
88:             outputs2 = model_outputs[loss_spec.name2]
89:             if outputs1 is None or outputs2 is None:
90:                 continue
91: 
92:             loss = loss_spec.loss_fn(outputs1, outputs2)
93:             metrics_dict[
94:                 f"{loss_spec.name1}<-{loss_spec.name2}_{loss_spec.loss_fn.__name__}"
95:             ] = loss
96:         for stat_spec in self.stats:
97:             outputs = model_outputs[stat_spec.name]
98:             if outputs is None:
99:                 continue
100: 
101:             stat = stat_spec.stat_fn(outputs)
102:             metrics_dict[f"{stat_spec.name}_{stat_spec.stat_fn.__name__}"] = stat
103: 
104:         return metrics_dict
105: 
106: 
107: class EstimatedLabeledModelLosses(EstimateModelLosses[LabeledDataBatch]):
108:     GT = "gt"
109:     GT_LOGITS = "gt_logits"
110: 
111:     def __init__(
112:         self,
113:         dataset: Dataset,
114:         models: dict[str, ModuleEnhanced],
115:         losses: list[LossSpec] | None = None,
116:         stats: list[StatSpec] | None = None,
117:     ):
118:         assert len(models) > 0
119:         first_model = peek(models.values())
120:         device = peek(first_model.parameters()).device
121:         for model in models.values():
122:             assert device == peek(model.parameters()).device
123: 
124:         def create_model_func(
125:             model: ModuleEnhanced,
126:         ) -> Callable[[LabeledDataBatch], torch.Tensor]:
127:             return lambda data: model(data.x)
128: 
129:         super().__init__(
130:             dataset=dataset,
131:             data_batch_type=LabeledDataBatch,
132:             apply_model_dict={
133:                 **{name: create_model_func(model) for name, model in models.items()},
134:                 self.GT: lambda data: data.y,
135:                 self.GT_LOGITS: lambda data: data.y_logits,
136:             },
137:             losses=losses,
138:             stats=stats,
139:             device=device,
140:         )
141: 
142: 
143: class EstimateWeakToStrong(EstimateModelLosses[StrongWeakDataBatch]):
144:     GT = "gt"
145:     GT_LOGITS = "gt_logits"
146:     STRONG = "strong"
147:     WEAK = "weak"
148: 
149:     def __init__(
150:         self,
151:         dataset: Dataset,
152:         strong_models: dict[str, ModuleEnhanced],
153:         weak_models: dict[str, ModuleEnhanced],
154:         losses: list[LossSpec] | None = None,
155:         stats: list[StatSpec] | None = None,
156:     ):
157:         # Check no overlap between strong and weak model names
158:         assert len(strong_models) > 0
159:         assert len(weak_models) > 0
160:         assert not set(strong_models.keys()) & set(weak_models.keys())
161:         all_models = {**strong_models, **weak_models}
162:         first_model = peek(all_models.values())
163:         device = peek(first_model.parameters()).device
164:         for model in all_models.values():
165:             assert device == peek(model.parameters()).device
166: 
167:         def create_model_func(
168:             model: ModuleEnhanced,
169:             model_type: str,
170:         ) -> Callable[[StrongWeakDataBatch], torch.Tensor]:
171:             if model_type == self.STRONG:
172:                 return lambda data: model(data.strong_x)
173:             elif model_type == self.WEAK:
174:                 return lambda data: model(data.weak_x)
175:             else:
176:                 raise ValueError(f"Unknown model type: {model_type}")
177: 
178:         super().__init__(
179:             dataset=dataset,
180:             data_batch_type=StrongWeakDataBatch,
181:             apply_model_dict={
182:                 **{
183:                     name: create_model_func(model, model_type=self.STRONG)
184:                     for name, model in strong_models.items()
185:                 },
186:                 **{
187:                     name: create_model_func(model, model_type=self.WEAK)
188:                     for name, model in weak_models.items()
189:                 },
190:                 self.GT: lambda data: data.y,
191:                 self.GT_LOGITS: lambda data: data.y_logits,
192:             },
193:             losses=losses,
194:             stats=stats,
195:             device=device,
196:         )
197: 
198:     @staticmethod
199:     def generate_default_loss_specs(
200:         dual_stgt: ModuleSpec, dual_st: ModuleSpec, dual_wk: ModuleSpec
201:     ):
202:         losses_list = [
203:             # WRT the ground truth labels
204:             LossSpec(
205:                 name1=dual_stgt.name,
206:                 name2=EstimateWeakToStrong.GT,
207:                 loss_fn=CrossEntropy(output_logits=True, label_logits=False),
208:             ),
209:             LossSpec(
210:                 name1=dual_st.name,
211:                 name2=EstimateWeakToStrong.GT,
212:                 loss_fn=CrossEntropy(output_logits=True, label_logits=False),
213:             ),
214:             LossSpec(
215:                 name1=dual_wk.name,
216:                 name2=EstimateWeakToStrong.GT,
217:                 loss_fn=CrossEntropy(output_logits=True, label_logits=False),
218:             ),
219:             LossSpec(
220:                 name1=dual_stgt.name,
221:                 name2=EstimateWeakToStrong.GT,
222:                 loss_fn=Accuracy(output_logits=True, label_logits=False, hard=True),
223:             ),
224:             LossSpec(
225:                 name1=dual_st.name,
226:                 name2=EstimateWeakToStrong.GT,
227:                 loss_fn=Accuracy(output_logits=True, label_logits=False, hard=True),
228:             ),
229:             LossSpec(
230:                 name1=dual_wk.name,
231:                 name2=EstimateWeakToStrong.GT,
232:                 loss_fn=Accuracy(output_logits=True, label_logits=False, hard=True),
233:             ),
234:             # WRT the primal_gt model
235:             LossSpec(
236:                 name1=dual_stgt.name,
237:                 name2=dual_st.name,
238:                 loss_fn=KLDivergence(output_logits=True, label_logits=True),
239:             ),
240:             LossSpec(
241:                 name1=dual_stgt.name,
242:                 name2=dual_wk.name,
243:                 loss_fn=KLDivergence(output_logits=True, label_logits=True),
244:             ),
245:             LossSpec(
246:                 name1=dual_stgt.name,
247:                 name2=dual_st.name,
248:                 loss_fn=Accuracy(output_logits=True, label_logits=True, hard=True),
249:             ),
250:             LossSpec(
251:                 name1=dual_stgt.name,
252:                 name2=dual_wk.name,
253:                 loss_fn=Accuracy(output_logits=True, label_logits=True, hard=True),
254:             ),
255:             # WRT the primal_st model
256:             LossSpec(
257:                 name1=dual_st.name,
258:                 name2=dual_wk.name,
259:                 loss_fn=KLDivergence(output_logits=True, label_logits=True),
260:             ),
261:             LossSpec(
262:                 name1=dual_st.name,
263:                 name2=dual_wk.name,
264:                 loss_fn=Accuracy(output_logits=True, label_logits=True, hard=True),
265:             ),
266:             # WRT forward_kl
267:             LossSpec(
268:                 name1=dual_wk.name,
269:                 name2=dual_st.name,
270:                 loss_fn=KLDivergence(output_logits=True, label_logits=True),
271:             ),
272:             LossSpec(
273:                 name1=dual_wk.name,
274:                 name2=dual_st.name,
275:                 loss_fn=CrossEntropy(output_logits=True, label_logits=True),
276:             ),
277:         ]
278: 
279:         return losses_list
MEMBER general-misfit-gain-d14451439ef4ffdee2c2ced23af6fa2bb4fcf7c9/vision/src/metrics/losses.py SHA256 f64e757ea9634675631b23a5d2242a1e82ca4216a170d61ea57a2e27cd013513
1: from typing import Callable, cast, Generic, TypeVar
2: from abc import ABC, abstractmethod
3: 
4: import torch
5: import torch.nn.functional as F
6: 
7: from ..torch_utils import clamped_log, clamped_logit
8: 
9: 
10: # LossFunction = Callable[[torch.Tensor, torch.Tensor], torch.Tensor]
11: 
12: 
13: class LossFunction(ABC):
14:     @property
15:     @abstractmethod
16:     def __name__(self) -> str:
17:         pass
18: 
19:     @abstractmethod
20:     def __call__(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
21:         pass
22: 
23:     def reverse_loss(self) -> "ReversedLossFunction":
24:         return ReversedLossFunction(self)
25: 
26: 
27: T = TypeVar("T", bound=LossFunction)
28: 
29: 
30: class ReversedLossFunction(Generic[T], LossFunction):
31:     def __init__(self, loss_fn: T):
32:         self.loss_fn = loss_fn
33: 
34:     def __call__(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
35:         return self.loss_fn(labels, outputs)
36: 
37:     @property
38:     def __name__(self) -> str:
39:         return f"reversed_{self.loss_fn.__name__}"
40: 
41: 
42: class BinaryOrMultiLoss(LossFunction):
43:     def __init__(
44:         self, binary: LossFunction, multi: LossFunction, name: str | None = None
45:     ):
46:         self.binary = binary
47:         self.multi = multi
48:         self._name = f"{binary.__name__}_or_{multi.__name__}" if name is None else name
49: 
50:     def __call__(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
51:         assert outputs.shape == labels.shape
52:         assert outputs.ndim == labels.ndim == 2
53: 
54:         if labels.shape[1] == 1:
55:             return self.binary(outputs, labels)
56:         else:
57:             return self.multi(outputs, labels)
58: 
59:     @property
60:     def __name__(self) -> str:
61:         return self._name
62: 
63: 
64: class ClassificationLossFunction(LossFunction):
65: 
66:     def __init__(self, output_logits: bool = False, label_logits: bool = False):
67:         """
68:         Initializes the ClassificationLossFunction.
69: 
70:         :param output_logits: If True, indicates that the output tensor is in logits format (raw scores).
71:         :param label_logits: If True, indicates that the label tensor is in logits format (raw scores).
72:         """
73:         self._output_logits = output_logits
74:         self._label_logits = label_logits
75: 
76:     @property
77:     def output_logits(self) -> bool:
78:         """
79:         Returns whether the outputs are logits.
80:         This property should be implemented by subclasses to indicate
81:         if the output tensor is in logits format (raw scores) or probabilities.
82:         """
83:         return self._output_logits
84: 
85:     @property
86:     def label_logits(self) -> bool:
87:         """
88:         Returns whether the labels are in logits format.
89:         This property should be implemented by subclasses to indicate
90:         if the label tensor is in logits format (raw scores) or probabilities.
91:         """
92:         return self._label_logits
93: 
94:     def reverse_loss(self) -> "ReversedClassificationLossFunction":
95:         return ReversedClassificationLossFunction(self)
96: 
97: 
98: S = TypeVar("S", bound=ClassificationLossFunction)
99: 
100: 
101: class ReversedClassificationLossFunction(
102:     ReversedLossFunction[S], ClassificationLossFunction
103: ):
104:     def __init__(self, loss_fn: S):
105:         self.loss_fn = loss_fn
106: 
107:     @property
108:     def output_logits(self) -> bool:
109:         """
110:         Returns whether the outputs are logits.
111:         This property is inherited from the original loss function.
112:         """
113:         return self.loss_fn.label_logits
114: 
115:     @property
116:     def label_logits(self) -> bool:
117:         """
118:         Returns whether the labels are in logits format.
119:         This property is inherited from the original loss function.
120:         """
121:         return self.loss_fn.output_logits
122: 
123: 
124: class MultiCrossEntropy(ClassificationLossFunction):
125:     def __call__(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
126:         assert outputs.shape == labels.shape
127:         assert outputs.ndim == labels.ndim == 2
128: 
129:         if self.label_logits:
130:             labels = torch.softmax(labels, dim=1)
131: 
132:         if self.output_logits:
133:             return F.cross_entropy(outputs, labels, reduction="none")
134:         else:
135:             outputs = clamped_log(outputs)
136:             return F.cross_entropy(outputs, labels, reduction="none")
137: 
138:     @property
139:     def __name__(self) -> str:
140:         return "multi_cross_entropy"
141: 
142: 
143: class BinaryCrossEntropy(ClassificationLossFunction):
144:     def __call__(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
145:         assert outputs.shape == labels.shape
146:         assert outputs.ndim == labels.ndim == 2
147: 
148:         if self.label_logits:
149:             labels = torch.sigmoid(labels)
150: 
151:         if self.output_logits:
152:             return F.binary_cross_entropy_with_logits(
153:                 outputs, labels, reduction="none"
154:             ).squeeze(1)
155:         else:
156:             return F.binary_cross_entropy(outputs, labels, reduction="none").squeeze(1)
157: 
158:     @property
159:     def __name__(self) -> str:
160:         return "binary_cross_entropy"
161: 
162: 
163: class CrossEntropy(BinaryOrMultiLoss, ClassificationLossFunction):
164:     def __init__(self, output_logits: bool = False, label_logits: bool = False):
165:         BinaryOrMultiLoss.__init__(
166:             self,
167:             BinaryCrossEntropy(output_logits, label_logits),
168:             MultiCrossEntropy(output_logits, label_logits),
169:             name="cross_entropy",
170:         )
171:         ClassificationLossFunction.__init__(self, output_logits, label_logits)
172: 
173: 
174: class BregmanDivergence(LossFunction):
175:     def __init__(self, outputs_dual: bool = False, targets_dual: bool = False):
176:         self.outputs_dual = outputs_dual
177:         self.targets_dual = targets_dual
178: 
179:     @abstractmethod
180:     def primal_potential(self, primal_values: torch.Tensor) -> torch.Tensor:
181:         pass
182: 
183:     @abstractmethod
184:     def dual_potential(self, dual_values: torch.Tensor) -> torch.Tensor:
185:         pass
186: 
187:     @abstractmethod
188:     def primal_to_dual(self, primal_values: torch.Tensor) -> torch.Tensor:
189:         pass
190: 
191:     @abstractmethod
192:     def dual_to_primal(self, dual_values: torch.Tensor) -> torch.Tensor:
193:         pass
194: 
195:     def __call__(self, outputs: torch.Tensor, targets: torch.Tensor) -> torch.Tensor:
196:         assert outputs.shape == targets.shape
197:         assert outputs.ndim == targets.ndim == 2
198: 
199:         if self.outputs_dual:
200:             outputs = self.dual_to_primal(outputs)
201:         if not self.targets_dual:
202:             targets = self.primal_to_dual(targets)
203: 
204:         return (
205:             self.primal_potential(outputs)
206:             + self.dual_potential(targets)
207:             - torch.sum(outputs * targets, dim=1)
208:         )
209: 
210:     def dual_divergence(self) -> "BregmanDivergence":
211:         return DualDivergence(
212:             self, outputs_dual=not self.targets_dual, targets_dual=not self.outputs_dual
213:         )
214: 
215: 
216: class DualDivergence(BregmanDivergence):
217:     def __init__(
218:         self,
219:         primal_divergence: BregmanDivergence,
220:         outputs_dual=False,
221:         targets_dual=False,
222:     ):
223:         super().__init__(outputs_dual, targets_dual)
224:         self.primal_divergence = primal_divergence
225: 
226:     def primal_potential(self, primal_values: torch.Tensor) -> torch.Tensor:
227:         return self.primal_divergence.dual_potential(primal_values)
228: 
229:     def dual_potential(self, dual_values: torch.Tensor) -> torch.Tensor:
230:         return self.primal_divergence.primal_potential(dual_values)
231: 
232:     def primal_to_dual(self, primal_values: torch.Tensor) -> torch.Tensor:
233:         return self.primal_divergence.dual_to_primal(primal_values)
234: 
235:     def dual_to_primal(self, dual_values: torch.Tensor) -> torch.Tensor:
236:         return self.primal_divergence.primal_to_dual(dual_values)
237: 
238:     @property
239:     def __name__(self) -> str:
240:         return f"dual_{self.primal_divergence.__name__}"
241: 
242:     def dual_divergence(self) -> "BregmanDivergence":
243:         return self.primal_divergence
244: 
245: 
246: class BinaryOrMultiBregmanDivergence(BinaryOrMultiLoss, BregmanDivergence):
247:     def __init__(
248:         self,
249:         binary: BregmanDivergence,
250:         multi: BregmanDivergence,
251:         name: str | None = None,
252:     ):
253:         super().__init__(binary, multi, name=name)
254:         self.binary = cast(BregmanDivergence, self.binary)
255:         self.multi = cast(BregmanDivergence, self.multi)
256: 
257:     def primal_potential(self, probs: torch.Tensor) -> torch.Tensor:
258:         if probs.shape[1] == 1:
259:             return self.binary.primal_potential(probs)  # type: ignore[attr-defined]
260:         else:
261:             return self.multi.primal_potential(probs)  # type: ignore[attr-defined]
262: 
263:     def dual_potential(self, logits: torch.Tensor) -> torch.Tensor:
264:         if logits.shape[1] == 1:
265:             return self.binary.dual_potential(logits)  # type: ignore[attr-defined]
266:         else:
267:             return self.multi.dual_potential(logits)  # type: ignore[attr-defined]
268: 
269:     def primal_to_dual(self, probs: torch.Tensor) -> torch.Tensor:
270:         if probs.shape[1] == 1:
271:             return self.binary.primal_to_dual(probs)  # type: ignore[attr-defined]
272:         else:
273:             return self.multi.primal_to_dual(probs)  # type: ignore[attr-defined]
274: 
275:     def dual_to_primal(self, logits: torch.Tensor) -> torch.Tensor:
276:         if logits.shape[1] == 1:
277:             return self.binary.dual_to_primal(logits)  # type: ignore[attr-defined]
278:         else:
279:             return self.multi.dual_to_primal(logits)  # type: ignore[attr-defined]
280: 
281: 
282: class MultiKLDivergence(BregmanDivergence, ClassificationLossFunction):
283:     # Output = arg1 in KL Div, Label = arg2 in KL Div
284:     def __init__(self, output_logits: bool = False, label_logits: bool = False):
285:         BregmanDivergence.__init__(
286:             self, outputs_dual=output_logits, targets_dual=label_logits
287:         )
288:         ClassificationLossFunction.__init__(self, output_logits, label_logits)
289: 
290:     def primal_potential(self, probs: torch.Tensor) -> torch.Tensor:
291:         return torch.sum(probs * clamped_log(probs), dim=1)
292: 
293:     def dual_potential(self, logits: torch.Tensor) -> torch.Tensor:
294:         return torch.logsumexp(logits, dim=1)
295: 
296:     def primal_to_dual(self, probs: torch.Tensor) -> torch.Tensor:
297:         return clamped_log(probs)
298: 
299:     def dual_to_primal(self, logits: torch.Tensor) -> torch.Tensor:
300:         return torch.softmax(logits, dim=1)
301: 
302:     @property
303:     def __name__(self) -> str:
304:         return "multi_kl_divergence"
305: 
306: 
307: class BinaryKLDivergence(BregmanDivergence, ClassificationLossFunction):
308:     # Output = arg1 in KL Div, Label = arg2 in KL Div
309:     def __init__(self, output_logits: bool = False, label_logits: bool = False):
310:         BregmanDivergence.__init__(
311:             self, outputs_dual=output_logits, targets_dual=label_logits
312:         )
313:         ClassificationLossFunction.__init__(self, output_logits, label_logits)
314: 
315:     def primal_potential(self, probs: torch.Tensor) -> torch.Tensor:
316:         return (
317:             probs * clamped_log(probs) + (1 - probs) * clamped_log(1 - probs)
318:         ).squeeze(1)
319: 
320:     def dual_potential(self, logits: torch.Tensor) -> torch.Tensor:
321:         return torch.log(1 + torch.exp(logits)).squeeze(1)
322: 
323:     def primal_to_dual(self, probs: torch.Tensor) -> torch.Tensor:
324:         return clamped_logit(probs)
325: 
326:     def dual_to_primal(self, logits: torch.Tensor) -> torch.Tensor:
327:         return torch.sigmoid(logits)
328: 
329:     @property
330:     def __name__(self) -> str:
331:         return "binary_kl_divergence"
332: 
333: 
334: class KLDivergence(BinaryOrMultiBregmanDivergence, ClassificationLossFunction):
335:     def __init__(self, output_logits: bool = False, label_logits: bool = False):
336:         BinaryOrMultiBregmanDivergence.__init__(
337:             self,
338:             BinaryKLDivergence(output_logits, label_logits),
339:             MultiKLDivergence(output_logits, label_logits),
340:             name="kl_divergence",
341:         )
342:         ClassificationLossFunction.__init__(self, output_logits, label_logits)
343: 
344: 
345: class MultiAccuracy(ClassificationLossFunction):
346:     def __init__(
347:         self,
348:         output_logits: bool = False,
349:         label_logits: bool = False,
350:         hard: bool = False,
351:     ):
352:         super().__init__(output_logits, label_logits)
353:         self.hard = hard
354: 
355:     def __call__(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
356:         assert outputs.shape == labels.shape
357:         assert outputs.ndim == labels.ndim == 2
358: 
359:         if self.hard:
360:             labels = F.one_hot(labels.argmax(dim=1), num_classes=labels.shape[1]).to(
361:                 outputs.dtype
362:             )
363:         else:
364:             if self.label_logits:
365:                 labels = torch.softmax(labels, dim=1)
366: 
367:         # Don't need to do anything if outputs are logits.
368:         preds = F.one_hot(outputs.argmax(dim=1), num_classes=outputs.shape[1]).to(
369:             outputs.dtype
370:         )
371: 
372:         return torch.sum(preds * labels, dim=1)
373: 
374:     @property
375:     def __name__(self) -> str:
376:         return "multi_accuracy"
377: 
378: 
379: class BinaryAccuracy(ClassificationLossFunction):
380:     def __init__(
381:         self,
382:         output_logits: bool = False,
383:         label_logits: bool = False,
384:         hard: bool = False,
385:     ):
386:         super().__init__(output_logits, label_logits)
387:         self.hard = hard
388: 
389:     def __call__(self, outputs: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
390:         assert outputs.shape == labels.shape
391:         assert outputs.shape[1] == 1
392:         assert outputs.ndim == labels.ndim == 2
393: 
394:         if self.label_logits:
395:             if self.hard:
396:                 labels = (labels >= 0).to(outputs.dtype)
397:             else:
398:                 labels = torch.sigmoid(labels)
399:         else:
400:             if self.hard:
401:                 labels = (labels >= 0.5).to(outputs.dtype)
402: 
403:         if self.output_logits:
404:             preds = (outputs >= 0).to(outputs.dtype)
405:         else:
406:             preds = (torch.sigmoid(outputs) >= 0.5).to(outputs.dtype)
407: 
408:         return (preds * labels + (1 - preds) * (1 - labels)).squeeze(1)
409: 
410:     @property
411:     def __name__(self) -> str:
412:         return "binary_accuracy"
413: 
414: 
415: class Accuracy(BinaryOrMultiLoss, ClassificationLossFunction):
416:     def __init__(
417:         self,
418:         output_logits: bool = False,
419:         label_logits: bool = False,
420:         hard: bool = False,
421:     ):
422:         BinaryOrMultiLoss.__init__(
423:             self,
424:             BinaryAccuracy(output_logits, label_logits, hard=hard),
425:             MultiAccuracy(output_logits, label_logits, hard=hard),
426:             name="accuracy",
427:         )
428:         ClassificationLossFunction.__init__(self, output_logits, label_logits)
429:         self.hard = hard
MEMBER general-misfit-gain-d14451439ef4ffdee2c2ced23af6fa2bb4fcf7c9/vision/src/models/mlp.py SHA256 8c6b85f18275167fa0f054a5a11963cfa862a4a535224c1223e44521200d3501
1: from typing import Optional
2: 
3: import torch
4: import torch.nn as nn
5: 
6: from ..torch_utils import sigmoid_or_softmax, logit_or_log, ModuleEnhanced
7: 
8: 
9: class PrimalConvexCombination(ModuleEnhanced):
10:     def __init__(self, num_heads: int):
11:         super(PrimalConvexCombination, self).__init__()
12:         assert num_heads > 1
13: 
14:         self.num_heads = num_heads
15:         self.combine = nn.Parameter(torch.zeros(self.num_heads))
16: 
17:     def forward(self, x):
18:         # Expects primal inputs of shape (batch_size, output_dim, num_heads)
19:         assert x.dim() == 3
20:         assert x.shape[2] == self.num_heads
21: 
22:         coefficients = torch.softmax(self.combine, dim=0)
23:         x = torch.einsum("bij,j->bi", x, coefficients)
24:         return x
25: 
26: 
27: class LogisticRegression(ModuleEnhanced):
28:     def __init__(
29:         self, input_dim: int, output_dim: int, num_heads: int = 1, logit_outputs=True
30:     ):
31:         super(LogisticRegression, self).__init__()
32:         self.num_heads = num_heads
33:         self.output_dim = output_dim
34:         self.logit_outputs = logit_outputs
35:         self.finetune = nn.Linear(input_dim, output_dim * self.num_heads)
36:         if self.num_heads > 1:
37:             self.combine: PrimalConvexCombination | None = PrimalConvexCombination(
38:                 num_heads=self.num_heads
39:             )
40:         else:
41:             self.combine = None
42: 
43:     def forward(self, x):
44:         x = self.finetune(x)
45:         if self.num_heads > 1:
46:             assert self.combine is not None
47:             x = x.view(-1, self.output_dim, self.num_heads)
48:             # Convert to primal for convex combination
49:             x = sigmoid_or_softmax(x, dim=1)
50:             x = self.combine(x)
51:             if self.logit_outputs:
52:                 x = logit_or_log(x, dim=1)
53:             return x
54:         else:
55:             if not self.logit_outputs:
56:                 x = sigmoid_or_softmax(x, dim=1)
57:             return x
58: 
59:     def weight_decay_params(self):
60:         return {
61:             "decay_params": [self.finetune.weight],
62:             "other_params": [self.finetune.bias]
63:             + (list(self.combine.parameters()) if self.combine is not None else []),
64:         }
65: 
66: 
67: class SelectOutputs(ModuleEnhanced):
68:     def __init__(self, model: nn.Module, indices: torch.Tensor):
69:         super(SelectOutputs, self).__init__()
70:         self.model = model
71:         self.indices = indices
72: 
73:     def forward(self, x):
74:         x = self.model(x)
75:         assert x.dim() == 2
76:         x = x[:, self.indices]
77:         return x
78: 
79: 
80: class MLP(ModuleEnhanced):
81:     def __init__(
82:         self,
83:         input_dim: int,
84:         hidden_dim: int,
85:         output_dim: int,
86:         num_layers: int,
87:         representation_state_dict: Optional[dict[str, torch.Tensor]] = None,
88:         finetune_scale=1.0,
89:         activation=nn.ReLU(),
90:     ):
91:         super(MLP, self).__init__()
92:         assert num_layers > 0
93: 
94:         layers = []
95:         self.activation = activation
96: 
97:         for layer in range(num_layers):
98:             if layer == 0:
99:                 layers.append(
100:                     nn.Sequential(nn.Linear(input_dim, hidden_dim), activation)
101:                 )
102:             else:
103:                 layers.append(
104:                     nn.Sequential(nn.Linear(hidden_dim, hidden_dim), activation)
105:                 )
106: 
107:         self.representation = ModuleEnhanced.enhance(nn.Sequential(*layers))
108:         if representation_state_dict is not None:
109:             self.representation.load_state_dict(representation_state_dict)
110: 
111:         self.finetune = ModuleEnhanced.enhance(nn.Linear(hidden_dim, output_dim))
112:         self.finetune_scale = finetune_scale
113: 
114:     def forward(self, x: torch.Tensor):
115:         out = self.representation(x)
116:         out = self.finetune_scale * self.finetune(out)
117:         return out
118: 
119: 
120: class TruncatedMLP(MLP):
121:     def __init__(
122:         self,
123:         input_dim: int,
124:         hidden_dim: int,
125:         output_dim: int,
126:         num_layers: int,
127:         representation_state_dict: Optional[dict[str, torch.Tensor]] = None,
128:         finetune_scale=1.0,
129:         activation=nn.ReLU(),
130:         truncation_factor=0.5,
131:     ):
132:         orig_input_dim = input_dim
133:         input_dim = int(input_dim * truncation_factor)
134:         truncation_factor = input_dim / orig_input_dim
135:         super(TruncatedMLP, self).__init__(
136:             input_dim,
137:             hidden_dim,
138:             output_dim,
139:             num_layers,
140:             representation_state_dict,
141:             finetune_scale,
142:             activation,
143:         )
144:         self.truncation_factor = truncation_factor
145: 
146:     def forward(self, x: torch.Tensor):
147:         x = x[:, : int(x.shape[1] * self.truncation_factor)]
148:         out = self.representation(x)
149:         out = self.finetune_scale * self.finetune(out)
150:         return out
