Uh oh!
There was an error while loading. Please reload this page.
forked from shihuihong214/P2-ViT
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot.py
More file actions
Latest commit
217 lines (168 loc) · 6.83 KB
/
Copy pathplot.py
File metadata and controls
217 lines (168 loc) · 6.83 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
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
# 필요한 라이브러리 임포트
frommathimportsqrt, ceil
importmatplotlib.pyplotasplt
# import seaborn as sns
importnumpyasnp
importtorch
importos
defplot_ckalist_resume(cka_list, save_name):
# CKA 리스트의 길이 계산
n=len(cka_list)
# 서브플롯 행과 열 수 계산
y=ceil(sqrt(n))
ifn==sqrt(n)*sqrt(n):
x=y
elif (y-1) *y<n:
x=y
else:
x=y-1
print("x | y :", x, y)
# 전체 그림 생성
fig=plt.figure(figsize=(y*4, x*4), frameon=False)
sc=None
fori, ckainenumerate(cka_list):
# 서브플롯 추가
ax=fig.add_subplot(x, y, i+1)
ll=cka.shape[0]
# CKA 행렬 이미지로 표시
sc=ax.imshow(cka, cmap='magma', vmin=0.0, vmax=1.0)
# x축 틱 설정
step=max(1, int(ll/5))
tick= [iforiinrange(0, ll, step)]
ax.set_xticks(tick)
# y축 틱 제거
ax.set_yticks([])
# y축 반전
ax.axes.invert_yaxis()
# 컬러바 위치 및 크기 설정
l, b, w, h=0.92, 0.35, 0.015, 0.35
rect= [l, b, w, h]
cbar_ax=fig.add_axes(rect)
# 컬러바 추가
plt.colorbar(sc, cax=cbar_ax)
# 그림 저장
plt.savefig(f'{save_name}.png', dpi=700)
# 주의: 이 함수는 PyTorch 텐서를 직접 다루지 않습니다.
# CKA 계산 결과가 NumPy 배열 형태로 제공된다고 가정합니다.
# 만약 PyTorch 텐서를 직접 다룰 경우, 아래와 같이 수정이 필요할 수 있습니다:
# cka = cka.cpu().numpy() if isinstance(cka, torch.Tensor) else cka
# 필요한 라이브러리 임포트
importtorch
importargparse
importos
importpickle
importnumpyasnp
fromplotimport*
defplot_cka_map(cka_file_name, plot_name, base_dir):
# GPU 설정
#base_dir + cka_file_name폴더가 없으면 폴더를 만든다.
ifnotos.path.exists(os.path.join(base_dir, cka_file_name)):
os.makedirs(os.path.join(base_dir, cka_file_name))
# CKA 결과 파일 경로 설정
cka_dir=os.path.join(base_dir, cka_file_name, cka_file_name+"_heatmap.pkl")
# CKA 결과 불러오기
withopen(cka_dir, 'rb') asf:
cka=pickle.load(f)
qkv_activations= [(i*4) +1foriinrange(0, 12)]
proj_activations= [(i*4) +2foriinrange(0, 12)]
mlp_fc1_activations= [(i*4) +3foriinrange(0, 12)]
mlp_fc2_activations= [(i*4) +4foriinrange(0, 12)]
# 전체 레이어에 대한 CKA 결과 플롯 생성
plot_dir=os.path.join(base_dir, plot_name)
qkv_plot_dir=os.path.join(plot_dir, 'cka_qkv')
proj_plot_dir=os.path.join(plot_dir, 'cka_proj')
mlp_fc1_plot_dir=os.path.join(plot_dir, 'cka_mlp_fc1')
mlp_fc2_plot_dir=os.path.join(plot_dir, 'cka_mlp_fc2')
#qkv
qkv_cka1=cka[qkv_activations]
qkv_cka1=qkv_cka1[:,qkv_activations]
print(cka.shape, qkv_cka1.shape)
#pickle로 저장한다.
withopen(os.path.join(plot_dir, 'cka_qkv.pkl'), 'wb') asf:
pickle.dump(qkv_cka1, f)
#proj
proj_cka1=cka[proj_activations]
proj_cka1=proj_cka1[:,proj_activations]
print(cka.shape, proj_cka1.shape)
withopen(os.path.join(plot_dir, 'cka_proj.pkl'), 'wb') asf:
pickle.dump(proj_cka1, f)
#mlp_fc1
mlp_fc1_cka1=cka[mlp_fc1_activations]
mlp_fc1_cka1=mlp_fc1_cka1[:,mlp_fc1_activations]
print(cka.shape, mlp_fc1_cka1.shape)
withopen(os.path.join(plot_dir, 'cka_mlp_fc1.pkl'), 'wb') asf:
pickle.dump(mlp_fc1_cka1, f)
#mlp_fc2
mlp_fc2_cka1=cka[mlp_fc2_activations]
mlp_fc2_cka1=mlp_fc2_cka1[:,mlp_fc2_activations]
print(cka.shape, mlp_fc2_cka1.shape)
withopen(os.path.join(plot_dir, 'cka_mlp_fc2.pkl'), 'wb') asf:
pickle.dump(mlp_fc2_cka1, f)
plot_ckalist_resume([cka], plot_dir)
plot_ckalist_resume([qkv_cka1], qkv_plot_dir)
plot_ckalist_resume([proj_cka1], proj_plot_dir)
plot_ckalist_resume([mlp_fc1_cka1], mlp_fc1_plot_dir)
plot_ckalist_resume([mlp_fc2_cka1], mlp_fc2_plot_dir)
# plot_cka_map('cka_not_quantized_result.pkl', 'cka_not_quantized_result.png')
importpickle
importmatplotlib.pyplotasplt
importnumpyasnp
defload_and_plot_diagonal(pickle_file):
# pickle 파일 불러오기
withopen(f'{pickle_file}.pkl', 'rb') asf:
heatmap=pickle.load(f)
# 대각 성분 추출
diagonal=np.diag(heatmap)
# 그래프 그리기
plt.figure(figsize=(10, 6))
plt.plot(diagonal, marker='o')
plt.title('Diagonal Elements of CKA Matrix')
plt.xlabel('Layer Index')
plt.ylabel('CKA Value')
plt.ylim(0, 1) # CKA 값의 범위는 0에서 1 사이입니다
plt.grid(True)
# 그래프 저장
plt.savefig(f'{pickle_file}_diagonal.png', dpi=300, bbox_inches='tight')
plt.close()
returndiagonal
importpickle
importmatplotlib.pyplotasplt
importnumpyasnp
defload_diagonal(pickle_file):
withopen(f'{pickle_file}.pkl', 'rb') asf:
heatmap=pickle.load(f)
returnnp.diag(heatmap)
defplot_all_diagonals(pickle_files, labels):
plt.figure(figsize=(15, 8))
qkv_activations= [i*4+1foriinrange(12)]
proj_activations= [i*4+2foriinrange(12)]
mlp_fc1_activations= [i*4+3foriinrange(12)]
mlp_fc2_activations= [i*4+4foriinrange(12)]
all_activations=qkv_activations+proj_activations+mlp_fc1_activations+mlp_fc2_activations
max_activation=max(all_activations)
forpickle_file, labelinzip(pickle_files, labels):
diagonal=load_diagonal(pickle_file)
iflabel=='Comprehensive':
plt.plot(range(len(diagonal)), diagonal, marker='o', label=label)
eliflabel=='QKV':
values= [diagonal[i] ifi<len(diagonal) elseNoneforiinrange(12)]
plt.plot(qkv_activations, values, marker='o', label=label)
eliflabel=='Proj':
values= [diagonal[i] ifi<len(diagonal) elseNoneforiinrange(12)]
plt.plot(proj_activations, values, marker='o', label=label)
eliflabel=='MLP FC1':
values= [diagonal[i] ifi<len(diagonal) elseNoneforiinrange(12)]
plt.plot(mlp_fc1_activations, values, marker='o', label=label)
eliflabel=='MLP FC2':
values= [diagonal[i] ifi<len(diagonal) elseNoneforiinrange(12)]
plt.plot(mlp_fc2_activations, values, marker='o', label=label)
plt.title('Diagonal Elements of CKA Matrices')
plt.xlabel('Layer Index')
plt.ylabel('CKA Value')
plt.ylim(0, 1)
plt.xlim(0, max_activation+1)
plt.xticks(range(0, max_activation+1, 4))
plt.grid(True)
plt.legend()
plt.savefig('all_diagonals_matched.png', dpi=300, bbox_inches='tight')
plt.show()