-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapplyCLIPSurgery.m
More file actions
164 lines (130 loc) · 7.85 KB
/
Copy pathapplyCLIPSurgery.m
File metadata and controls
164 lines (130 loc) · 7.85 KB
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
% Copyright 2026 The MathWorks, Inc.
function imageEncoder = applyCLIPSurgery(clipImageEncoder)
arguments
clipImageEncoder (1, 1) dlnetwork
end
imageEncoder = clipImageEncoder; % Do not modify in place.
imageEncoder = addDualPath(imageEncoder);
imageEncoder = initialize(imageEncoder);
end
function imageEncoder = addDualPath(imageEncoder)
% Adds the dual path, reusing parameters from existing selfAttention layers.
% This involves two steps:
% 1. Replace the existing selfAttentionLayers with attentionLayers.
% This requires a separate fullyConnectedLayer for each of Q, K, V,
% and Output projection.
% 2. Add the dual path, reusing the output from the attentionLayers in
% step 1.
replaceDepth = 6; % The number of transformer blocks from the end to modify.
numBlocks = 24; % The number of transformer blocks in the model.
blockIdxs = numBlocks-replaceDepth+1:numBlocks;
% The attention layers are 0-indexed, everything else is 1-indexed.
layerNames = "transformer:TopLevelModule:CLIPModel_visual:transformer:resblocks:" ...
+ string(blockIdxs - 1) + ":attn:SelfAttention";
for idx = 1:numel(layerNames)
blockNum = blockIdxs(idx);
disp("Modifying transformer " + blockNum)
% ---------------------------- Step 1 ----------------------------
% Get the name/layer of the selfAttention layer in the normal path,
% and its input/output layers.
layerName = layerNames(idx);
layer = getLayer(imageEncoder, layerName);
imageEncoder = removeLayers(imageEncoder, layerName);
inputName = "transformer:resblock" + num2str(blockNum) + "_ln1";
outputName = "transformer:resblock" + num2str(blockNum) + "_add1";
% Replace the selfAttention layer with an attentionLayer, so the
% Value paramaters are reusable.
newLayerName = "ClipAttention"+blockNum;
newAttnLayer = attentionLayer(layer.NumHeads, Name=newLayerName);
imageEncoder = addLayers(imageEncoder, newAttnLayer);
% Set up the QKV inputs as fully connected layers, and copy their
% parameters. Connect their input and output.
newQueryLayer = copyFCLayer(layer, newLayerName+"query", FromAttention="Query");
imageEncoder = addLayers(imageEncoder, newQueryLayer);
imageEncoder = connectLayers(imageEncoder, inputName, newQueryLayer.Name);
imageEncoder = connectLayers(imageEncoder, newQueryLayer.Name, newAttnLayer.Name + "/query");
newKeyLayer = copyFCLayer(layer, newLayerName+"key", FromAttention="Key");
imageEncoder = addLayers(imageEncoder, newKeyLayer);
imageEncoder = connectLayers(imageEncoder, inputName, newKeyLayer.Name);
imageEncoder = connectLayers(imageEncoder, newKeyLayer.Name, newAttnLayer.Name + "/key");
newValueLayer = copyFCLayer(layer, newLayerName+"value", FromAttention="Value");
imageEncoder = addLayers(imageEncoder, newValueLayer);
imageEncoder = connectLayers(imageEncoder, inputName, newValueLayer.Name);
imageEncoder = connectLayers(imageEncoder, newValueLayer.Name, newAttnLayer.Name + "/value");
% Create and connect a fully connected layer for the output
% projection of the attentionLayer.
newOutputLayer = copyFCLayer(layer, newLayerName+"output", OutputLearnables=true, FromAttention="Output");
imageEncoder = addLayers(imageEncoder, newOutputLayer);
imageEncoder = connectLayers(imageEncoder, newAttnLayer.Name, newOutputLayer.Name);
imageEncoder = connectLayers(imageEncoder, newOutputLayer.Name+"/out", outputName+"/in2");
% ---------------------------- Step 2 ----------------------------
% Construct a VVV attention layer from the normal path layer.
vvvAttn = attentionLayer(layer.NumHeads, Name="vvv_attn"+blockNum);
imageEncoder = addLayers(imageEncoder, vvvAttn);
% VVV attention.
imageEncoder = connectLayers(imageEncoder, newValueLayer.Name, vvvAttn.Name+"/query");
imageEncoder = connectLayers(imageEncoder, newValueLayer.Name, vvvAttn.Name+"/value");
imageEncoder = connectLayers(imageEncoder, newValueLayer.Name, vvvAttn.Name+"/key");
vvvOutput = fullyConnectedLayer(newOutputLayer.OutputSize, InputLearnables=["bias","weights"], ...
Name="vvvOutput" + blockNum);
imageEncoder = addLayers(imageEncoder, vvvOutput);
% Share output projection weights of QKV attention branch with VVV
% attention branch.
imageEncoder = connectLayers(imageEncoder, newOutputLayer.Name + "/weights", vvvOutput.Name + "/weights");
imageEncoder = connectLayers(imageEncoder, newOutputLayer.Name + "/bias", vvvOutput.Name + "/bias");
imageEncoder = connectLayers(imageEncoder, vvvAttn.Name, vvvOutput.Name + "/in");
% Create an additionLayer for the output of the VVV attention layer.
outputToVVVLayerName = "transformer:resblock" + blockNum + "_dualpath_add3";
outputLayer = additionLayer(2, Name=outputToVVVLayerName);
imageEncoder = addLayers(imageEncoder, outputLayer);
if idx == 1
firstAddLayer = "transformer:resblock" + string(blockNum - 1) + "_add2";
else
previousName = "transformer:resblock" + string(blockNum - 1) + "_dualpath_add3";
firstAddLayer = getLayer(imageEncoder, previousName).Name;
end
% Connect the VVV attention layer and previous output to the additionLayer.
add1Name = outputLayer.Name + "/in1";
imageEncoder = connectLayers(imageEncoder, firstAddLayer, add1Name);
add2Name = outputLayer.Name + "/in2";
imageEncoder = connectLayers(imageEncoder, vvvOutput.Name, add2Name);
end
% Add layer from the dual path to the outputs of the image encoder.
outputIdx = 24;
outputName = "transformer:resblock" + outputIdx + "_dualpath_add3";
% Set the CLS token embedding to come from the original path, and
% remove the slice layer in the original path.
imageEncoder = postProcessOutput(imageEncoder, outputName);
end
function imageEncoder = postProcessOutput(imageEncoder, outputName)
layerNormLayer = getLayer(imageEncoder, "lnPost");
origPathOutput = getLayer(imageEncoder, "transformer:resblock24_add2");
replaceCLSEmbedLayer = ReplaceClsEmbeddingLayer(Name="ReplaceClsEmbeddingLayer");
imageEncoder = addLayers(imageEncoder, replaceCLSEmbedLayer);
imageEncoder = connectLayers(imageEncoder, outputName, replaceCLSEmbedLayer.Name + "/dest");
imageEncoder = connectLayers(imageEncoder, origPathOutput.Name, replaceCLSEmbedLayer.Name + "/source");
imageEncoder = removeLayers(imageEncoder, "slice");
imageEncoder = connectLayers(imageEncoder, replaceCLSEmbedLayer.Name, layerNormLayer.Name);
end
function newLayer = copyFCLayer(oldLayer, newLayerName, params)
arguments
oldLayer
newLayerName (1, 1) string
params.OutputLearnables (1, 1) logical = false
params.FromAttention (1, 1) string {mustBeMember(params.FromAttention, ["", "Query", "Key", "Value", "Output"])} = ""
end
if params.OutputLearnables
newLayer = fullyConnectedLayer(oldLayer.OutputSize, Name=newLayerName, ...
OutputLearnables=["weights", "bias"]);
else
newLayer = fullyConnectedLayer(oldLayer.OutputSize, Name=newLayerName);
end
newLayer.Weights = oldLayer.(params.FromAttention + "Weights");
newLayer.Bias = oldLayer.(params.FromAttention + "Bias");
newLayer.WeightsInitializer = oldLayer.WeightsInitializer;
newLayer.WeightLearnRateFactor = oldLayer.WeightLearnRateFactor;
newLayer.WeightL2Factor = oldLayer.WeightL2Factor;
newLayer.BiasInitializer = oldLayer.BiasInitializer;
newLayer.BiasLearnRateFactor = oldLayer.BiasLearnRateFactor;
newLayer.BiasL2Factor = oldLayer.BiasL2Factor;
end