yefllower commited on
Commit
196bee3
·
1 Parent(s): 784d417

EEGFaceSem: processed data, code, models

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. EEGFaceSem/EEGModels.py +402 -0
  2. EEGFaceSem/EEGPT/__init__.py +1 -0
  3. EEGFaceSem/EEGPT/eegpt_linear.py +207 -0
  4. EEGFaceSem/EEGPT/modules/EEGPT_mcae.py +876 -0
  5. EEGFaceSem/EEGPT/modules/Network/__init__.py +0 -0
  6. EEGFaceSem/EEGPT/modules/Network/utils.py +118 -0
  7. EEGFaceSem/EEGPT/modules/__init__.py +0 -0
  8. EEGFaceSem/__init__.py +144 -0
  9. EEGFaceSem/benchmark.py +300 -0
  10. EEGFaceSem/download.py +205 -0
  11. EEGFaceSem/generation.py +112 -0
  12. EEGFaceSem/models.py +414 -0
  13. EEGFaceSem/pgan/__init__.py +0 -0
  14. EEGFaceSem/pgan/config.py +140 -0
  15. EEGFaceSem/pgan/dataset.py +241 -0
  16. EEGFaceSem/pgan/dataset_tool.py +740 -0
  17. EEGFaceSem/pgan/legacy.py +117 -0
  18. EEGFaceSem/pgan/loss.py +82 -0
  19. EEGFaceSem/pgan/misc.py +344 -0
  20. EEGFaceSem/pgan/networks.py +316 -0
  21. EEGFaceSem/pgan/tfutil.py +770 -0
  22. EEGFaceSem/pgan/util_scripts.py +239 -0
  23. EEGFaceSem/preprocess.py +93 -0
  24. EEGFaceSem/utils.py +245 -0
  25. README.md +110 -3
  26. README_code.md +99 -0
  27. data/latents/latent.pkl +3 -0
  28. data/processed/01-epo.fif +3 -0
  29. data/processed/01-ev2img.pkl +3 -0
  30. data/processed/02-epo.fif +3 -0
  31. data/processed/02-ev2img.pkl +3 -0
  32. data/processed/03-epo.fif +3 -0
  33. data/processed/03-ev2img.pkl +3 -0
  34. data/processed/04-epo.fif +3 -0
  35. data/processed/04-ev2img.pkl +3 -0
  36. data/processed/05-epo.fif +3 -0
  37. data/processed/05-ev2img.pkl +3 -0
  38. data/processed/06-epo.fif +3 -0
  39. data/processed/06-ev2img.pkl +3 -0
  40. data/processed/07-epo.fif +3 -0
  41. data/processed/07-ev2img.pkl +3 -0
  42. data/processed/08-epo.fif +3 -0
  43. data/processed/08-ev2img.pkl +3 -0
  44. data/processed/09-epo.fif +3 -0
  45. data/processed/09-ev2img.pkl +3 -0
  46. data/processed/10-epo.fif +3 -0
  47. data/processed/10-ev2img.pkl +3 -0
  48. data/processed/11-epo.fif +3 -0
  49. data/processed/11-ev2img.pkl +3 -0
  50. data/processed/12-epo.fif +3 -0
EEGFaceSem/EEGModels.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ARL_EEGModels - A collection of Convolutional Neural Network models for EEG
3
+ Signal Processing and Classification, using Keras and Tensorflow
4
+
5
+ Requirements:
6
+ (1) tensorflow == 2.X (as of this writing, 2.0 - 2.3 have been verified
7
+ as working)
8
+
9
+ To run the EEG/MEG ERP classification sample script, you will also need
10
+
11
+ (4) mne >= 0.17.1
12
+ (5) PyRiemann >= 0.2.5
13
+ (6) scikit-learn >= 0.20.1
14
+ (7) matplotlib >= 2.2.3
15
+
16
+ To use:
17
+
18
+ (1) Place this file in the PYTHONPATH variable in your IDE (i.e.: Spyder)
19
+ (2) Import the model as
20
+
21
+ from EEGModels import EEGNet
22
+
23
+ model = EEGNet(nb_classes = ..., Chans = ..., Samples = ...)
24
+
25
+ (3) Then compile and fit the model
26
+
27
+ model.compile(loss = ..., optimizer = ..., metrics = ...)
28
+ fitted = model.fit(...)
29
+ predicted = model.predict(...)
30
+
31
+ Portions of this project are works of the United States Government and are not
32
+ subject to domestic copyright protection under 17 USC Sec. 105. Those
33
+ portions are released world-wide under the terms of the Creative Commons Zero
34
+ 1.0 (CC0) license.
35
+
36
+ Other portions of this project are subject to domestic copyright protection
37
+ under 17 USC Sec. 105. Those portions are licensed under the Apache 2.0
38
+ license. The complete text of the license governing this material is in
39
+ the file labeled LICENSE.TXT that is a part of this project's official
40
+ distribution.
41
+ """
42
+
43
+ from tensorflow.keras.models import Model
44
+ from tensorflow.keras.layers import Dense, Activation, Permute, Dropout
45
+ from tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D
46
+ from tensorflow.keras.layers import SeparableConv2D, DepthwiseConv2D
47
+ from tensorflow.keras.layers import BatchNormalization
48
+ from tensorflow.keras.layers import SpatialDropout2D
49
+ from tensorflow.keras.regularizers import l1_l2
50
+ from tensorflow.keras.layers import Input, Flatten
51
+ from tensorflow.keras.constraints import max_norm
52
+ from tensorflow.keras import backend as K
53
+
54
+
55
+ def EEGNet(nb_classes, Chans = 64, Samples = 128,
56
+ dropoutRate = 0.5, kernLength = 64, F1 = 8,
57
+ D = 2, F2 = 16, norm_rate = 0.25, dropoutType = 'Dropout'):
58
+ """ Keras Implementation of EEGNet
59
+ http://iopscience.iop.org/article/10.1088/1741-2552/aace8c/meta
60
+
61
+ Note that this implements the newest version of EEGNet and NOT the earlier
62
+ version (version v1 and v2 on arxiv). We strongly recommend using this
63
+ architecture as it performs much better and has nicer properties than
64
+ our earlier version. For example:
65
+
66
+ 1. Depthwise Convolutions to learn spatial filters within a
67
+ temporal convolution. The use of the depth_multiplier option maps
68
+ exactly to the number of spatial filters learned within a temporal
69
+ filter. This matches the setup of algorithms like FBCSP which learn
70
+ spatial filters within each filter in a filter-bank. This also limits
71
+ the number of free parameters to fit when compared to a fully-connected
72
+ convolution.
73
+
74
+ 2. Separable Convolutions to learn how to optimally combine spatial
75
+ filters across temporal bands. Separable Convolutions are Depthwise
76
+ Convolutions followed by (1x1) Pointwise Convolutions.
77
+
78
+
79
+ While the original paper used Dropout, we found that SpatialDropout2D
80
+ sometimes produced slightly better results for classification of ERP
81
+ signals. However, SpatialDropout2D significantly reduced performance
82
+ on the Oscillatory dataset (SMR, BCI-IV Dataset 2A). We recommend using
83
+ the default Dropout in most cases.
84
+
85
+ Assumes the input signal is sampled at 128Hz. If you want to use this model
86
+ for any other sampling rate you will need to modify the lengths of temporal
87
+ kernels and average pooling size in blocks 1 and 2 as needed (double the
88
+ kernel lengths for double the sampling rate, etc). Note that we haven't
89
+ tested the model performance with this rule so this may not work well.
90
+
91
+ The model with default parameters gives the EEGNet-8,2 model as discussed
92
+ in the paper. This model should do pretty well in general, although it is
93
+ advised to do some model searching to get optimal performance on your
94
+ particular dataset.
95
+
96
+ We set F2 = F1 * D (number of input filters = number of output filters) for
97
+ the SeparableConv2D layer. We haven't extensively tested other values of this
98
+ parameter (say, F2 < F1 * D for compressed learning, and F2 > F1 * D for
99
+ overcomplete). We believe the main parameters to focus on are F1 and D.
100
+
101
+ Inputs:
102
+
103
+ nb_classes : int, number of classes to classify
104
+ Chans, Samples : number of channels and time points in the EEG data
105
+ dropoutRate : dropout fraction
106
+ kernLength : length of temporal convolution in first layer. We found
107
+ that setting this to be half the sampling rate worked
108
+ well in practice. For the SMR dataset in particular
109
+ since the data was high-passed at 4Hz we used a kernel
110
+ length of 32.
111
+ F1, F2 : number of temporal filters (F1) and number of pointwise
112
+ filters (F2) to learn. Default: F1 = 8, F2 = F1 * D.
113
+ D : number of spatial filters to learn within each temporal
114
+ convolution. Default: D = 2
115
+ dropoutType : Either SpatialDropout2D or Dropout, passed as a string.
116
+
117
+ """
118
+
119
+ if dropoutType == 'SpatialDropout2D':
120
+ dropoutType = SpatialDropout2D
121
+ elif dropoutType == 'Dropout':
122
+ dropoutType = Dropout
123
+ else:
124
+ raise ValueError('dropoutType must be one of SpatialDropout2D '
125
+ 'or Dropout, passed as a string.')
126
+
127
+ input1 = Input(shape = (Chans, Samples, 1))
128
+
129
+ ##################################################################
130
+ block1 = Conv2D(F1, (1, kernLength), padding = 'same',
131
+ input_shape = (Chans, Samples, 1),
132
+ use_bias = False)(input1)
133
+ block1 = BatchNormalization()(block1)
134
+ block1 = DepthwiseConv2D((Chans, 1), use_bias = False,
135
+ depth_multiplier = D,
136
+ depthwise_constraint = max_norm(1.))(block1)
137
+ block1 = BatchNormalization()(block1)
138
+ block1 = Activation('elu')(block1)
139
+ block1 = AveragePooling2D((1, 4))(block1)
140
+ block1 = dropoutType(dropoutRate)(block1)
141
+
142
+ block2 = SeparableConv2D(F2, (1, 16),
143
+ use_bias = False, padding = 'same')(block1)
144
+ block2 = BatchNormalization()(block2)
145
+ block2 = Activation('elu')(block2)
146
+ block2 = AveragePooling2D((1, 8))(block2)
147
+ block2 = dropoutType(dropoutRate)(block2)
148
+
149
+ flatten = Flatten(name = 'flatten')(block2)
150
+
151
+ dense = Dense(nb_classes, name = 'dense',
152
+ kernel_constraint = max_norm(norm_rate))(flatten)
153
+ softmax = Activation('softmax', name = 'softmax')(dense)
154
+
155
+ return Model(inputs=input1, outputs=softmax)
156
+
157
+
158
+
159
+
160
+ def EEGNet_SSVEP(nb_classes = 12, Chans = 8, Samples = 256,
161
+ dropoutRate = 0.5, kernLength = 256, F1 = 96,
162
+ D = 1, F2 = 96, dropoutType = 'Dropout'):
163
+ """ SSVEP Variant of EEGNet, as used in [1].
164
+
165
+ Inputs:
166
+
167
+ nb_classes : int, number of classes to classify
168
+ Chans, Samples : number of channels and time points in the EEG data
169
+ dropoutRate : dropout fraction
170
+ kernLength : length of temporal convolution in first layer
171
+ F1, F2 : number of temporal filters (F1) and number of pointwise
172
+ filters (F2) to learn.
173
+ D : number of spatial filters to learn within each temporal
174
+ convolution.
175
+ dropoutType : Either SpatialDropout2D or Dropout, passed as a string.
176
+
177
+
178
+ [1]. Waytowich, N. et. al. (2018). Compact Convolutional Neural Networks
179
+ for Classification of Asynchronous Steady-State Visual Evoked Potentials.
180
+ Journal of Neural Engineering vol. 15(6).
181
+ http://iopscience.iop.org/article/10.1088/1741-2552/aae5d8
182
+
183
+ """
184
+
185
+ if dropoutType == 'SpatialDropout2D':
186
+ dropoutType = SpatialDropout2D
187
+ elif dropoutType == 'Dropout':
188
+ dropoutType = Dropout
189
+ else:
190
+ raise ValueError('dropoutType must be one of SpatialDropout2D '
191
+ 'or Dropout, passed as a string.')
192
+
193
+ input1 = Input(shape = (Chans, Samples, 1))
194
+
195
+ ##################################################################
196
+ block1 = Conv2D(F1, (1, kernLength), padding = 'same',
197
+ input_shape = (Chans, Samples, 1),
198
+ use_bias = False)(input1)
199
+ block1 = BatchNormalization()(block1)
200
+ block1 = DepthwiseConv2D((Chans, 1), use_bias = False,
201
+ depth_multiplier = D,
202
+ depthwise_constraint = max_norm(1.))(block1)
203
+ block1 = BatchNormalization()(block1)
204
+ block1 = Activation('elu')(block1)
205
+ block1 = AveragePooling2D((1, 4))(block1)
206
+ block1 = dropoutType(dropoutRate)(block1)
207
+
208
+ block2 = SeparableConv2D(F2, (1, 16),
209
+ use_bias = False, padding = 'same')(block1)
210
+ block2 = BatchNormalization()(block2)
211
+ block2 = Activation('elu')(block2)
212
+ block2 = AveragePooling2D((1, 8))(block2)
213
+ block2 = dropoutType(dropoutRate)(block2)
214
+
215
+ flatten = Flatten(name = 'flatten')(block2)
216
+
217
+ dense = Dense(nb_classes, name = 'dense')(flatten)
218
+ softmax = Activation('softmax', name = 'softmax')(dense)
219
+
220
+ return Model(inputs=input1, outputs=softmax)
221
+
222
+
223
+
224
+ def EEGNet_old(nb_classes, Chans = 64, Samples = 128, regRate = 0.0001,
225
+ dropoutRate = 0.25, kernels = [(2, 32), (8, 4)], strides = (2, 4)):
226
+ """ Keras Implementation of EEGNet_v1 (https://arxiv.org/abs/1611.08024v2)
227
+
228
+ This model is the original EEGNet model proposed on arxiv
229
+ https://arxiv.org/abs/1611.08024v2
230
+
231
+ with a few modifications: we use striding instead of max-pooling as this
232
+ helped slightly in classification performance while also providing a
233
+ computational speed-up.
234
+
235
+ Note that we no longer recommend the use of this architecture, as the new
236
+ version of EEGNet performs much better overall and has nicer properties.
237
+
238
+ Inputs:
239
+
240
+ nb_classes : total number of final categories
241
+ Chans, Samples : number of EEG channels and samples, respectively
242
+ regRate : regularization rate for L1 and L2 regularizations
243
+ dropoutRate : dropout fraction
244
+ kernels : the 2nd and 3rd layer kernel dimensions (default is
245
+ the [2, 32] x [8, 4] configuration)
246
+ strides : the stride size (note that this replaces the max-pool
247
+ used in the original paper)
248
+
249
+ """
250
+
251
+ # start the model
252
+ input_main = Input((Chans, Samples))
253
+ layer1 = Conv2D(16, (Chans, 1), input_shape=(Chans, Samples, 1),
254
+ kernel_regularizer = l1_l2(l1=regRate, l2=regRate))(input_main)
255
+ layer1 = BatchNormalization()(layer1)
256
+ layer1 = Activation('elu')(layer1)
257
+ layer1 = Dropout(dropoutRate)(layer1)
258
+
259
+ permute_dims = 2, 1, 3
260
+ permute1 = Permute(permute_dims)(layer1)
261
+
262
+ layer2 = Conv2D(4, kernels[0], padding = 'same',
263
+ kernel_regularizer=l1_l2(l1=0.0, l2=regRate),
264
+ strides = strides)(permute1)
265
+ layer2 = BatchNormalization()(layer2)
266
+ layer2 = Activation('elu')(layer2)
267
+ layer2 = Dropout(dropoutRate)(layer2)
268
+
269
+ layer3 = Conv2D(4, kernels[1], padding = 'same',
270
+ kernel_regularizer=l1_l2(l1=0.0, l2=regRate),
271
+ strides = strides)(layer2)
272
+ layer3 = BatchNormalization()(layer3)
273
+ layer3 = Activation('elu')(layer3)
274
+ layer3 = Dropout(dropoutRate)(layer3)
275
+
276
+ flatten = Flatten(name = 'flatten')(layer3)
277
+
278
+ dense = Dense(nb_classes, name = 'dense')(flatten)
279
+ softmax = Activation('softmax', name = 'softmax')(dense)
280
+
281
+ return Model(inputs=input_main, outputs=softmax)
282
+
283
+
284
+
285
+ def DeepConvNet(nb_classes, Chans = 64, Samples = 256,
286
+ dropoutRate = 0.5):
287
+ """ Keras implementation of the Deep Convolutional Network as described in
288
+ Schirrmeister et. al. (2017), Human Brain Mapping.
289
+
290
+ This implementation assumes the input is a 2-second EEG signal sampled at
291
+ 128Hz, as opposed to signals sampled at 250Hz as described in the original
292
+ paper. We also perform temporal convolutions of length (1, 5) as opposed
293
+ to (1, 10) due to this sampling rate difference.
294
+
295
+ Note that we use the max_norm constraint on all convolutional layers, as
296
+ well as the classification layer. We also change the defaults for the
297
+ BatchNormalization layer. We used this based on a personal communication
298
+ with the original authors.
299
+
300
+ ours original paper
301
+ pool_size 1, 2 1, 3
302
+ strides 1, 2 1, 3
303
+ conv filters 1, 5 1, 10
304
+
305
+ Note that this implementation has not been verified by the original
306
+ authors.
307
+
308
+ """
309
+
310
+ # start the model
311
+ input_main = Input((Chans, Samples, 1))
312
+ block1 = Conv2D(25, (1, 5),
313
+ input_shape=(Chans, Samples, 1),
314
+ kernel_constraint = max_norm(2., axis=(0,1,2)))(input_main)
315
+ block1 = Conv2D(25, (Chans, 1),
316
+ kernel_constraint = max_norm(2., axis=(0,1,2)))(block1)
317
+ block1 = BatchNormalization(epsilon=1e-05, momentum=0.9)(block1)
318
+ block1 = Activation('elu')(block1)
319
+ block1 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block1)
320
+ block1 = Dropout(dropoutRate)(block1)
321
+
322
+ block2 = Conv2D(50, (1, 5),
323
+ kernel_constraint = max_norm(2., axis=(0,1,2)))(block1)
324
+ block2 = BatchNormalization(epsilon=1e-05, momentum=0.9)(block2)
325
+ block2 = Activation('elu')(block2)
326
+ block2 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block2)
327
+ block2 = Dropout(dropoutRate)(block2)
328
+
329
+ block3 = Conv2D(100, (1, 5),
330
+ kernel_constraint = max_norm(2., axis=(0,1,2)))(block2)
331
+ block3 = BatchNormalization(epsilon=1e-05, momentum=0.9)(block3)
332
+ block3 = Activation('elu')(block3)
333
+ block3 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block3)
334
+ block3 = Dropout(dropoutRate)(block3)
335
+
336
+ block4 = Conv2D(200, (1, 5),
337
+ kernel_constraint = max_norm(2., axis=(0,1,2)))(block3)
338
+ block4 = BatchNormalization(epsilon=1e-05, momentum=0.9)(block4)
339
+ block4 = Activation('elu')(block4)
340
+ block4 = MaxPooling2D(pool_size=(1, 2), strides=(1, 2))(block4)
341
+ block4 = Dropout(dropoutRate)(block4)
342
+
343
+ flatten = Flatten()(block4)
344
+
345
+ dense = Dense(nb_classes, kernel_constraint = max_norm(0.5))(flatten)
346
+ softmax = Activation('softmax')(dense)
347
+
348
+ return Model(inputs=input_main, outputs=softmax)
349
+
350
+
351
+ # need these for ShallowConvNet
352
+ def square(x):
353
+ return K.square(x)
354
+
355
+ def log(x):
356
+ return K.log(K.clip(x, min_value = 1e-7, max_value = 10000))
357
+
358
+
359
+ def ShallowConvNet(nb_classes, Chans = 64, Samples = 128, dropoutRate = 0.5):
360
+ """ Keras implementation of the Shallow Convolutional Network as described
361
+ in Schirrmeister et. al. (2017), Human Brain Mapping.
362
+
363
+ Assumes the input is a 2-second EEG signal sampled at 128Hz. Note that in
364
+ the original paper, they do temporal convolutions of length 25 for EEG
365
+ data sampled at 250Hz. We instead use length 13 since the sampling rate is
366
+ roughly half of the 250Hz which the paper used. The pool_size and stride
367
+ in later layers is also approximately half of what is used in the paper.
368
+
369
+ Note that we use the max_norm constraint on all convolutional layers, as
370
+ well as the classification layer. We also change the defaults for the
371
+ BatchNormalization layer. We used this based on a personal communication
372
+ with the original authors.
373
+
374
+ ours original paper
375
+ pool_size 1, 35 1, 75
376
+ strides 1, 7 1, 15
377
+ conv filters 1, 13 1, 25
378
+
379
+ Note that this implementation has not been verified by the original
380
+ authors. We do note that this implementation reproduces the results in the
381
+ original paper with minor deviations.
382
+ """
383
+
384
+ # start the model
385
+ input_main = Input((Chans, Samples, 1))
386
+ block1 = Conv2D(40, (1, 13),
387
+ input_shape=(Chans, Samples, 1),
388
+ kernel_constraint = max_norm(2., axis=(0,1,2)))(input_main)
389
+ block1 = Conv2D(40, (Chans, 1), use_bias=False,
390
+ kernel_constraint = max_norm(2., axis=(0,1,2)))(block1)
391
+ block1 = BatchNormalization(epsilon=1e-05, momentum=0.9)(block1)
392
+ block1 = Activation(square)(block1)
393
+ block1 = AveragePooling2D(pool_size=(1, 35), strides=(1, 7))(block1)
394
+ block1 = Activation(log)(block1)
395
+ block1 = Dropout(dropoutRate)(block1)
396
+ flatten = Flatten()(block1)
397
+ dense = Dense(nb_classes, kernel_constraint = max_norm(0.5))(flatten)
398
+ softmax = Activation('softmax')(dense)
399
+
400
+ return Model(inputs=input_main, outputs=softmax)
401
+
402
+
EEGFaceSem/EEGPT/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .eegpt_linear import EEGPT_InternalModel
EEGFaceSem/EEGPT/eegpt_linear.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import torch
3
+ from torch import nn
4
+ from torch.utils.data import TensorDataset, DataLoader
5
+ import numpy as np
6
+ from functools import partial
7
+ import math
8
+ import os
9
+ from itertools import chain
10
+
11
+ # Imports from copied modules
12
+ from .modules.EEGPT_mcae import Block, trunc_normal_
13
+ from .modules.Network.utils import LinearWithConstraint
14
+
15
+ # Constants
16
+ EEGPT_ch_names = [
17
+ 'FP1', 'FPZ', 'FP2', 'AF7', 'AF3', 'AF4', 'AF8', 'F7', 'F5', 'F3', 'F1', 'FZ', 'F2', 'F4', 'F6', 'F8',
18
+ 'FT7', 'FC5', 'FC3', 'FC1', 'FCZ', 'FC2', 'FC4', 'FC6', 'FT8', 'T7', 'C5', 'C3', 'C1', 'CZ', 'C2', 'C4',
19
+ 'C6', 'T8', 'TP7', 'CP5', 'CP3', 'CP1', 'CPZ', 'CP2', 'CP4', 'CP6', 'TP8', 'P7', 'P5', 'P3', 'P1', 'PZ',
20
+ 'P2', 'P4', 'P6', 'P8', 'PO7', "PO5", 'PO3', 'POZ', 'PO4', "PO6", 'PO8', 'O1', 'OZ', 'O2',
21
+ ]
22
+ EEGPT_ch_names = [x.upper() for x in EEGPT_ch_names]
23
+ CHANNEL_DICT = {k.upper(): v for v, k in enumerate(EEGPT_ch_names)}
24
+ FACECAT_ch_names_all = [x.upper() for x in ['Fp1', 'Fp2', 'F7', 'F3', 'Fz', 'F4', 'F8', 'FC5', 'FC1', 'FC2', 'FC6', 'T7', 'C3', 'Cz', 'C4', 'T8', 'TP9', 'CP5', 'CP1', 'CP2', 'CP6', 'TP10', 'P7', 'P3', 'Pz', 'P4', 'P8', 'PO9', 'O1', 'Iz', 'O2', 'PO10']]
25
+ FACECAT_ch_names, FACECAT_ch_ids = [], []
26
+ for ch in EEGPT_ch_names:
27
+ if ch in FACECAT_ch_names_all:
28
+ FACECAT_ch_names.append(ch)
29
+ FACECAT_ch_ids.append(FACECAT_ch_names_all.index(ch))
30
+
31
+ # Helper function from original script
32
+ def seed_torch(seed=1029):
33
+ import random
34
+ random.seed(seed)
35
+ os.environ['PYTHONHASHSEED'] = str(seed)
36
+ np.random.seed(seed)
37
+ torch.manual_seed(seed)
38
+ torch.cuda.manual_seed(seed)
39
+ torch.cuda.manual_seed_all(seed)
40
+ torch.backends.cudnn.benchmark = False
41
+ torch.backends.cudnn.deterministic = True
42
+
43
+ # --- Start of Model-related classes copied from rep_EEGPT_inter.py ---
44
+
45
+ class Conv2dWithConstraint(nn.Conv2d):
46
+ def __init__(self, *args, doWeightNorm=True, max_norm=1, **kwargs):
47
+ self.max_norm = max_norm
48
+ self.doWeightNorm = doWeightNorm
49
+ super(Conv2dWithConstraint, self).__init__(*args, **kwargs)
50
+
51
+ def forward(self, x):
52
+ if self.doWeightNorm:
53
+ self.weight.data = torch.renorm(self.weight.data, p=2, dim=0, maxnorm=self.max_norm)
54
+ return super(Conv2dWithConstraint, self).forward(x)
55
+
56
+ class PatchEmbed(nn.Module):
57
+ def __init__(self, patch_size=16, patch_stride=None, embed_dim=768):
58
+ super().__init__()
59
+ self.patch_size = patch_size
60
+ self.patch_stride = patch_stride
61
+ self.proj = nn.Conv2d(1, embed_dim, kernel_size=(1, patch_size),
62
+ stride=(1, patch_size if patch_stride is None else patch_stride))
63
+
64
+ @staticmethod
65
+ def compute_num_patches(img_size, patch_size, patch_stride):
66
+ if patch_stride is None:
67
+ return (img_size[0], (img_size[1] // patch_size))
68
+ else:
69
+ return (img_size[0], ((img_size[1] - patch_size) // patch_stride + 1))
70
+
71
+ def forward(self, x):
72
+ x = x.unsqueeze(1)
73
+ x = self.proj(x).transpose(1, 3)
74
+ return x
75
+
76
+ class ChannelScaleLayer(nn.Module):
77
+ def __init__(self, ch_nums=1):
78
+ super().__init__()
79
+ self.shape = (ch_nums,)
80
+ init_weights = 10**-6 * torch.rand(self.shape)
81
+ self.weights = nn.Parameter(init_weights, requires_grad=True)
82
+
83
+ def forward(self, x):
84
+ return x * (1 + self.weights[..., None])
85
+
86
+ class EEGTransformerMulti(nn.Module):
87
+ def __init__(self, patch_size=64, patch_stride=None, embed_dim=768, embed_num=1,
88
+ depth=12, num_heads=12, mlp_ratio=4.0, qkv_bias=True, drop_rate=0.0,
89
+ attn_drop_rate=0.0, drop_path_rate=0.0, norm_layer=nn.LayerNorm,
90
+ patch_module=PatchEmbed, init_std=0.02, **kwargs):
91
+ super().__init__()
92
+ self.embed_dim = embed_dim
93
+ self.embed_num = embed_num
94
+ self.init_std = init_std
95
+ self.patch_embed = patch_module(patch_size=patch_size, patch_stride=patch_stride, embed_dim=embed_dim)
96
+ self.chan_embed = nn.Embedding(len(CHANNEL_DICT), embed_dim)
97
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)]
98
+ self.blocks = nn.ModuleList([
99
+ Block(dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias,
100
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer)
101
+ for i in range(depth)])
102
+ self.norm = norm_layer(embed_dim)
103
+ self.summary_token = nn.Parameter(torch.zeros(1, embed_num, embed_dim))
104
+ trunc_normal_(self.summary_token, std=init_std)
105
+ self.apply(self._init_weights)
106
+ def rescale(param, layer_id):
107
+ param.div_(math.sqrt(2.0 * layer_id))
108
+ for layer_id, layer in enumerate(self.blocks):
109
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
110
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
111
+
112
+ def _init_weights(self, m):
113
+ if isinstance(m, nn.Linear):
114
+ trunc_normal_(m.weight, std=self.init_std)
115
+ if isinstance(m, nn.Linear) and m.bias is not None:
116
+ nn.init.constant_(m.bias, 0)
117
+ elif isinstance(m, nn.LayerNorm):
118
+ nn.init.constant_(m.bias, 0)
119
+ nn.init.constant_(m.weight, 1.0)
120
+ elif isinstance(m, nn.Conv2d):
121
+ trunc_normal_(m.weight, std=self.init_std)
122
+ if m.bias is not None:
123
+ nn.init.constant_(m.bias, 0)
124
+ elif isinstance(m, nn.Embedding):
125
+ torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
126
+
127
+ def prepare_chan_ids(self, channels):
128
+ chan_ids = [CHANNEL_DICT[ch.upper().strip('.')] for ch in channels]
129
+ return torch.tensor(chan_ids).unsqueeze_(0).long()
130
+
131
+ def forward(self, x, chan_ids):
132
+ x = self.patch_embed(x)
133
+ B, N, C, D = x.shape
134
+ chan_ids = chan_ids.to(x.device)
135
+ x = x + self.chan_embed(chan_ids).unsqueeze(0)
136
+ x = x.flatten(0, 1)
137
+ summary_token = self.summary_token.repeat((x.shape[0], 1, 1))
138
+ x = torch.cat([x, summary_token], dim=1)
139
+ for blk in self.blocks:
140
+ x = blk(x)
141
+ x = x[:, -summary_token.shape[1]:, :]
142
+ x = self.norm(x)
143
+ x = x.flatten(-2)
144
+ x = x.reshape((B, N, self.embed_num, -1))
145
+ return x
146
+
147
+ # --- End of copied classes ---
148
+
149
+
150
+ class EEGPT_InternalModel(nn.Module):
151
+ """A single nn.Module to hold all parts for easier management."""
152
+ def __init__(self, num_classes, pretrained_weights_path=None, input_shape=None, ids_map=FACECAT_ch_ids, ch_names=FACECAT_ch_names):
153
+ super().__init__()
154
+ self.num_classes = num_classes
155
+ _, self.n_samples = input_shape
156
+ self.chans_num = len(ids_map)
157
+ self.ids_map = ids_map
158
+ self.ch_names = ch_names
159
+
160
+ self.channel_scaler = ChannelScaleLayer(ch_nums=self.chans_num)
161
+ self.target_encoder = EEGTransformerMulti(patch_size=64, patch_stride=32, embed_num=4, embed_dim=512, depth=8, num_heads=8, mlp_ratio=4.0, qkv_bias=True, norm_layer=partial(nn.LayerNorm, eps=1e-6))
162
+ self.chans_ids = self.target_encoder.prepare_chan_ids(self.ch_names)
163
+
164
+ if pretrained_weights_path:
165
+ self.initilize_pretrained_ckpt(pretrained_weights_path)
166
+
167
+ # Freeze the encoder
168
+ for param in self.target_encoder.parameters():
169
+ param.requires_grad = False
170
+
171
+ # Fine-tuning Head
172
+ self.linear_probe1 = LinearWithConstraint(2048, 16, max_norm=1)
173
+ mult = (self.n_samples - 64) // 32 + 1
174
+ self.linear_probe2 = LinearWithConstraint(16*mult, self.num_classes, max_norm=0.25)
175
+ self.drop = nn.Dropout(p=0.50)
176
+
177
+ # add a method to load the model from a checkpoint only once for all instances
178
+ def initilize_pretrained_ckpt(self, pretrained_weights_path):
179
+ if not hasattr(EEGPT_InternalModel, 'encoder_state_dict'):
180
+ pretrain_ckpt = torch.load(pretrained_weights_path, map_location='cpu', weights_only=False)
181
+ EEGPT_InternalModel.encoder_state_dict = {k.replace('target_encoder.', ''): v for k, v in pretrain_ckpt['state_dict'].items() if k.startswith("target_encoder.")}
182
+ self.target_encoder.load_state_dict(EEGPT_InternalModel.encoder_state_dict)
183
+
184
+ def forward(self, x):
185
+ x = x.to(torch.float)
186
+ x = x * 1e3
187
+ x = x - x.mean(dim=-2, keepdim=True)
188
+ x = x[:, self.ids_map, :]
189
+ x = self.channel_scaler(x)
190
+
191
+ self.target_encoder.eval()
192
+ z = self.target_encoder(x, self.chans_ids.to(x.device))
193
+ h = z.flatten(2)
194
+ h = self.linear_probe1(self.drop(h))
195
+ h = h.flatten(1)
196
+ h = self.linear_probe2(h)
197
+ return h
198
+
199
+ def trainable_parameters(self):
200
+ return chain(
201
+ self.channel_scaler.parameters(),
202
+ self.linear_probe1.parameters(),
203
+ self.linear_probe2.parameters()
204
+ )
205
+
206
+ def copy_from(self, other_model):
207
+ self.load_state_dict(other_model.state_dict())
EEGFaceSem/EEGPT/modules/EEGPT_mcae.py ADDED
@@ -0,0 +1,876 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # EEG Pretrain Transformers
2
+ # Copyright (c) Meta Platforms, Inc. and affiliates.
3
+ # All rights reserved.
4
+ #
5
+ # This source code is licensed under the license found in the
6
+ # LICENSE file in the root directory of this source tree.
7
+ #
8
+
9
+ import math
10
+ from functools import partial
11
+ import numpy as np
12
+
13
+ import torch
14
+ import torch.nn as nn
15
+
16
+ import math
17
+
18
+ import torch
19
+
20
+ from logging import getLogger
21
+
22
+ logger = getLogger()
23
+
24
+
25
+ CHANNEL_DICT = {k.upper():v for v,k in enumerate(
26
+ [ 'FP1', 'FPZ', 'FP2',
27
+ "AF7", 'AF3', 'AF4', "AF8",
28
+ 'F7', 'F5', 'F3', 'F1', 'FZ', 'F2', 'F4', 'F6', 'F8',
29
+ 'FT7', 'FC5', 'FC3', 'FC1', 'FCZ', 'FC2', 'FC4', 'FC6', 'FT8',
30
+ 'T7', 'C5', 'C3', 'C1', 'CZ', 'C2', 'C4', 'C6', 'T8',
31
+ 'TP7', 'CP5', 'CP3', 'CP1', 'CPZ', 'CP2', 'CP4', 'CP6', 'TP8',
32
+ 'P7', 'P5', 'P3', 'P1', 'PZ', 'P2', 'P4', 'P6', 'P8',
33
+ 'PO7', "PO5", 'PO3', 'POZ', 'PO4', "PO6", 'PO8',
34
+ 'O1', 'OZ', 'O2', ])}
35
+
36
+ ################################# Utils ######################################
37
+
38
+ def _no_grad_trunc_normal_(tensor, mean, std, a, b):
39
+ # Cut & paste from PyTorch official master until it's in a few official releases - RW
40
+
41
+ def norm_cdf(x):
42
+ # Computes standard normal cumulative distribution function
43
+ return (1. + math.erf(x / math.sqrt(2.))) / 2.
44
+
45
+ with torch.no_grad():
46
+ # Values are generated by using a truncated uniform distribution and
47
+ # then using the inverse CDF for the normal distribution.
48
+ # Get upper and lower cdf values
49
+ l = norm_cdf((a - mean) / std)
50
+ u = norm_cdf((b - mean) / std)
51
+
52
+ # Uniformly fill tensor with values from [l, u], then translate to
53
+ # [2l-1, 2u-1].
54
+ tensor.uniform_(2 * l - 1, 2 * u - 1)
55
+
56
+ # Use inverse cdf transform for normal distribution to get truncated
57
+ # standard normal
58
+ tensor.erfinv_()
59
+
60
+ # Transform to proper mean, std
61
+ tensor.mul_(std * math.sqrt(2.))
62
+ tensor.add_(mean)
63
+
64
+ # Clamp to ensure it's in the proper range
65
+ tensor.clamp_(min=a, max=b)
66
+ return tensor
67
+
68
+
69
+ def trunc_normal_(tensor, mean=0., std=1., a=-2., b=2.):
70
+ # type: (Tensor, float, float, float, float) -> Tensor
71
+ return _no_grad_trunc_normal_(tensor, mean, std, a, b)
72
+
73
+
74
+ def apply_mask(mask, x):
75
+ """
76
+ :param x: tensor of shape [B (batch-size), N (num-patches), C, D (feature-dim)]
77
+ :param mask: tensor [mN, mC] containing indices of patches in [N, C] to keep
78
+ """
79
+ B, N, C, D = x.shape
80
+ if len(mask.shape)==2:
81
+ mN, mC = mask.shape
82
+
83
+ mask_keep = mask.reshape((1,mN*mC,1)).repeat((B, 1, D))
84
+ masked_x = torch.gather(x.reshape((B, N*C, D)), dim=-2, index=mask_keep)
85
+ masked_x = masked_x.contiguous().view((B,mN,mC,D))
86
+ else:
87
+ mN = mask.shape[0]
88
+
89
+ mask_keep = mask.reshape((1,mN,1)).repeat((B, 1, D))
90
+ masked_x = torch.gather(x.reshape((B, N*C, D)), dim=-2, index=mask_keep)
91
+ return masked_x
92
+
93
+ def apply_mask_t(mask_t, x):
94
+ """
95
+ :param x: tensor of shape [B (batch-size), N (num-patches), C, D (feature-dim)]
96
+ :param mask: tensor [mN, mC] containing indices of patches in [N, C] to keep
97
+ """
98
+ B, N, D = x.shape
99
+ mN = mask_t.shape[0]
100
+
101
+ mask_keep = mask_t.reshape((1,mN,1)).repeat((B, 1, D))
102
+ masked_x = torch.gather(x, dim=1, index=mask_keep)
103
+ return masked_x
104
+
105
+ def repeat_interleave_batch(x, B, repeat):
106
+ N = len(x) // B
107
+ x = torch.cat([
108
+ torch.cat([x[i*B:(i+1)*B] for _ in range(repeat)], dim=0)
109
+ for i in range(N)
110
+ ], dim=0)
111
+ return x
112
+
113
+ # helper functions
114
+ def exists(val):
115
+ return val is not None
116
+
117
+ # rotary embedding helper functions
118
+
119
+ def rotate_half(x):
120
+
121
+ # x = rearrange(x, '... (d r) -> ... d r', r = 2)
122
+ x = x.reshape((*x.shape[:-1],x.shape[-1]//2, 2))
123
+ x1, x2 = x.unbind(dim = -1)
124
+ x = torch.stack((-x2, x1), dim = -1)
125
+ # return rearrange(x, '... d r -> ... (d r)')
126
+ return x.flatten(-2)
127
+
128
+ def apply_rotary_emb(freqs, t, start_index = 0, scale = 1.):
129
+ freqs = freqs.to(t)
130
+ rot_dim = freqs.shape[-1]
131
+ end_index = start_index + rot_dim
132
+ assert rot_dim <= t.shape[-1], f'feature dimension {t.shape[-1]} is not of sufficient size to rotate in all the positions {rot_dim}'
133
+ t_left, t, t_right = t[..., :start_index], t[..., start_index:end_index], t[..., end_index:]
134
+ t = (t * freqs.cos() * scale) + (rotate_half(t) * freqs.sin() * scale)
135
+ return torch.cat((t_left, t, t_right), dim = -1)
136
+
137
+ ################################# RoPE Model Begin ######################################
138
+ class RotaryEmbedding(nn.Module):
139
+ def __init__(
140
+ self,
141
+ dim,
142
+ theta = 10000,
143
+ learned_freq = False,
144
+ interpolate_factor = 1.
145
+ ):
146
+ super().__init__()
147
+
148
+ self.cache = dict()
149
+ self.cache_scale = dict()
150
+ self.freqs = nn.Parameter(
151
+ 1. / (theta ** (torch.arange(0, dim, 2)[:(dim // 2)].float() / dim)),
152
+ requires_grad = learned_freq)
153
+
154
+ # interpolation factors
155
+
156
+ assert interpolate_factor >= 1.
157
+ self.interpolate_factor = interpolate_factor
158
+
159
+ self.register_buffer('scale', None)
160
+
161
+ def prepare_freqs(self, num_patches = (1, 8), device='cuda', dtype=torch.float, offset = 0):
162
+ # num_patches (C, N)
163
+ C, N = num_patches
164
+ cache_key = f'freqs:{num_patches}'
165
+
166
+ if cache_key in self.cache:
167
+ return self.cache[cache_key]
168
+
169
+ seq_pos = torch.arange(N, device = device, dtype = dtype)
170
+ seq_pos = seq_pos.repeat_interleave(repeats=C, dim=0) # correspond to x (B, N, C, D)
171
+ seq_pos = (seq_pos + offset) / self.interpolate_factor
172
+
173
+ freqs = self.freqs
174
+ freqs = torch.outer(seq_pos.type(freqs.dtype), freqs) # (n_seq_pos, n_freqs)
175
+ freqs = freqs.repeat_interleave(repeats=2, dim=-1) # (n_seq_pos, n_freqs*2)
176
+
177
+ self.cache[cache_key] = freqs
178
+
179
+ return freqs
180
+
181
+
182
+
183
+
184
+ ################################# EEGPT Model Begin ######################################
185
+
186
+ class DropPath(nn.Module):
187
+ """Drop paths (Stochastic Depth) per sample (when applied in main path of residual blocks).
188
+ """
189
+ def __init__(self, drop_prob=None):
190
+ super(DropPath, self).__init__()
191
+ self.drop_prob = drop_prob
192
+
193
+ def drop_path(self, x, drop_prob: float = 0., training: bool = False):
194
+ if drop_prob == 0. or not training:
195
+ return x
196
+ keep_prob = 1 - drop_prob
197
+ shape = (x.shape[0],) + (1,) * (x.ndim - 1) # work with diff dim tensors, not just 2D ConvNets
198
+ random_tensor = keep_prob + torch.rand(shape, dtype=x.dtype, device=x.device)
199
+ random_tensor.floor_() # binarize
200
+ output = x.div(keep_prob) * random_tensor
201
+ return output
202
+
203
+ def forward(self, x):
204
+ return self.drop_path(x, self.drop_prob, self.training)
205
+
206
+
207
+ class MLP(nn.Module):
208
+ def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.):
209
+ super().__init__()
210
+ out_features = out_features or in_features
211
+ hidden_features = hidden_features or in_features
212
+ self.fc1 = nn.Linear(in_features, hidden_features)
213
+ self.act = act_layer()
214
+ self.fc2 = nn.Linear(hidden_features, out_features)
215
+ self.drop = nn.Dropout(drop)
216
+
217
+ def forward(self, x):
218
+ x = self.fc1(x)
219
+ x = self.act(x)
220
+ x = self.drop(x)
221
+ x = self.fc2(x)
222
+ x = self.drop(x)
223
+ return x
224
+
225
+
226
+ class Attention(nn.Module):
227
+ def __init__(self, dim, num_heads=8, qkv_bias=False, attn_drop=0., proj_drop=0., is_causal=False, use_rope=False, return_attention=False):
228
+ super().__init__()
229
+ self.num_heads = num_heads
230
+ self.head_dim = dim // num_heads
231
+
232
+ self.use_rope = use_rope
233
+
234
+ self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias)
235
+
236
+ self.attn_drop = attn_drop
237
+ self.proj = nn.Linear(dim, dim)
238
+ self.proj_drop = nn.Dropout(proj_drop)
239
+ self.is_causal = is_causal
240
+ self.return_attention= return_attention
241
+
242
+ def forward(self, x, freqs=None):
243
+ B, T, C = x.shape
244
+ qkv = self.qkv(x).reshape(B, T, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) # 3,B,nh,t,d
245
+ q, k, v = qkv[0], qkv[1], qkv[2] # B,nh,t,d
246
+
247
+ if self.use_rope:# RoPE
248
+ q = apply_rotary_emb(freqs, q)
249
+ k = apply_rotary_emb(freqs, k)
250
+ if self.return_attention:
251
+ if self.is_causal:
252
+ attn_mask = torch.ones(q.size(-2), q.size(-2), dtype=torch.bool).tril(diagonal=0)
253
+ attn_maak = torch.zeros(q.size(-2), q.size(-2))
254
+ attn_mask = attn_maak.masked_fill(torch.logical_not(attn_mask), -float('inf'))
255
+ attn_weight = torch.softmax((q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))) + attn_mask, dim=-1)
256
+ else:
257
+ attn_weight = torch.softmax((q @ k.transpose(-2, -1) / math.sqrt(q.size(-1))), dim=-1)
258
+ return attn_weight
259
+ # efficient attention using Flash Attention CUDA kernels
260
+ y = torch.nn.functional.scaled_dot_product_attention(
261
+ q, k, v, attn_mask=None, dropout_p=self.attn_drop if self.training else 0, is_causal=self.is_causal)
262
+ x = y.transpose(1, 2).contiguous().view(B, T, C) #(B, nh, T, hs) -> (B, T, hs*nh)
263
+ x = self.proj(x)
264
+ x = self.proj_drop(x)
265
+ return x
266
+
267
+
268
+ class Block(nn.Module):
269
+ def __init__(self, dim, num_heads, mlp_ratio=4., qkv_bias=False, drop=0., attn_drop=0.,
270
+ drop_path=0., act_layer=nn.GELU, norm_layer=nn.LayerNorm, is_causal=False, use_rope=False, return_attention=False):
271
+ super().__init__()
272
+
273
+ self.return_attention= return_attention
274
+ self.norm1 = norm_layer(dim)
275
+ self.attn = Attention(
276
+ dim, num_heads=num_heads, qkv_bias=qkv_bias, attn_drop=attn_drop, proj_drop=drop, is_causal=is_causal, use_rope=use_rope, return_attention = return_attention)
277
+ self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity()
278
+ self.norm2 = norm_layer(dim)
279
+ mlp_hidden_dim = int(dim * mlp_ratio)
280
+ self.mlp = MLP(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop)
281
+
282
+ def forward(self, x, freqs=None):
283
+ y = self.attn(self.norm1(x), freqs)
284
+ if self.return_attention: return y
285
+ x = x + self.drop_path(y)
286
+ x = x + self.drop_path(self.mlp(self.norm2(x)))
287
+ return x
288
+
289
+ class PatchEmbed(nn.Module):
290
+ """ Image to Patch Embedding
291
+ """
292
+ def __init__(self, img_size=(64, 1000), patch_size=16, patch_stride=None, embed_dim=768):
293
+ super().__init__()
294
+ self.img_size = img_size
295
+ self.patch_size = patch_size
296
+ self.patch_stride = patch_stride
297
+ if patch_stride is None:
298
+ self.num_patches = ((img_size[0]), (img_size[1] // patch_size))
299
+ else:
300
+ self.num_patches = ((img_size[0]), ((img_size[1] - patch_size) // patch_stride + 1))
301
+
302
+ self.proj = nn.Conv2d(1, embed_dim, kernel_size=(1,patch_size),
303
+ stride=(1, patch_size if patch_stride is None else patch_stride))
304
+
305
+ def forward(self, x):
306
+ # x: B,C,T
307
+ x = x.unsqueeze(1)# B, 1, C, T
308
+ x = self.proj(x).transpose(1,3) # B, T, C, D
309
+ return x
310
+ class PatchNormEmbed(nn.Module):
311
+ """ Image to Patch Embedding
312
+ """
313
+ def __init__(self, img_size=(64, 1000), patch_size=16, patch_stride=None, embed_dim=768):
314
+ super().__init__()
315
+
316
+ assert img_size[1] % patch_size==0
317
+
318
+ self.img_size = img_size
319
+ self.patch_size = patch_size
320
+ self.patch_stride = patch_stride
321
+
322
+ if patch_stride is None:
323
+ self.num_patches = ((img_size[0]), (img_size[1] // patch_size))
324
+ else:
325
+ self.num_patches = ((img_size[0]), ((img_size[1] - patch_size) // patch_stride + 1))
326
+
327
+ self.unfold = torch.nn.Unfold(kernel_size=(1, patch_size), stride = (1, patch_stride if patch_stride is not None else patch_size))
328
+
329
+ self.proj = nn.Linear(patch_size, embed_dim)#+2
330
+
331
+ def forward(self, x):
332
+ # x: B,C,T
333
+ B,C,T = x.shape
334
+ x = x.unsqueeze(1) # B 1 C T
335
+
336
+ x = self.unfold(x)
337
+
338
+ x = x.transpose(-1,-2)
339
+
340
+ x = x.view(B, C, -1, self.patch_size).contiguous()
341
+ x = x.transpose(1,2)
342
+
343
+ # m = torch.mean(x, dim=-1).unsqueeze(-1)
344
+ # v = torch.std( x, dim=-1).unsqueeze(-1)
345
+ x = torch.layer_norm(x, (self.patch_size,))
346
+ # x = torch.cat([x,m,v], dim=-1) # B, T, C, P
347
+ # print(x)
348
+
349
+ x = self.proj(x) # B, T, C, D
350
+
351
+ return x
352
+ class EEGTransformerReconstructor(nn.Module):
353
+ """ EEG Transformer """
354
+ def __init__(
355
+ self,
356
+ num_patches,
357
+ patch_size=64,
358
+ embed_num=1,
359
+ use_pos_embed = False,
360
+ use_inp_embed = True,
361
+ embed_dim=768,
362
+ reconstructor_embed_dim=384,
363
+ depth=6,
364
+ num_heads=12,
365
+ mlp_ratio=4.0,
366
+ qkv_bias=True,
367
+ drop_rate=0.0,
368
+ attn_drop_rate=0.0,
369
+ drop_path_rate=0.0,
370
+ norm_layer=nn.LayerNorm,
371
+ init_std=0.02,
372
+ interpolate_factor = 2.,
373
+ return_attention_layer=-1,
374
+ **kwargs
375
+ ):
376
+ super().__init__()
377
+ self.use_inp_embed = use_inp_embed
378
+ self.use_pos_embed = use_pos_embed
379
+ self.num_patches = num_patches
380
+
381
+ if use_inp_embed:
382
+ self.reconstructor_embed = nn.Linear(embed_dim, reconstructor_embed_dim, bias=True)
383
+
384
+ if use_pos_embed:
385
+ self.pos_embed = nn.Parameter(torch.zeros(1, 1, embed_num, reconstructor_embed_dim))
386
+ trunc_normal_(self.pos_embed, std=init_std)
387
+
388
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, reconstructor_embed_dim))
389
+
390
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
391
+ # --
392
+ self.time_embed_dim = (reconstructor_embed_dim//num_heads)//2
393
+ self.time_embed = RotaryEmbedding(dim=self.time_embed_dim, interpolate_factor=interpolate_factor)
394
+ self.chan_embed = nn.Embedding(len(CHANNEL_DICT), reconstructor_embed_dim)
395
+ # --
396
+ self.reconstructor_blocks = nn.ModuleList([
397
+ Block(
398
+ dim=reconstructor_embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias,
399
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, is_causal=False, use_rope=True,
400
+ return_attention=(i+1)==return_attention_layer)
401
+ for i in range(depth)])
402
+ self.reconstructor_norm = norm_layer(reconstructor_embed_dim)
403
+ self.reconstructor_proj = nn.Linear(reconstructor_embed_dim, patch_size, bias=True)
404
+ # ------
405
+ self.init_std = init_std
406
+ trunc_normal_(self.mask_token, std=self.init_std)
407
+ self.apply(self._init_weights)
408
+ self.fix_init_weight()
409
+
410
+
411
+ def fix_init_weight(self):
412
+ def rescale(param, layer_id):
413
+ param.div_(math.sqrt(2.0 * layer_id))
414
+
415
+ for layer_id, layer in enumerate(self.reconstructor_blocks):
416
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
417
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
418
+
419
+ def _init_weights(self, m):
420
+ if isinstance(m, nn.Linear):
421
+ trunc_normal_(m.weight, std=self.init_std)
422
+ if isinstance(m, nn.Linear) and m.bias is not None:
423
+ nn.init.constant_(m.bias, 0)
424
+ elif isinstance(m, nn.LayerNorm):
425
+ nn.init.constant_(m.bias, 0)
426
+ nn.init.constant_(m.weight, 1.0)
427
+ elif isinstance(m, nn.Conv2d):
428
+ trunc_normal_(m.weight, std=self.init_std)
429
+ if m.bias is not None:
430
+ nn.init.constant_(m.bias, 0)
431
+ elif isinstance(m, nn.Embedding):
432
+ torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
433
+
434
+ def forward(self, x, chan_ids=None, mask_x=None, mask_y=None):
435
+ # conditions: (Nq, D) as qurey for downstream
436
+ # mask_x/mask_y: (mN, mC) one number index like (n*C+c) in matrix (N,C)
437
+
438
+ chan_ids = chan_ids.to(x).long()
439
+
440
+ # -- map from encoder-dim to pedictor-dim
441
+ if self.use_inp_embed:
442
+ x = self.reconstructor_embed(x)
443
+
444
+ C, N = self.num_patches
445
+ B, mN, eN, D= x.shape
446
+ # assert mN == N, f"{mN},{N}"
447
+ ############## Mask x ###############
448
+ # -- add channels positional embedding to x
449
+ chan_embed = self.chan_embed(chan_ids).unsqueeze(0) # (1,C) -> (1,1,C,D)
450
+ # -- get freqs for RoPE
451
+
452
+ if mask_x is not None:
453
+ mask_x = mask_x.to(x.device)
454
+ mask_x = torch.floor(mask_x[:,0] / C).long().to(x.device) # select first as represent
455
+
456
+ freqs_x = self.time_embed.prepare_freqs((1, N), x.device, x.dtype)
457
+ freqs_x = freqs_x.contiguous().view((1,N,self.time_embed_dim))
458
+ freqs_x = apply_mask_t(mask_x, freqs_x) # 1, mN, 1, D
459
+ freqs_x = freqs_x.contiguous().view((mask_x.shape[0], 1, self.time_embed_dim)) # mN, D//2
460
+ freqs_x = freqs_x.repeat((1, eN, 1)).flatten(0,1)
461
+
462
+ else:
463
+ freqs_x = self.time_embed.prepare_freqs((eN, N), x.device, x.dtype) # NC, time_dim
464
+
465
+ ############# Mask y ################
466
+ if mask_y is not None:
467
+ mask_y = mask_y.to(x.device)
468
+
469
+ # create query mask_token ys
470
+ N_y = mask_y.shape[0]
471
+ chan_embed = chan_embed.repeat((1,N,1,1))
472
+ chan_embed = apply_mask(mask_y, chan_embed)
473
+
474
+ freqs = self.time_embed.prepare_freqs((C, N), x.device, x.dtype) # NC, time_dim
475
+ freqs_y = freqs.contiguous().view((1, N, C, self.time_embed_dim))
476
+ freqs_y = apply_mask(mask_y, freqs_y) # 1, mN, mC, D
477
+ freqs_y = freqs_y.contiguous().view((N_y, self.time_embed_dim))
478
+
479
+ y = self.mask_token.repeat((B, N_y, 1)) + chan_embed
480
+
481
+
482
+ if self.use_pos_embed:
483
+ x = x + self.pos_embed.repeat((B, x.shape[1], 1, 1)).to(x.device)
484
+
485
+ # -- concat query mask_token ys
486
+ x = x.flatten(1,2) # B N E D -> B NE D
487
+ x = torch.cat([x,y], dim=1)
488
+ freqs_x = torch.cat([freqs_x, freqs_y], dim=0).to(x)
489
+
490
+
491
+ # -- fwd prop
492
+ for blk in self.reconstructor_blocks:
493
+ x = blk(x, freqs_x) # B, NC, D
494
+ if blk.return_attention==True: return x
495
+
496
+
497
+ x = x[:,-N_y:,:] # B, N_y, D
498
+
499
+ x = self.reconstructor_norm(x)
500
+
501
+ x = self.reconstructor_proj(x)
502
+
503
+ return x
504
+
505
+ class EEGTransformerPredictor(nn.Module):
506
+ """ EEG Transformer """
507
+ def __init__(
508
+ self,
509
+ num_patches,
510
+ embed_dim=768,
511
+ embed_num=1,
512
+ use_pos_embed = False,
513
+ use_inp_embed = True,
514
+ use_part_pred = False,
515
+ predictor_embed_dim=384,
516
+ depth=6,
517
+ num_heads=12,
518
+ mlp_ratio=4.0,
519
+ qkv_bias=True,
520
+ drop_rate=0.0,
521
+ attn_drop_rate=0.0,
522
+ drop_path_rate=0.0,
523
+ norm_layer=nn.LayerNorm,
524
+ init_std=0.02,
525
+ interpolate_factor = 2.,
526
+ return_attention_layer=-1,
527
+ **kwargs
528
+ ):
529
+ super().__init__()
530
+ self.use_part_pred = use_part_pred
531
+ self.use_pos_embed = use_pos_embed
532
+ self.use_inp_embed = use_inp_embed
533
+ self.num_patches = num_patches
534
+ self.embed_num = embed_num
535
+
536
+ if use_inp_embed:
537
+ self.predictor_embed = nn.Linear(embed_dim, predictor_embed_dim, bias=True)
538
+
539
+ if use_pos_embed:
540
+ self.pos_embed = nn.Parameter(torch.zeros(1, 1, embed_num, predictor_embed_dim))
541
+ trunc_normal_(self.pos_embed, std=init_std)
542
+
543
+ self.mask_token = nn.Parameter(torch.zeros(1, 1, embed_num, predictor_embed_dim))
544
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
545
+ # --
546
+ self.time_embed_dim = (predictor_embed_dim//num_heads)//2
547
+ self.time_embed = RotaryEmbedding(dim=self.time_embed_dim, interpolate_factor=interpolate_factor)
548
+
549
+ # --
550
+ self.predictor_blocks = nn.ModuleList([
551
+ Block(
552
+ dim=predictor_embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias,
553
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer, is_causal=False, use_rope=True,
554
+ return_attention=(i+1)==return_attention_layer)
555
+ for i in range(depth)])
556
+ self.predictor_norm = norm_layer(predictor_embed_dim)
557
+ self.predictor_proj = nn.Linear(predictor_embed_dim, embed_dim, bias=True)
558
+ # ------
559
+ self.init_std = init_std
560
+ trunc_normal_(self.mask_token, std=self.init_std)
561
+ self.apply(self._init_weights)
562
+ self.fix_init_weight()
563
+
564
+
565
+ def fix_init_weight(self):
566
+ def rescale(param, layer_id):
567
+ param.div_(math.sqrt(2.0 * layer_id))
568
+
569
+ for layer_id, layer in enumerate(self.predictor_blocks):
570
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
571
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
572
+
573
+ def _init_weights(self, m):
574
+ if isinstance(m, nn.Linear):
575
+ trunc_normal_(m.weight, std=self.init_std)
576
+ if isinstance(m, nn.Linear) and m.bias is not None:
577
+ nn.init.constant_(m.bias, 0)
578
+ elif isinstance(m, nn.LayerNorm):
579
+ nn.init.constant_(m.bias, 0)
580
+ nn.init.constant_(m.weight, 1.0)
581
+ elif isinstance(m, nn.Conv2d):
582
+ trunc_normal_(m.weight, std=self.init_std)
583
+ if m.bias is not None:
584
+ nn.init.constant_(m.bias, 0)
585
+ elif isinstance(m, nn.Embedding):
586
+ torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
587
+
588
+ def forward(self, x, mask_x=None, mask_t=None):
589
+ # conditions: (Nq, D) as qurey for downstream
590
+ # mask_t: mN one number index like (n*C+c) in matrix (N,1)
591
+
592
+ # -- map from encoder-dim to pedictor-dim
593
+ if self.use_part_pred:
594
+ inp_x = x
595
+
596
+ if self.use_inp_embed:
597
+ x = self.predictor_embed(x)
598
+
599
+ C, N = self.num_patches
600
+ B, mN, eN, D = x.shape
601
+
602
+ ############## Mask x ###############
603
+ # -- get freqs for RoPE
604
+ freqs = self.time_embed.prepare_freqs((eN, N), x.device, x.dtype) # NC, time_dim
605
+
606
+ if mask_x is not None:
607
+ mask_x = mask_x
608
+ mask_x = torch.floor(mask_x[:,0] / C).long()
609
+ ############# Mask y ################
610
+ if mask_t is None:
611
+ mask_t = torch.tensor(list(set(list(range(0,N))) - set(mask_x.tolist()))).long()
612
+ # -- concat query mask_token ys
613
+ N_y = mask_t.shape[0]
614
+ y = self.mask_token.repeat((B, N_y, 1, 1))
615
+ x = torch.cat([x,y], dim=1)
616
+
617
+ # -- masked index of tensor x rearrange to normal index
618
+ mask_id = torch.concat([mask_x.to(x.device), mask_t.to(x.device)], dim=0)
619
+ x = torch.index_select(x, dim=1, index=torch.argsort(mask_id))
620
+
621
+ if self.use_pos_embed:
622
+ x = x + self.pos_embed.repeat((B, x.shape[1], 1, 1)).to(x.device)
623
+
624
+ B, N, eN, D = x.shape
625
+ x = x.flatten(1,2)
626
+
627
+ # -- fwd prop
628
+ for blk in self.predictor_blocks:
629
+ x = blk(x, freqs) # B, NC, D
630
+ if blk.return_attention==True: return x
631
+
632
+ # -- reshape back
633
+ x = x.reshape((B, N, eN, D))
634
+
635
+ x = self.predictor_norm(x)
636
+
637
+ x = self.predictor_proj(x)
638
+
639
+ if self.use_part_pred and mask_x is not None:
640
+ cmb_x = torch.index_select(x, dim=1, index=mask_t.to(x.device))
641
+ cmb_x = torch.concat([inp_x, cmb_x], dim=1)
642
+ cmb_x = torch.index_select(cmb_x, dim=1, index=torch.argsort(mask_id))
643
+ return x, cmb_x
644
+ return x
645
+
646
+ class EEGTransformer(nn.Module):
647
+ """ EEG Transformer """
648
+ def __init__(
649
+ self,
650
+ img_size=(64,1000),
651
+ patch_size=64,
652
+ patch_stride=None,
653
+ embed_dim=768,
654
+ embed_num=1,
655
+ predictor_embed_dim=384,
656
+ depth=12,
657
+ predictor_depth=12,
658
+ num_heads=12,
659
+ mlp_ratio=4.0,
660
+ qkv_bias=True,
661
+ drop_rate=0.0,
662
+ attn_drop_rate=0.0,
663
+ drop_path_rate=0.0,
664
+ norm_layer=nn.LayerNorm,
665
+ patch_module=PatchEmbed,# PatchNormEmbed
666
+ init_std=0.02,
667
+ interpolate_factor = 2.,
668
+ return_attention_layer=-1,
669
+ **kwargs
670
+ ):
671
+ super().__init__()
672
+ self.num_features = self.embed_dim = embed_dim
673
+ self.embed_num = embed_num
674
+
675
+ self.num_heads = num_heads
676
+
677
+ # --
678
+ self.patch_embed = patch_module(
679
+ img_size=img_size,
680
+ patch_size=patch_size,
681
+ patch_stride=patch_stride,
682
+ embed_dim=embed_dim)
683
+ self.num_patches = self.patch_embed.num_patches
684
+ # --
685
+
686
+ self.chan_embed = nn.Embedding(len(CHANNEL_DICT), embed_dim)
687
+ # --
688
+ dpr = [x.item() for x in torch.linspace(0, drop_path_rate, depth)] # stochastic depth decay rule
689
+ self.blocks = nn.ModuleList([
690
+ Block(
691
+ dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias,
692
+ drop=drop_rate, attn_drop=attn_drop_rate, drop_path=dpr[i], norm_layer=norm_layer,
693
+ is_causal=False, use_rope= False, return_attention=(i+1)==return_attention_layer)
694
+ for i in range(depth)])
695
+ self.norm = norm_layer(embed_dim)
696
+ # ------
697
+ self.init_std = init_std
698
+ self.summary_token = nn.Parameter(torch.zeros(1, embed_num, embed_dim))
699
+
700
+ trunc_normal_(self.summary_token, std=self.init_std)
701
+ self.apply(self._init_weights)
702
+ self.fix_init_weight()
703
+
704
+ def prepare_chan_ids(self, channels):
705
+ chan_ids = []
706
+ for ch in channels:
707
+ ch = ch.upper().strip('.')
708
+ assert ch in CHANNEL_DICT
709
+ chan_ids.append(CHANNEL_DICT[ch])
710
+ return torch.tensor(chan_ids).unsqueeze_(0).long()
711
+
712
+ def fix_init_weight(self):
713
+ def rescale(param, layer_id):
714
+ param.div_(math.sqrt(2.0 * layer_id))
715
+
716
+ for layer_id, layer in enumerate(self.blocks):
717
+ rescale(layer.attn.proj.weight.data, layer_id + 1)
718
+ rescale(layer.mlp.fc2.weight.data, layer_id + 1)
719
+
720
+ def _init_weights(self, m):
721
+ if isinstance(m, nn.Linear):
722
+ trunc_normal_(m.weight, std=self.init_std)
723
+ if isinstance(m, nn.Linear) and m.bias is not None:
724
+ nn.init.constant_(m.bias, 0)
725
+ elif isinstance(m, nn.LayerNorm):
726
+ nn.init.constant_(m.bias, 0)
727
+ nn.init.constant_(m.weight, 1.0)
728
+ elif isinstance(m, nn.Conv2d):
729
+ trunc_normal_(m.weight, std=self.init_std)
730
+ if m.bias is not None:
731
+ nn.init.constant_(m.bias, 0)
732
+ elif isinstance(m, nn.Embedding):
733
+ torch.nn.init.normal_(m.weight, mean=0.0, std=0.02)
734
+
735
+ def forward(self, x, chan_ids=None, mask_x=None, mask_t=None):
736
+ # x.shape B, C, T
737
+ # mask_x.shape mN, mC
738
+ # mask_t.shape mN
739
+
740
+ # -- patchify x
741
+ x = self.patch_embed(x) #
742
+ B, N, C, D = x.shape
743
+
744
+ assert N==self.num_patches[1] and C==self.num_patches[0], f"{N}=={self.num_patches[1]} and {C}=={self.num_patches[0]}"
745
+
746
+ if chan_ids is None:
747
+ chan_ids = torch.arange(0,C)
748
+ chan_ids = chan_ids.to(x)
749
+
750
+ # -- add channels positional embedding to x
751
+ x = x + self.chan_embed(chan_ids.long()).unsqueeze(0) # (1,C) -> (1,1,C,D)
752
+
753
+ if mask_x is not None:
754
+ mask_x = mask_x.to(x.device)
755
+ x = apply_mask(mask_x, x)# B, mN, mC, D
756
+ B, N, C, D = x.shape
757
+
758
+
759
+ x = x.flatten(0, 1) # BmN, mC, D
760
+
761
+ # -- concat summary token
762
+ summary_token = self.summary_token.repeat((x.shape[0], 1, 1))
763
+ x = torch.cat([x,summary_token], dim=1) # BmN, mC+embed_num, D
764
+
765
+ # -- fwd prop
766
+ for i, blk in enumerate(self.blocks):
767
+ x = blk(x) # B*N, mC+1, D
768
+ if blk.return_attention==True: return x
769
+
770
+ x = x[:, -summary_token.shape[1]:, :]
771
+
772
+ if self.norm is not None:
773
+ x = self.norm(x)
774
+
775
+
776
+ x = x.flatten(-2)
777
+ x = x.reshape((B, N, -1))
778
+ # -- reshape back
779
+
780
+ if mask_t is not None:
781
+ mask_t = mask_t.to(x.device)
782
+ x = apply_mask_t(mask_t, x)# B, mN, D
783
+
784
+ x = x.reshape((B, N, self.embed_num, -1))
785
+
786
+ return x
787
+
788
+
789
+
790
+ if __name__=="__main__":
791
+ m = PatchNormEmbed((3,100), 10, 2)
792
+ print(m(1000*torch.randn((1,3,100))))
793
+ exit()
794
+ VIT_EMBED_DIMS = {
795
+ 'vit_little': 32*3,
796
+ 'vit_tiny': 192,
797
+ 'vit_small': 384,
798
+ 'vit_base': 768,
799
+ 'vit_large': 1024,
800
+ 'vit_huge': 1280,
801
+ 'vit_giant': 1408,
802
+ }
803
+
804
+ import random
805
+ import os
806
+ def seed_torch(seed=1029):
807
+ random.seed(seed)
808
+ os.environ['PYTHONHASHSEED'] = str(seed) # 为了禁止hash随机化,使得实验可复现
809
+ np.random.seed(seed)
810
+ torch.manual_seed(seed)
811
+ torch.cuda.manual_seed(seed)
812
+ torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.
813
+ torch.backends.cudnn.benchmark = False
814
+ torch.backends.cudnn.deterministic = True
815
+
816
+
817
+ seed_torch(7)
818
+ model = EEGTransformer(
819
+ img_size=[2, 12],
820
+ patch_size=2,
821
+ embed_dim=4,
822
+ depth=2,
823
+ num_heads=1,
824
+ mlp_ratio=4.0,
825
+ drop_rate=0.0,
826
+ attn_drop_rate=0.0,
827
+ drop_path_rate=0.0,
828
+ init_std=0.02,
829
+ qkv_bias=True,
830
+ norm_layer=partial(nn.LayerNorm, eps=1e-6))
831
+
832
+ x = torch.rand(1,2,12)
833
+ out = model(x, mask_x=torch.tensor([[4,5],[0,1],[2,3]]))
834
+ # out = model(x, mask_t=torch.tensor([0,1,4,5]))
835
+ print(out.shape)
836
+ # exit()
837
+
838
+
839
+ model2 = EEGTransformerPredictor(
840
+ num_patches=model.num_patches,
841
+ embed_dim=4,
842
+ predictor_embed_dim=4,
843
+ depth=2,
844
+ num_heads=1,
845
+ mlp_ratio=4.0,
846
+ drop_rate=0.0,
847
+ attn_drop_rate=0.0,
848
+ drop_path_rate=0.0,
849
+ init_std=0.02,
850
+ qkv_bias=True,
851
+ norm_layer=partial(nn.LayerNorm, eps=1e-6))
852
+
853
+ # a = model2(out, )
854
+ # print(a)
855
+ # out[0,1,0,0]=-1
856
+ # a = model2(out)
857
+ # print(a, a.shape)
858
+ a = model2(out, mask_x=torch.tensor([[4,5],[0,1],[2,3]]), mask_t=None)
859
+
860
+ model3 = EEGTransformerReconstructor(
861
+ num_patches=model.num_patches,
862
+ patch_size=2,
863
+ embed_dim=4,
864
+ reconstructor_embed_dim=4,
865
+ depth=2,
866
+ num_heads=1,
867
+ mlp_ratio=4.0,
868
+ drop_rate=0.0,
869
+ attn_drop_rate=0.0,
870
+ drop_path_rate=0.0,
871
+ init_std=0.02,
872
+ qkv_bias=True,
873
+ norm_layer=partial(nn.LayerNorm, eps=1e-6))
874
+
875
+ b = model3(a, mask_y=torch.tensor([6,7,8,9]))
876
+ print(b)
EEGFaceSem/EEGPT/modules/Network/__init__.py ADDED
File without changes
EEGFaceSem/EEGPT/modules/Network/utils.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ import torch
3
+ from torch.autograd import Function
4
+
5
+ class ReverseLayerF(Function):
6
+
7
+ @staticmethod
8
+ def forward(ctx, x, alpha):
9
+ ctx.alpha = alpha
10
+
11
+ return x.view_as(x)
12
+
13
+ @staticmethod
14
+ def backward(ctx, grad_output):
15
+ output = grad_output.neg() * ctx.alpha
16
+
17
+ return output, None
18
+
19
+ class Conv2dWithConstraint(nn.Conv2d):
20
+ '''
21
+ Lawhern V J, Solon A J, Waytowich N R, et al. EEGNet: a compact convolutional neural network for EEG-based brain–computer interfaces[J]. Journal of neural engineering, 2018, 15(5): 056013.
22
+ '''
23
+ def __init__(self, *args, doWeightNorm = True, max_norm=1, **kwargs):
24
+ self.max_norm = max_norm
25
+ self.doWeightNorm = doWeightNorm
26
+ super(Conv2dWithConstraint, self).__init__(*args, **kwargs)
27
+
28
+ def forward(self, x):
29
+ if self.doWeightNorm:
30
+ self.weight.data = torch.renorm(
31
+ self.weight.data, p=2, dim=0, maxnorm=self.max_norm
32
+ )
33
+ return super(Conv2dWithConstraint, self).forward(x)
34
+
35
+ class Conv1dWithConstraint(nn.Conv1d):
36
+ '''
37
+ Lawhern V J, Solon A J, Waytowich N R, et al. EEGNet: a compact convolutional neural network for EEG-based brain–computer interfaces[J]. Journal of neural engineering, 2018, 15(5): 056013.
38
+ '''
39
+ def __init__(self, *args, doWeightNorm = True, max_norm=1, **kwargs):
40
+ self.max_norm = max_norm
41
+ self.doWeightNorm = doWeightNorm
42
+ super(Conv1dWithConstraint, self).__init__(*args, **kwargs)
43
+
44
+ def forward(self, x):
45
+ if self.doWeightNorm:
46
+ self.weight.data = torch.renorm(
47
+ self.weight.data, p=2, dim=0, maxnorm=self.max_norm
48
+ )
49
+ return super(Conv1dWithConstraint, self).forward(x)
50
+
51
+ class LinearWithConstraint(nn.Linear):
52
+ def __init__(self, *args, doWeightNorm = True, max_norm=1, **kwargs):
53
+ self.max_norm = max_norm
54
+ self.doWeightNorm = doWeightNorm
55
+ super(LinearWithConstraint, self).__init__(*args, **kwargs)
56
+
57
+ def forward(self, x):
58
+ if self.doWeightNorm:
59
+ self.weight.data = torch.renorm(
60
+ self.weight.data, p=2, dim=0, maxnorm=self.max_norm
61
+ )
62
+ return super(LinearWithConstraint, self).forward(x)
63
+
64
+
65
+ def SMMDL_marginal(Cs,Ct):
66
+
67
+ '''
68
+ The SMMDL used in the CRGNet.
69
+ Arg:
70
+ Cs:The source input which shape is NxdXd.
71
+ Ct:The target input which shape is Nxdxd.
72
+ '''
73
+
74
+ Cs = torch.mean(Cs,dim=0)
75
+ Ct = torch.mean(Ct,dim=0)
76
+
77
+ # loss = torch.mean((Cs-Ct)**2)
78
+ loss = torch.mean(torch.mul((Cs-Ct), (Cs-Ct)))
79
+
80
+ return loss
81
+
82
+ def SMMDL_conditional(Cs,s_label,Ct,t_label):
83
+
84
+ '''
85
+ The Conditional SMMDL of the source and target data.
86
+ Arg:
87
+ Cs:The source input which shape is NxdXd.
88
+ s_label:The label of Cs data.
89
+ Ct:The target input which shape is Nxdxd.
90
+ t_label:The label of Ct data.
91
+ '''
92
+ s_label = s_label.reshape(-1)
93
+ t_label = t_label.reshape(-1)
94
+
95
+ class_unique = torch.unique(s_label)
96
+
97
+ class_num = len(class_unique)
98
+ all_loss = 0.0
99
+
100
+ for c in class_unique:
101
+ s_index = (s_label == c)
102
+ t_index = (t_label == c)
103
+ # print(t_index)
104
+ if torch.sum(t_index)==0:
105
+ class_num-=1
106
+ continue
107
+ c_Cs = Cs[s_index]
108
+ c_Ct = Ct[t_index]
109
+ m_Cs = torch.mean(c_Cs,dim = 0)
110
+ m_Ct = torch.mean(c_Ct,dim = 0)
111
+ loss = torch.mean((m_Cs-m_Ct)**2)
112
+ all_loss +=loss
113
+
114
+ if class_num == 0:
115
+ return 0
116
+
117
+ return all_loss/class_num
118
+
EEGFaceSem/EEGPT/modules/__init__.py ADDED
File without changes
EEGFaceSem/__init__.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EEGFaceSem - EEG Dataset for Semantic Visual Response
3
+
4
+ A Python package for the EEGFaceSem brain dataset from CVPR 2024.
5
+ """
6
+
7
+ __version__ = "0.1.0"
8
+
9
+ # ============================================================================
10
+ # TASK DEFINITIONS
11
+ # ============================================================================
12
+ # 8 binary classification tasks in order
13
+
14
+ ALL_TASKS = [
15
+ 'facecat/female', # 0
16
+ 'facecat/male', # 1
17
+ 'facecat/blond', # 2
18
+ 'facecat/darkhaired', # 3
19
+ 'facecat/smiles', # 4
20
+ 'facecat/nosmile', # 5
21
+ 'facecat/old', # 6
22
+ 'facecat/young', # 7
23
+ ]
24
+
25
+ TASK_NAMES = ['female', 'male', 'blond', 'darkhaired', 'smiles', 'nosmile', 'old', 'young']
26
+
27
+ def get_task_id(task):
28
+ """Convert task name or id to task_id."""
29
+ if isinstance(task, int):
30
+ return task
31
+ task_lower = task.lower()
32
+ if task_lower in TASK_NAMES:
33
+ return TASK_NAMES.index(task_lower)
34
+ # Try with prefix
35
+ for i, t in enumerate(ALL_TASKS):
36
+ if task_lower in t.lower():
37
+ return i
38
+ raise ValueError(f"Unknown task: {task}. Valid tasks: {TASK_NAMES}")
39
+
40
+ # ============================================================================
41
+ # CORE API
42
+ # ============================================================================
43
+
44
+ # Download functions
45
+ from .download import download, download_models, download_latents, get_data_dir
46
+
47
+ # Dataset loading - returns (X, Y, ids) tuple
48
+ from .utils import Dataset, load_from_processed, load_latent
49
+
50
+ # Benchmark
51
+ from .benchmark import benchmark
52
+
53
+ # Image generation
54
+ from .generation import generate
55
+
56
+
57
+ def load_data(data_dir=None, task=None, subjects=None, auto_download=True):
58
+ """
59
+ Load EEGFaceSem processed data.
60
+
61
+ Args:
62
+ data_dir: Path to data directory. Default: ~/.cache/EEGFaceSem
63
+ task: Task name ('female', 'male', etc.) or task_id (0-7). None for all.
64
+ subjects: List of subject IDs (1-30) to download. None = all subjects.
65
+ auto_download: Download data if not found. Default: True
66
+
67
+ Returns:
68
+ X: numpy array (n_trials, n_channels, n_timesteps) - EEG epochs
69
+ Y: numpy array (n_trials,) - Binary labels (0 or 1)
70
+ ids: numpy array (n_trials, 5) - [subject_id, task_id, trial_id, label, image_id]
71
+
72
+ Example:
73
+ >>> X, Y, ids = EEGFaceSem.load_data(task='female')
74
+ >>> X, Y, ids = EEGFaceSem.load_data(task='female', subjects=[1]) # One subject only
75
+ """
76
+ from pathlib import Path
77
+
78
+ if data_dir is None:
79
+ data_dir = get_data_dir()
80
+ data_dir = Path(data_dir)
81
+
82
+ # Auto-download if needed
83
+ processed_dir = data_dir / "data" / "processed"
84
+ if auto_download and not processed_dir.exists():
85
+ download(data_dir=data_dir, data_type="processed", subjects=subjects)
86
+
87
+ # Convert task name to full path if needed
88
+ task_full = None
89
+ if task is not None:
90
+ task_id = get_task_id(task)
91
+ task_full = ALL_TASKS[task_id]
92
+
93
+ # Load dataset
94
+ dataset = Dataset(str(processed_dir), cache=True, task=task_full)
95
+
96
+ # Reshape X to (n_trials, n_channels, n_timesteps)
97
+ X = dataset.X.reshape(dataset.X.shape[0], 32, -1)
98
+ Y = dataset.Y
99
+ ids = dataset.ids
100
+
101
+ return X, Y, ids
102
+
103
+
104
+ # ============================================================================
105
+ # CONVENIENCE FUNCTIONS
106
+ # ============================================================================
107
+
108
+ def get_subjects(ids):
109
+ """Get unique subject IDs from ids array."""
110
+ import numpy as np
111
+ return np.unique(ids[:, 0])
112
+
113
+
114
+ def split_by_subject(X, Y, ids, test_subject):
115
+ """
116
+ Split data by subject for leave-one-subject-out cross-validation.
117
+
118
+ Returns:
119
+ (X_train, Y_train), (X_test, Y_test)
120
+ """
121
+ import numpy as np
122
+ test_mask = ids[:, 0] == test_subject
123
+ train_mask = ~test_mask
124
+
125
+ return (X[train_mask], Y[train_mask]), (X[test_mask], Y[test_mask])
126
+
127
+
128
+ def split_random(X, Y, test_size=0.2, random_state=42):
129
+ """
130
+ Random train/test split.
131
+
132
+ Returns:
133
+ (X_train, Y_train), (X_test, Y_test)
134
+ """
135
+ import numpy as np
136
+ np.random.seed(random_state)
137
+ n = len(X)
138
+ indices = np.random.permutation(n)
139
+ test_n = int(n * test_size)
140
+
141
+ test_idx = indices[:test_n]
142
+ train_idx = indices[test_n:]
143
+
144
+ return (X[train_idx], Y[train_idx]), (X[test_idx], Y[test_idx])
EEGFaceSem/benchmark.py ADDED
@@ -0,0 +1,300 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # benchmark.py
2
+ import argparse
3
+ import logging
4
+ import sys
5
+ import os
6
+ import pickle
7
+ import numpy as np
8
+ from sklearn.model_selection import KFold
9
+ from sklearn.metrics import accuracy_score, roc_auc_score, f1_score
10
+ from copy import deepcopy
11
+
12
+ # --- Import all models ---
13
+ from .models import (
14
+ BaseModel,
15
+ LDAModel,
16
+ LRModel,
17
+ MLPModel,
18
+ EEGNetModel,
19
+ EEGPTLinear
20
+ )
21
+ from .download import get_data_dir
22
+
23
+ # --- Constants ---
24
+
25
+ all_tasks = ['facecat/female', 'facecat/male', 'facecat/blond', 'facecat/darkhaired', 'facecat/smiles', 'facecat/nosmile', 'facecat/old', 'facecat/young']
26
+
27
+ def get_default_data_path():
28
+ """Get default data path from package cache or current directory."""
29
+ data_dir = get_data_dir()
30
+ processed = data_dir / "data" / "processed"
31
+ if processed.exists():
32
+ return str(processed)
33
+ return './data/processed/'
34
+ # N_SUBJECTS = 30
35
+ N_TASKS = len(all_tasks)
36
+ # TRIALS_PER_TASK_SUBJECT = 280
37
+ # TOTAL_TRIALS = N_SUBJECTS * N_TASKS * TRIALS_PER_TASK_SUBJECT # 67200
38
+ N_CHANNELS = 32 # 32 channels
39
+ N_TIMESTEPS = 1101 # 1101 time points [-0.2, 0.9]s with 1000Hz sampling rate
40
+
41
+ # --- 1. Data Loading ---
42
+
43
+ from .utils import Dataset
44
+ def load_data(task_id=-1, data_path='./data/processed/'):
45
+ """
46
+ Dataset loader will return:
47
+ X: (n_trials, n_channels, n_timesteps) - The epoch data.
48
+ Y_binary: (n_trials,) - The binary label (0 or 1).
49
+ ids: (n_trials, 5) - Metadata array:
50
+ [subject_idx, task_idx, trial_idx, label, image_idx]
51
+ """
52
+ print(f"--- Loading task_id={task_id} ---")
53
+ # Z, Y, D = load_from_processed(data_path, cache=True)
54
+ if task_id == -1:
55
+ task = None
56
+ else:
57
+ task = all_tasks[task_id]
58
+ dataset = Dataset(data_path, cache=True, chs=N_CHANNELS, samples=N_TIMESTEPS, task=task)
59
+ return dataset.X, dataset.Y, dataset.ids
60
+
61
+ # --- 2. Logging Setup ---
62
+
63
+ def setup_logging(log_file):
64
+ """Configures logging to both file and console."""
65
+ for handler in logging.root.handlers[:]:
66
+ logging.root.removeHandler(handler)
67
+
68
+ format='[%(asctime)s %(levelname)-8s %(thread)-6d %(filename)s:%(lineno)d]: %(message)s'
69
+ logging.basicConfig(
70
+ level=logging.INFO,
71
+ format=format,
72
+ handlers=[
73
+ logging.FileHandler(log_file, mode='a'),
74
+ logging.StreamHandler(sys.stdout)
75
+ ]
76
+ )
77
+ return logging.getLogger()
78
+
79
+ # --- 3. Helper Functions ---
80
+
81
+ def initialize_model(args, n_classes, input_shape):
82
+ """Factory function to create the model instance."""
83
+
84
+ model_kwargs = {
85
+ 'lr': args.lr,
86
+ 'batch_size': args.batch_size,
87
+ 'epochs': args.epochs
88
+ }
89
+
90
+ if args.model == 'LDA':
91
+ model_class = LDAModel
92
+ elif args.model == 'LR':
93
+ model_class = LRModel
94
+ elif args.model == 'MLP':
95
+ model_class = MLPModel
96
+ elif args.model == 'EEGNet':
97
+ model_class = EEGNetModel
98
+ elif args.model == 'EEGPT':
99
+ model_kwargs['eegpt_load_path'] = args.eegpt_load_path
100
+ model_class = EEGPTLinear
101
+ else:
102
+ raise ValueError(f"Unknown model type: {args.model}")
103
+ return model_class(n_classes=n_classes, input_shape=input_shape, **model_kwargs)
104
+
105
+ def evaluate_predictions(Y_test, Y_prob, n_classes=2):
106
+ """Calculates accuracy and AUC from probabilities."""
107
+ if n_classes == 2:
108
+ Y_pred = (Y_prob[:, 1] > 0.5).astype(int)
109
+ try:
110
+ auc = roc_auc_score(Y_test, Y_prob[:, 1])
111
+ except ValueError:
112
+ auc = 0.5 # Handle case where only one class is present
113
+ f1 = f1_score(Y_test, Y_pred, average='macro')
114
+ else:
115
+ Y_pred = np.argmax(Y_prob, axis=1)
116
+ try:
117
+ auc = roc_auc_score(Y_test, Y_prob, multi_class='ovr')
118
+ except ValueError:
119
+ auc = 0.5
120
+ f1 = f1_score(Y_test, Y_pred, average='macro')
121
+
122
+ acc = accuracy_score(Y_test, Y_pred)
123
+ return acc, auc, f1
124
+
125
+ # --- 4. Core Experiment Logic ---
126
+
127
+ def run_experiment(args, logger):
128
+ logger.info(f"--- New Job Started --- \nArgs: {vars(args)}")
129
+
130
+ # --- 4.1. Load Data ---
131
+ X, Y_binary, ids = load_data(task_id=args.task_id, data_path=args.data_path)
132
+ logger.info(f"Loaded data with shapes: X:{X.shape}, Y:{Y_binary.shape}, ids:{ids.shape}")
133
+ X = X.reshape(X.shape[0], -1)
134
+
135
+ input_shape = (N_CHANNELS, N_TIMESTEPS) # (n_channels, n_timesteps)
136
+
137
+ # --- 4.2. Define Task Labels ---
138
+ if args.experiment == 'relevance':
139
+ Y = Y_binary
140
+ n_classes = 2
141
+ elif args.experiment == 'task':
142
+ Y = ids[:, 1] # task_idx (0-7)
143
+ n_classes = N_TASKS
144
+ elif args.experiment == 'joint':
145
+ Y = ids[:, 1] * 2 + Y_binary # 16-class (0-15)
146
+ n_classes = N_TASKS * 2
147
+ else:
148
+ logger.error(f"Unknown experiment type: {args.experiment}"); return
149
+
150
+ # --- 4.3. Execute Strategy ---
151
+
152
+ subject_ids = np.unique(ids[:, 0])
153
+ results = {}
154
+ if args.strategy == 'single_subject':
155
+ for subject_id in subject_ids:
156
+ logger.info(f"Running Subject-Specific ({args.k_folds}-fold CV) for subject: {subject_id}")
157
+ subject_mask = (ids[:, 0] == subject_id)
158
+ X_subject, Y_subject, ids_subject = X[subject_mask], Y[subject_mask], ids[subject_mask]
159
+
160
+ kf = KFold(n_splits=args.k_folds, shuffle=True, random_state=42)
161
+
162
+ for fold, (train_idx, test_idx) in enumerate(kf.split(X_subject)):
163
+ # Get fold data
164
+ X_train, Y_train = X_subject[train_idx], Y_subject[train_idx]
165
+ X_test, Y_test, ids_test = X_subject[test_idx], Y_subject[test_idx], ids_subject[test_idx]
166
+
167
+ # # Create validation split from training data
168
+ # val_split_size = max(1, int(0.15 * len(X_train_valid)))
169
+ # ids = np.arange(len(X_train_valid))
170
+ # np.random.shuffle(ids)
171
+ # X_train, Y_train = X_train_valid[ids[val_split_size:]], Y_train_valid[ids[val_split_size:]]
172
+ # X_valid, Y_valid = X_train_valid[ids[:val_split_size]], Y_train_valid[ids[:val_split_size]]
173
+
174
+ try:
175
+ # Initialize a new model for each fold
176
+ model = initialize_model(args, n_classes, input_shape)
177
+ model.fit(X_train, Y_train)
178
+
179
+ y_prob = model.predict_proba(X_test)
180
+ acc, auc, f1 = evaluate_predictions(Y_test, y_prob, n_classes)
181
+ results[(subject_id, fold)] = (y_prob, test_idx, ids_test, (acc, auc, f1))
182
+
183
+ logger.info(f"RESULT, exp:{args.experiment}, strat:{args.strategy}, task_id:{args.task_id}, subject:{subject_id}, fold:{fold}, model:{args.model}, acc:{acc:.4f}, auc:{auc:.4f}, f1:{f1:.4f}")
184
+ except Exception as e:
185
+ logger.error(f"Failed exp:{args.experiment}, strat:{args.strategy}, task_id:{args.task_id}, subject:{subject_id}, fold:{fold}, model:{args.model}: {e}", exc_info=True)
186
+ elif args.strategy == 'cross_subject' or args.strategy == 'subject_adapted':
187
+ for test_subject_id in subject_ids:
188
+ if args.k_folds == -1:
189
+ args.k_folds = 1
190
+ args.fold = 0
191
+ if test_subject_id % args.k_folds != args.fold:
192
+ continue
193
+ logger.info(f"Running Subject-Independent (LOSO) for test subject: {test_subject_id}")
194
+
195
+ test_mask = (ids[:, 0] == test_subject_id)
196
+ train_mask = (ids[:, 0] != test_subject_id)
197
+
198
+ X_train, Y_train = X[train_mask], Y[train_mask]
199
+ X_test, Y_test, ids_test = X[test_mask], Y[test_mask], ids[test_mask]
200
+
201
+ try:
202
+ model = initialize_model(args, n_classes, input_shape)
203
+ model.fit(X_train, Y_train)
204
+
205
+ y_prob = model.predict_proba(X_test)
206
+ acc, auc, f1 = evaluate_predictions(Y_test, y_prob, n_classes)
207
+ if args.strategy == 'cross_subject':
208
+ results[test_subject_id] = (y_prob, test_mask, ids_test, (acc, auc, f1))
209
+
210
+ logger.info(f"RESULT, exp:{args.experiment}, strat:{args.strategy}, task_id:{args.task_id}, subject:{test_subject_id}, model:{args.model}, acc:{acc:.4f}, auc:{auc:.4f}, f1:{f1:.4f}")
211
+ except Exception as e:
212
+ logger.error(f"Failed exp:{args.experiment}, strat:{args.strategy}, task_id:{args.task_id}, subject:{test_subject_id}, model:{args.model}: {e}", exc_info=True)
213
+
214
+ if args.strategy == 'subject_adapted':
215
+ kf = KFold(n_splits=args.k_folds, shuffle=True, random_state=42)
216
+ X_subject, Y_subject, ids_subject = X[test_mask], Y[test_mask], ids[test_mask]
217
+ for fold, (train_idx, test_idx) in enumerate(kf.split(X_test)):
218
+ # Get fold data
219
+ X_ft_train, Y_ft_train = X_subject[train_idx], Y_subject[train_idx]
220
+ X_ft_test, Y_ft_test, ids_ft_test = X_subject[test_idx], Y_subject[test_idx], ids_subject[test_idx]
221
+
222
+ try:
223
+ ft_model = initialize_model(args, n_classes, input_shape)
224
+ ft_model.copy_from(model)
225
+ ft_model.fit(X_ft_train, Y_ft_train)
226
+
227
+ y_prob = ft_model.predict_proba(X_ft_test)
228
+ acc, auc, f1 = evaluate_predictions(Y_ft_test, y_prob, n_classes)
229
+ results[(test_subject_id, fold)] = (y_prob, test_idx, ids_ft_test, (acc, auc, f1))
230
+ logger.info(f"RESULT, exp:{args.experiment}, strat:{args.strategy}, task_id:{args.task_id}, subject:{test_subject_id}, fold:{fold}, model:{args.model}, acc:{acc:.4f}, auc:{auc:.4f}, f1:{f1:.4f}")
231
+
232
+ except Exception as e:
233
+ logger.error(f"Failed exp:{args.experiment}, strat:{args.strategy}, task_id:{args.task_id}, subject:{test_subject_id}, fold:{fold}, model:{args.model}: {e}", exc_info=True)
234
+ continue
235
+
236
+
237
+ os.makedirs(f'./results/', exist_ok=True)
238
+ pickle.dump(results, open(f'./results/results_{args.prefix}_{args.experiment}_{args.strategy}_{args.model}_task{args.task_id}_fold{args.fold}.pkl', 'wb'))
239
+ # summarize results
240
+ metrics = np.array([v[3] for v in results.values()])
241
+ if args.strategy == 'single_subject':
242
+ metrics = metrics.reshape(-1, args.k_folds, 3)
243
+ metrics = np.mean(metrics, axis=1)
244
+ mean_acc, mean_auc, mean_f1 = np.mean(metrics, axis=0)
245
+ std_acc, std_auc, std_f1 = np.std(metrics, axis=0)
246
+ logger.info(f"SUMMARY, exp:{args.experiment}, strat:{args.strategy}, task_id:{args.task_id}, model:{args.model}, acc:{mean_acc:.4f} +/- {std_acc:.4f}, auc:{mean_auc:.4f} +/- {std_auc:.4f}, f1:{mean_f1:.4f} +/- {std_f1:.4f}")
247
+ logger.info(f"--- Job Finished ---")
248
+
249
+ def get_args():
250
+ parser = argparse.ArgumentParser(description="Run EEG Dataset Benchmark Experiments")
251
+
252
+ # --- Experiment Selection ---
253
+ parser.add_argument('--experiment', type=str, default='relevance',
254
+ choices=['relevance', 'task', 'joint'],
255
+ help="The benchmark task to run.")
256
+
257
+ parser.add_argument('--strategy', type=str, default='single_subject',
258
+ choices=['single_subject', 'cross_subject', 'subject_adapted'],
259
+ help="The training strategy to use.")
260
+
261
+ parser.add_argument('--model', type=str, default='LDA', choices=['LDA', 'LR', 'MLP', 'EEGNet', 'EEGPT'], help="The classifier model to evaluate.")
262
+
263
+ # --- Configuration ---
264
+ parser.add_argument("--prefix", type=str, default="", help="dir_prefix")
265
+ parser.add_argument('--task_id', type=int, default=-1, help="Task ID (0-7) to run. Or -1 for all tasks combined.")
266
+ parser.add_argument('--k_folds', type=int, default=-1, help="Number of folds for cross-validation. ")
267
+ parser.add_argument('--fold', type=int, default=-1, help="index of fold for cross-validation.")
268
+ parser.add_argument('--data_path', type=str, default=None, help="Path to the preprocessed dataset. Default: auto-detect.")
269
+ parser.add_argument('--epochs', type=int, default=100, help="Max epochs.")
270
+ parser.add_argument('--batch_size', type=int, default=32, help="Batch size.")
271
+ parser.add_argument('--lr', type=float, default=0.001, help="Learning rate.")
272
+ parser.add_argument('--eegpt_load_path', type=str, default='models/eegpt_mcae_58chs_4s_large4E.ckpt', help="Path to the pre-trained EEGPT checkpoint.")
273
+
274
+ args = parser.parse_args()
275
+ return args
276
+
277
+ def benchmark(model, **kwargs):
278
+ args = get_args()
279
+ args.model = model
280
+ for k, v in kwargs.items():
281
+ setattr(args, k, v)
282
+ # Use default data path if not specified
283
+ if args.data_path is None:
284
+ args.data_path = get_default_data_path()
285
+ os.makedirs(f'./logs/', exist_ok=True)
286
+ logger = setup_logging(f'./logs/log_{args.prefix}_{args.experiment}_{args.strategy}_{args.model}.log')
287
+ run_experiment(args, logger)
288
+
289
+ if __name__ == "__main__":
290
+ args = get_args()
291
+
292
+ # --- Setup and Run ---
293
+ os.makedirs('./logs/', exist_ok=True)
294
+ log_file = f'./logs/log_{args.prefix}_{args.experiment}_{args.strategy}_{args.model}.log'
295
+ logger = setup_logging(log_file)
296
+
297
+ if args.strategy == 'subject_adapted' and args.model in ['LDA', 'LR']:
298
+ logger.warning(f"Subject adaption not supported for {args.model}. Skipping.")
299
+ else:
300
+ run_experiment(args, logger)
EEGFaceSem/download.py ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Download EEGFaceSem data from HuggingFace.
3
+ """
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ REPO_ID = "yefllower/EEGFaceSem"
9
+ DEFAULT_DATA_DIR = Path.home() / ".cache" / "EEGFaceSem"
10
+
11
+
12
+ def get_data_dir(data_dir=None):
13
+ """Get the data directory, creating if needed."""
14
+ if data_dir is None:
15
+ data_dir = DEFAULT_DATA_DIR
16
+ data_dir = Path(data_dir)
17
+ data_dir.mkdir(parents=True, exist_ok=True)
18
+ return data_dir
19
+
20
+
21
+ def is_downloaded(data_dir, data_type="processed"):
22
+ """Check if data is already downloaded."""
23
+ data_dir = Path(data_dir)
24
+ if data_type == "raw":
25
+ # Check for at least one raw file
26
+ return (data_dir / "data" / "raw" / "01.vhdr").exists()
27
+ else: # processed
28
+ return (data_dir / "data" / "processed" / "01-epo.fif").exists()
29
+
30
+
31
+ def download(data_dir=None, data_type="processed", subjects=None, force=False):
32
+ """
33
+ Download EEGFaceSem data from HuggingFace.
34
+
35
+ Args:
36
+ data_dir: Where to save data. Default: ~/.cache/EEGFaceSem
37
+ data_type: "raw", "processed", or "both". Default: "processed"
38
+ subjects: List of subject IDs (1-30) to download. None = all subjects.
39
+ Example: subjects=[1] downloads only subject 01.
40
+ force: Re-download even if files exist. Default: False
41
+
42
+ Returns:
43
+ Path to the data directory
44
+
45
+ Example:
46
+ >>> import EEGFaceSem
47
+ >>> EEGFaceSem.download() # Downloads all processed data
48
+ >>> EEGFaceSem.download(subjects=[1, 2]) # Only subjects 01 and 02
49
+ """
50
+ try:
51
+ from huggingface_hub import snapshot_download
52
+ except ImportError:
53
+ raise ImportError(
54
+ "huggingface_hub is required for downloading. "
55
+ "Install with: pip install huggingface_hub"
56
+ )
57
+
58
+ data_dir = get_data_dir(data_dir)
59
+
60
+ # Check if already downloaded (only if downloading all subjects)
61
+ if subjects is None and not force and is_downloaded(data_dir, data_type):
62
+ print(f"Data already exists at {data_dir}. Use force=True to re-download.")
63
+ return data_dir
64
+
65
+ # Build patterns for which files to download
66
+ allow_patterns = []
67
+
68
+ # If specific subjects requested, build patterns for those subjects
69
+ if subjects is not None:
70
+ subject_patterns = [f"{s:02d}" for s in subjects]
71
+
72
+ if data_type in ["raw", "both"]:
73
+ for sp in subject_patterns:
74
+ allow_patterns.extend([
75
+ f"data/raw/{sp}.eeg",
76
+ f"data/raw/{sp}.vhdr",
77
+ f"data/raw/{sp}.vmrk"
78
+ ])
79
+
80
+ if data_type in ["processed", "both"]:
81
+ for sp in subject_patterns:
82
+ allow_patterns.extend([
83
+ f"data/processed/{sp}-epo.fif",
84
+ f"data/processed/{sp}-ev2img.pkl"
85
+ ])
86
+
87
+ print(f"Downloading EEGFaceSem {data_type} data for subjects {subjects}...")
88
+ else:
89
+ # Download all subjects
90
+ if data_type in ["raw", "both"]:
91
+ allow_patterns.extend([
92
+ "data/raw/*.eeg",
93
+ "data/raw/*.vhdr",
94
+ "data/raw/*.vmrk"
95
+ ])
96
+
97
+ if data_type in ["processed", "both"]:
98
+ allow_patterns.extend([
99
+ "data/processed/*-epo.fif",
100
+ "data/processed/*-ev2img.pkl"
101
+ ])
102
+
103
+ print(f"Downloading EEGFaceSem {data_type} data (all subjects)...")
104
+
105
+ print(f"Destination: {data_dir}")
106
+
107
+ snapshot_download(
108
+ repo_id=REPO_ID,
109
+ repo_type="dataset",
110
+ local_dir=str(data_dir),
111
+ allow_patterns=allow_patterns,
112
+ )
113
+
114
+ print(f"Download complete! Data saved to: {data_dir}")
115
+ return data_dir
116
+
117
+
118
+ def download_models(data_dir=None, force=False):
119
+ """
120
+ Download pretrained models (Progressive GAN, EEGPT) from HuggingFace.
121
+
122
+ Args:
123
+ data_dir: Where to save models. Default: ~/.cache/EEGFaceSem
124
+ force: Re-download even if files exist.
125
+
126
+ Returns:
127
+ Path to the models directory
128
+ """
129
+ try:
130
+ from huggingface_hub import snapshot_download
131
+ except ImportError:
132
+ raise ImportError(
133
+ "huggingface_hub is required. Install with: pip install huggingface_hub"
134
+ )
135
+
136
+ data_dir = get_data_dir(data_dir)
137
+ models_dir = data_dir / "models"
138
+
139
+ # Check if already downloaded
140
+ if not force and (models_dir / "karras2018iclr-celebahq-1024x1024.pkl").exists():
141
+ print(f"Models already exist at {models_dir}. Use force=True to re-download.")
142
+ return models_dir
143
+
144
+ print("Downloading pretrained models from HuggingFace...")
145
+
146
+ snapshot_download(
147
+ repo_id=REPO_ID,
148
+ repo_type="dataset",
149
+ local_dir=str(data_dir),
150
+ allow_patterns=["models/*"],
151
+ )
152
+
153
+ print(f"Models saved to: {models_dir}")
154
+ return models_dir
155
+
156
+
157
+ def download_latents(data_dir=None, force=False):
158
+ """
159
+ Download latent vectors for stimulus images from HuggingFace.
160
+
161
+ Args:
162
+ data_dir: Where to save. Default: ~/.cache/EEGFaceSem
163
+ force: Re-download even if files exist.
164
+
165
+ Returns:
166
+ Path to the latents directory
167
+ """
168
+ try:
169
+ from huggingface_hub import snapshot_download
170
+ except ImportError:
171
+ raise ImportError(
172
+ "huggingface_hub is required. Install with: pip install huggingface_hub"
173
+ )
174
+
175
+ data_dir = get_data_dir(data_dir)
176
+ latents_dir = data_dir / "data" / "latents"
177
+
178
+ # Check if already downloaded
179
+ if not force and (latents_dir / "latent.pkl").exists():
180
+ print(f"Latents already exist at {latents_dir}. Use force=True to re-download.")
181
+ return latents_dir
182
+
183
+ print("Downloading latent vectors from HuggingFace...")
184
+
185
+ snapshot_download(
186
+ repo_id=REPO_ID,
187
+ repo_type="dataset",
188
+ local_dir=str(data_dir),
189
+ allow_patterns=["data/latents/*"],
190
+ )
191
+
192
+ print(f"Latents saved to: {latents_dir}")
193
+ return latents_dir
194
+
195
+
196
+ if __name__ == "__main__":
197
+ # Quick test
198
+ import argparse
199
+ parser = argparse.ArgumentParser()
200
+ parser.add_argument("--data_dir", default=None)
201
+ parser.add_argument("--type", default="processed", choices=["raw", "processed", "both"])
202
+ parser.add_argument("--force", action="store_true")
203
+ args = parser.parse_args()
204
+
205
+ download(data_dir=args.data_dir, data_type=args.type, force=args.force)
EEGFaceSem/generation.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import pickle
4
+ import numpy as np
5
+ import PIL.Image
6
+
7
+ # --- Globals ---
8
+ _G = None
9
+ _D = None
10
+ _Gs = None
11
+
12
+ def load_pgan_model(model_path):
13
+ """
14
+ Loads the pretrained Progressive GAN model from a pickle file.
15
+
16
+ This function temporarily modifies sys.path to allow the pickle file
17
+ to find its required modules (networks, legacy, etc.) which are
18
+ encapsulated inside the .pgan submodule.
19
+ """
20
+ global _G, _D, _Gs
21
+ if _Gs is not None:
22
+ return _G, _D, _Gs
23
+
24
+ pgan_dir = os.path.dirname(os.path.abspath(__file__)) + '/pgan'
25
+
26
+ # Temporarily add the pgan directory to sys.path
27
+ need_to_remove = False
28
+ if pgan_dir not in sys.path:
29
+ sys.path.insert(0, pgan_dir)
30
+ need_to_remove = True
31
+
32
+ try:
33
+ print("Loading Progressive GAN model...")
34
+ import tensorflow.compat.v1 as tf
35
+ tf.disable_v2_behavior()
36
+ # tf.InteractiveSession()
37
+ sess = tf.compat.v1.InteractiveSession()
38
+ _G, _D, _Gs = pickle.load(open(model_path, 'rb'))
39
+ finally:
40
+ # Always remove the path modification, even if an error occurs.
41
+ if pgan_dir in sys.path and need_to_remove:
42
+ sys.path.remove(pgan_dir)
43
+
44
+ return _G, _D, _Gs
45
+
46
+ def generate_images(latent_vectors, Gs_model, batch_size=10):
47
+ """Generates images from a batch of latent vectors."""
48
+ imgs = []
49
+ for i in range(0, latent_vectors.shape[0], batch_size):
50
+ batch_vectors = latent_vectors[i:i+batch_size]
51
+ labels = np.zeros([batch_vectors.shape[0]] + Gs_model.input_shapes[1][1:])
52
+
53
+ images = Gs_model.run(batch_vectors, labels)
54
+ images = np.clip(np.rint((images + 1.0) / 2.0 * 255.0), 0.0, 255.0).astype(np.uint8)
55
+ images = images.transpose(0, 2, 3, 1) # NCHW => NHWC
56
+
57
+ imgs.extend([PIL.Image.fromarray(img) for img in images])
58
+ return imgs
59
+
60
+ def generate_image(latent_vector, Gs_model):
61
+ """Generates a single image from a 512-dimensional latent vector."""
62
+ if latent_vector.ndim == 1:
63
+ latent_vector = np.expand_dims(latent_vector, axis=0)
64
+ images = generate_images(latent_vector, Gs_model, batch_size=1)
65
+ return images[0]
66
+
67
+ def generate(vector, model_path=None):
68
+ """
69
+ Generate face images from latent vectors using Progressive GAN.
70
+
71
+ Args:
72
+ vector: numpy array of shape (n, 512) or (512,) for single image
73
+ model_path: Path to PGAN model. Default: auto-detect from package.
74
+
75
+ Returns:
76
+ List of PIL.Image objects
77
+ """
78
+ if model_path is None:
79
+ # Try to find model in package cache
80
+ from .download import get_data_dir
81
+ data_dir = get_data_dir()
82
+ model_path = data_dir / 'models' / 'karras2018iclr-celebahq-1024x1024.pkl'
83
+ if not model_path.exists():
84
+ # Try local path
85
+ model_path = 'models/karras2018iclr-celebahq-1024x1024.pkl'
86
+
87
+ _, _, Gs = load_pgan_model(str(model_path))
88
+ if vector.ndim == 1:
89
+ vector = np.expand_dims(vector, axis=0)
90
+ images = generate_images(vector, Gs, batch_size=1)
91
+ return images
92
+
93
+ if __name__ == "__main__":
94
+ # Example of how to use the generation functions as a script.
95
+ model_file = 'models/karras2018iclr-celebahq-1024x1024.pkl'
96
+ _, _, Gs = load_pgan_model(model_file)
97
+
98
+ random_vector = np.random.randn(1, 512)
99
+ image = generate_image(random_vector, Gs)
100
+
101
+ output_path = "generated_sample_from_package.png"
102
+ image.save(output_path)
103
+ print(f"Image saved to {output_path}")
104
+
105
+ random_vector = np.random.randn(4, 512)
106
+ images = generate_images(random_vector, Gs)
107
+ for i, img in enumerate(images):
108
+ output_path = f"generated_sample_from_package_{i}.png"
109
+ img.save(output_path)
110
+ print(f"Image {i} saved to {output_path}")
111
+
112
+
EEGFaceSem/models.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # models.py
2
+ import numpy as np
3
+ from abc import ABC, abstractmethod
4
+
5
+ # --- Sklearn Imports ---
6
+ from sklearn.preprocessing import StandardScaler
7
+ from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
8
+ from sklearn.linear_model import LogisticRegression
9
+ from sklearn.decomposition import PCA
10
+
11
+ # --- 1. Abstract Base Class ---
12
+
13
+ class BaseModel(ABC):
14
+ """
15
+ Abstract Base Class for all benchmark models.
16
+ It ensures that every model has a .fit() and .predict_proba() method,
17
+ allowing the main benchmark script to treat all models polymorphically.
18
+ """
19
+ def __init__(self, n_classes, input_shape, **kwargs):
20
+ """
21
+ Initialize the model.
22
+ :param n_classes: Number of output classes (e.g., 2 for binary, 8 for task-ID).
23
+ :param input_shape: Shape of a single sample, e.g., (n_channels, n_timesteps).
24
+ :param kwargs: Model-specific hyperparameters (e.g., lr, batch_size, C).
25
+ """
26
+ self.n_classes = n_classes
27
+ self.input_shape = input_shape # e.g., (32, 500)
28
+ self.n_chans, self.n_samples = self.input_shape
29
+ self.model = None
30
+ self.kwargs = kwargs # Store all other hyperparams
31
+ self.scaler = None # For models that need scaling
32
+
33
+ @abstractmethod
34
+ def fit(self, X_train, Y_train):
35
+ """
36
+ Train the model.
37
+ :param X_train: (n_samples, n_channels, n_timesteps)
38
+ :param Y_train: (n_samples,) - integer labels
39
+ """
40
+ pass
41
+
42
+ @abstractmethod
43
+ def predict_proba(self, X_test):
44
+ """
45
+ Get class probabilities for test data.
46
+ :param X_test: (n_test_samples, n_channels, n_timesteps)
47
+ :return: (n_test_samples, n_classes) array of probabilities.
48
+ """
49
+ pass
50
+
51
+ @abstractmethod
52
+ def get_model_name(self):
53
+ """Return a string name for logging."""
54
+ pass
55
+
56
+ @abstractmethod
57
+ def copy_from(self, other_model):
58
+ """Copy weights from another model."""
59
+ pass
60
+
61
+ @staticmethod
62
+ def validation_split(X, Y, val_size=0.15):
63
+ """Split data into train and validation sets."""
64
+ val_split_size = max(1, int(val_size * len(X)))
65
+ ids = np.arange(len(X))
66
+ np.random.shuffle(ids)
67
+ X_train, Y_train = X[ids[val_split_size:]], Y[ids[val_split_size:]]
68
+ X_valid, Y_valid = X[ids[:val_split_size]], Y[ids[:val_split_size]]
69
+ return X_train, Y_train, X_valid, Y_valid
70
+
71
+
72
+ # --- 2. Sklearn Model Implementations ---
73
+
74
+ class LDAModel(BaseModel):
75
+ """Linear Discriminant Analysis Implementation"""
76
+
77
+ def fit(self, X_train, Y_train):
78
+ # 1. Flatten data
79
+ n_samples = X_train.shape[0]
80
+ X_train_flat = X_train.reshape(n_samples, -1)
81
+
82
+ # 2. Scale data
83
+ self.scaler = StandardScaler()
84
+ X_train_scaled = self.scaler.fit_transform(X_train_flat)
85
+
86
+ # 3. Fit model
87
+ self.model = LinearDiscriminantAnalysis()
88
+ self.model.fit(X_train_scaled, Y_train) # Y_train is (n_samples,)
89
+
90
+ def predict_proba(self, X_test):
91
+ # 1. Flatten
92
+ n_samples = X_test.shape[0]
93
+ X_test_flat = X_test.reshape(n_samples, -1)
94
+
95
+ # 2. Scale
96
+ X_test_scaled = self.scaler.transform(X_test_flat)
97
+
98
+ # 3. Predict
99
+ probs = self.model.predict_proba(X_test_scaled)
100
+
101
+ # Handle binary case where sklearn returns (n, 1)
102
+ if self.n_classes == 2 and probs.shape[1] == 1:
103
+ probs = np.hstack([1 - probs, probs])
104
+ return probs
105
+
106
+ def get_model_name(self):
107
+ return "LDA"
108
+
109
+ def copy_from(self, other_model):
110
+ self.model = other_model.model
111
+ self.scaler = other_model.scaler
112
+
113
+ class LRModel(BaseModel):
114
+ """Logistic Regression Implementation"""
115
+
116
+ def fit(self, X_train, Y_train):
117
+ n_samples = X_train.shape[0]
118
+ X_train_flat = X_train.reshape(n_samples, -1)
119
+
120
+ self.scaler = StandardScaler()
121
+ X_train_scaled = self.scaler.fit_transform(X_train_flat)
122
+
123
+ self.pca = PCA(n_components=0.95, svd_solver='auto', random_state=42)
124
+ X_train_pca = self.pca.fit_transform(X_train_scaled)
125
+
126
+ self.model = LogisticRegression(C=self.kwargs.get('C', 1.0), solver='lbfgs', max_iter=1000, random_state=42)
127
+ self.model.fit(X_train_pca, Y_train)
128
+
129
+ def predict_proba(self, X_test):
130
+ n_samples = X_test.shape[0]
131
+ X_test_flat = X_test.reshape(n_samples, -1)
132
+ X_test_scaled = self.scaler.transform(X_test_flat)
133
+ X_test_pca = self.pca.transform(X_test_scaled)
134
+ return self.model.predict_proba(X_test_pca)
135
+
136
+ def get_model_name(self):
137
+ return "LogisticRegression"
138
+
139
+ def copy_from(self, other_model):
140
+ self.model = other_model.model
141
+ self.pca = other_model.pca
142
+ self.scaler = other_model.scaler
143
+
144
+ # --- 3. Deep Learning Model Implementations ---
145
+
146
+ class MLPModel(BaseModel):
147
+ """Simple Multi-Layer Perceptron (MLP) Implementation"""
148
+
149
+ def __init__(self, n_classes, input_shape, **kwargs):
150
+ import tensorflow as tf
151
+ from tensorflow.keras.models import Sequential
152
+ from tensorflow.keras.layers import Dense, Dropout, Input
153
+ super().__init__(n_classes, input_shape, **kwargs)
154
+ self.scaler = StandardScaler()
155
+ self.lr = kwargs.get('lr', 0.001)
156
+ self.batch_size = kwargs.get('batch_size', 32)
157
+ self.epochs = kwargs.get('epochs', 100)
158
+ flat_shape = np.prod(self.input_shape)
159
+
160
+ self.model = Sequential([
161
+ Input(shape=(flat_shape,)),
162
+ Dense(128, activation='relu'),
163
+ Dropout(0.5),
164
+ Dense(64, activation='relu'),
165
+ Dropout(0.3),
166
+ Dense(self.n_classes, activation='softmax')
167
+ ])
168
+
169
+ loss = 'categorical_crossentropy' if self.n_classes > 2 else 'binary_crossentropy'
170
+ if self.n_classes == 2:
171
+ loss = 'binary_crossentropy'
172
+ self.model.pop()
173
+ self.model.add(Dense(1, activation='sigmoid'))
174
+ else:
175
+ loss = 'categorical_crossentropy'
176
+
177
+ self.model.compile(
178
+ optimizer=tf.keras.optimizers.Adam(learning_rate=self.lr),
179
+ loss=loss,
180
+ metrics=['accuracy']
181
+ )
182
+
183
+ def fit(self, X_train, Y_train):
184
+ import tensorflow as tf
185
+ from tensorflow.keras.utils import to_categorical
186
+ from tensorflow.keras.callbacks import EarlyStopping
187
+ from EEGModels import EEGNet # From the eegmodels package
188
+ X_train, Y_train, X_valid, Y_valid = self.validation_split(X_train, Y_train)
189
+ X_train_flat = X_train.reshape(X_train.shape[0], -1)
190
+ X_train_scaled = self.scaler.fit_transform(X_train_flat)
191
+ if self.n_classes == 2:
192
+ Y_train_fmt = Y_train # (n_samples,)
193
+ else:
194
+ Y_train_fmt = to_categorical(Y_train, num_classes=self.n_classes)
195
+
196
+ callbacks = [EarlyStopping(monitor='val_loss', patience=10, restore_best_weights=True)]
197
+
198
+ fit_kwargs = {
199
+ "batch_size": self.batch_size,
200
+ "epochs": self.epochs,
201
+ "verbose": 0,
202
+ "callbacks": callbacks
203
+ }
204
+
205
+ X_valid_flat = X_valid.reshape(X_valid.shape[0], -1)
206
+ X_valid_scaled = self.scaler.transform(X_valid_flat)
207
+ if self.n_classes == 2:
208
+ Y_valid_fmt = Y_valid
209
+ else:
210
+ Y_valid_fmt = to_categorical(Y_valid, num_classes=self.n_classes)
211
+ fit_kwargs["validation_data"] = (X_valid_scaled, Y_valid_fmt)
212
+
213
+ self.model.fit(X_train_scaled, Y_train_fmt, **fit_kwargs)
214
+
215
+ def predict_proba(self, X_test):
216
+ X_test_flat = X_test.reshape(X_test.shape[0], -1)
217
+ X_test_scaled = self.scaler.transform(X_test_flat)
218
+ probs = self.model.predict(X_test_scaled)
219
+
220
+ if self.n_classes == 2:
221
+ # probs is (n, 1), reshape to (n, 2)
222
+ return np.hstack([1 - probs, probs])
223
+ else:
224
+ return probs
225
+
226
+ def get_model_name(self):
227
+ return "MLP"
228
+
229
+ def copy_from(self, other_model):
230
+ # copy model weights
231
+ self.model.set_weights(other_model.model.get_weights())
232
+ # copy scalers
233
+ self.scaler = other_model.scaler
234
+
235
+ class EEGNetModel(BaseModel):
236
+ """EEGNet"""
237
+
238
+ def __init__(self, n_classes, input_shape, **kwargs):
239
+ import tensorflow as tf
240
+ from EEGModels import EEGNet
241
+ super().__init__(n_classes, input_shape, **kwargs)
242
+ self.lr = kwargs.get('lr', 0.001)
243
+ self.n_chans, self.n_samples = self.input_shape
244
+ self.scaler = StandardScaler()
245
+ self.model = EEGNet(
246
+ nb_classes=self.n_classes,
247
+ Chans=self.n_chans,
248
+ Samples=self.n_samples,
249
+ dropoutRate=self.kwargs.get('dropoutRate', 0.5),
250
+ kernLength=self.kwargs.get('kernLength', 64),
251
+ F1=self.kwargs.get('F1', 8),
252
+ D=self.kwargs.get('D', 2),
253
+ F2=self.kwargs.get('F2', 16),
254
+ dropoutType='Dropout'
255
+ )
256
+
257
+ def fit(self, X_train, Y_train):
258
+ import tensorflow as tf
259
+ from tensorflow.keras.utils import to_categorical
260
+ from tensorflow.keras.callbacks import EarlyStopping
261
+ X_train, Y_train, X_valid, Y_valid = self.validation_split(X_train, Y_train)
262
+ loss = 'categorical_crossentropy'
263
+ # EEGNet multiclass output is softmax. For binary, we must also use categorical.
264
+ Y_train_fmt = to_categorical(Y_train, num_classes=self.n_classes)
265
+ # for i in range(X_train.shape[1]):
266
+ # X_train[:, i] = self.scalers[i].fit_transform(X_train[:, i])
267
+ # X_valid[:, i] = self.scalers[i].transform(X_valid[:, i])
268
+ X_train = self.scaler.fit_transform(X_train)
269
+
270
+ self.model.compile(
271
+ optimizer=tf.keras.optimizers.Adam(learning_rate=self.lr),
272
+ loss=loss,
273
+ metrics=['accuracy'] # Use 'accuracy' for categorical
274
+ )
275
+
276
+ # Reshape X to (batch, chans, samples, 1) for EEGNet
277
+ X_train_fmt = X_train.reshape(X_train.shape[0], self.n_chans, self.n_samples, 1)
278
+
279
+ callbacks = [EarlyStopping(monitor='val_loss', patience=15, restore_best_weights=True)]
280
+
281
+ fit_kwargs = {
282
+ "batch_size": self.kwargs.get('batch_size', 32),
283
+ "epochs": self.kwargs.get('epochs', 100),
284
+ "verbose": 0,
285
+ "callbacks": callbacks
286
+ }
287
+
288
+ X_valid = self.scaler.transform(X_valid)
289
+ X_valid_fmt = X_valid.reshape(X_valid.shape[0], self.n_chans, self.n_samples, 1)
290
+ Y_valid_fmt = to_categorical(Y_valid, num_classes=self.n_classes)
291
+ fit_kwargs["validation_data"] = (X_valid_fmt, Y_valid_fmt)
292
+
293
+ self.model.fit(X_train_fmt, Y_train_fmt, **fit_kwargs)
294
+
295
+ def predict_proba(self, X_test):# (32, 1101)
296
+ X_test = self.scaler.transform(X_test)
297
+ # for i in range(X_test.shape[1]):
298
+ # X_test[:, i] = self.scalers[i].transform(X_test[:, i])
299
+ X_test_fmt = X_test.reshape(X_test.shape[0], self.n_chans, self.n_samples, 1)
300
+ return self.model.predict(X_test_fmt)
301
+
302
+ def get_model_name(self):
303
+ return "EEGNet"
304
+
305
+ def copy_from(self, other_model):
306
+ # copy model weights
307
+ self.model.set_weights(other_model.model.get_weights())
308
+ # copy scalers
309
+ self.scaler = other_model.scaler
310
+
311
+ # --- 4. EEGPT ---
312
+
313
+ class EEGPTLinear(BaseModel):
314
+ """
315
+ EEGPT Model with a Linear Head.
316
+ The EEGPT model is loaded ONCE.
317
+ """
318
+ def __init__(self, n_classes, input_shape, **kwargs):
319
+ super().__init__(n_classes, input_shape, **kwargs)
320
+ self.lr = kwargs.get('lr', 0.001)
321
+ self.batch_size = kwargs.get('batch_size', 32)
322
+ self.num_epochs = kwargs.get('epochs', 100)
323
+ from .EEGPT import EEGPT_InternalModel
324
+ import torch
325
+ self.device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
326
+ self.model = EEGPT_InternalModel(n_classes, kwargs.get('eegpt_load_path', None), input_shape).to(self.device)
327
+
328
+ # 3. We also need a scaler for the embeddings
329
+ self.scaler = StandardScaler()
330
+
331
+ def fit(self, X_train, Y_train, verbose=False, validation=False):
332
+ import torch
333
+ if validation:
334
+ X_train, Y_train, X_valid, Y_valid = self.validation_split(X_train, Y_train)
335
+ # Y_train_fmt = to_categorical(Y_train, num_classes=self.n_classes)
336
+ X_train = self.scaler.fit_transform(X_train)
337
+ X_train = X_train.reshape(X_train.shape[0], self.n_chans, self.n_samples)
338
+ train_dataset = torch.utils.data.TensorDataset(torch.from_numpy(X_train).float(), torch.from_numpy(Y_train).long())
339
+ train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=self.batch_size, shuffle=True)
340
+
341
+ if validation:
342
+ X_valid = self.scaler.transform(X_valid)
343
+ X_valid = X_valid.reshape(X_valid.shape[0], self.n_chans, self.n_samples)
344
+ valid_dataset = torch.utils.data.TensorDataset(torch.from_numpy(X_valid).float(), torch.from_numpy(Y_valid).long())
345
+ valid_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=self.batch_size, shuffle=False)
346
+
347
+ optimizer = torch.optim.AdamW(self.model.trainable_parameters(), lr=self.lr, weight_decay=0.01)
348
+ scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=self.lr, steps_per_epoch=len(train_loader), epochs=self.num_epochs, pct_start=0.2)
349
+ loss_fn = torch.nn.CrossEntropyLoss()
350
+
351
+ self.model.train()
352
+ for epoch in range(self.num_epochs):
353
+ train_loss, train_acc = 0, 0
354
+ for X_batch, Y_batch in train_loader:
355
+ X_batch, Y_batch = X_batch.to(self.device), Y_batch.to(self.device)
356
+
357
+ optimizer.zero_grad()
358
+ logits = self.model(X_batch)
359
+ loss = loss_fn(logits, Y_batch)
360
+ loss.backward()
361
+ optimizer.step()
362
+ scheduler.step()
363
+ train_loss += loss.item()
364
+ preds = torch.argmax(logits, dim=1)
365
+ train_acc += (preds == Y_batch).sum().item()
366
+ train_loss /= len(train_loader)
367
+ train_acc /= len(train_dataset)
368
+
369
+ logstr = f"Epoch {epoch+1}/{self.num_epochs} | Train Loss: {train_loss:.4f} | Train Acc: {train_acc:.4f}"
370
+
371
+ if validation and (X_valid is not None and Y_valid is not None):
372
+ valid_loss, valid_acc = 0, 0
373
+ for X_batch, Y_batch in valid_loader:
374
+ X_batch, Y_batch = X_batch.to(self.device), Y_batch.to(self.device)
375
+ logits = self.model(X_batch)
376
+ loss = loss_fn(logits, Y_batch)
377
+ valid_loss += loss.item()
378
+ preds = torch.argmax(logits, dim=1)
379
+ valid_acc += (preds == Y_batch).sum().item()
380
+ valid_loss /= len(valid_loader)
381
+ valid_acc /= len(valid_dataset)
382
+ logstr += f" | Valid Loss: {valid_loss:.4f} | Valid Acc: {valid_acc:.4f}"
383
+
384
+ if verbose:
385
+ print(logstr)
386
+
387
+ def predict_proba(self, X_test):
388
+ import torch
389
+ X_test = self.scaler.transform(X_test)
390
+ X_test = X_test.reshape(X_test.shape[0], self.n_chans, self.n_samples)
391
+ X_test_tensor = torch.from_numpy(X_test).float().to(self.device)
392
+ test_dataset = torch.utils.data.TensorDataset(X_test_tensor)
393
+ test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=self.batch_size, shuffle=False)
394
+ self.model.eval()
395
+ all_logits = []
396
+ with torch.no_grad():
397
+ for X_batch in test_loader:
398
+ X_batch = X_batch[0].to(self.device)
399
+ logits = self.model(X_batch)
400
+ all_logits.append(logits.cpu().numpy())
401
+
402
+ return np.concatenate(all_logits, axis=0)
403
+ # X_test_fmt = X_test.reshape(X_test.shape[0], self.n_chans, self.n_samples, 1)
404
+ # return self.model.predict(X_test_fmt)
405
+
406
+ def get_model_name(self):
407
+ return "EEGPT-Linear"
408
+
409
+ def copy_from(self, other_model):
410
+ # copy model weights
411
+ # self.model.set_weights(other_model.model.get_weights())
412
+ self.model.copy_from(other_model.model)
413
+ # copy scalers
414
+ self.scaler = other_model.scaler
EEGFaceSem/pgan/__init__.py ADDED
File without changes
EEGFaceSem/pgan/config.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # This work is licensed under the Creative Commons Attribution-NonCommercial
4
+ # 4.0 International License. To view a copy of this license, visit
5
+
6
+ # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
7
+
8
+ #----------------------------------------------------------------------------
9
+ # Convenience class that behaves exactly like dict(), but allows accessing
10
+ # the keys and values using the attribute syntax, i.e., "mydict.key = value".
11
+
12
+ class EasyDict(dict):
13
+ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
14
+ def __getattr__(self, name): return self[name]
15
+ def __setattr__(self, name, value): self[name] = value
16
+ def __delattr__(self, name): del self[name]
17
+
18
+ #----------------------------------------------------------------------------
19
+ # Paths.
20
+
21
+ data_dir = 'datasets'
22
+ result_dir = 'results'
23
+
24
+ #----------------------------------------------------------------------------
25
+ # TensorFlow options.
26
+
27
+ tf_config = EasyDict() # TensorFlow session config, set by tfutil.init_tf().
28
+ env = EasyDict() # Environment variables, set by the main program in train.py.
29
+
30
+ tf_config['graph_options.place_pruned_graph'] = True # False (default) = Check that all ops are available on the designated device. True = Skip the check for ops that are not used.
31
+ #tf_config['gpu_options.allow_growth'] = False # False (default) = Allocate all GPU memory at the beginning. True = Allocate only as much GPU memory as needed.
32
+ #env.CUDA_VISIBLE_DEVICES = '0' # Unspecified (default) = Use all available GPUs. List of ints = CUDA device numbers to use.
33
+ env.TF_CPP_MIN_LOG_LEVEL = '1' # 0 (default) = Print all available debug info from TensorFlow. 1 = Print warnings and errors, but disable debug info.
34
+
35
+ #----------------------------------------------------------------------------
36
+ # Official training configs, targeted mainly for CelebA-HQ.
37
+ # To run, comment/uncomment the lines as appropriate and launch train.py.
38
+
39
+ desc = 'pgan' # Description string included in result subdir name.
40
+ random_seed = 1000 # Global random seed.
41
+ dataset = EasyDict() # Options for dataset.load_dataset().
42
+ train = EasyDict(func='train.train_progressive_gan') # Options for main training func.
43
+ G = EasyDict(func='networks.G_paper') # Options for generator network.
44
+ D = EasyDict(func='networks.D_paper') # Options for discriminator network.
45
+ G_opt = EasyDict(beta1=0.0, beta2=0.99, epsilon=1e-8) # Options for generator optimizer.
46
+ D_opt = EasyDict(beta1=0.0, beta2=0.99, epsilon=1e-8) # Options for discriminator optimizer.
47
+ G_loss = EasyDict(func='loss.G_wgan_acgan') # Options for generator loss.
48
+ D_loss = EasyDict(func='loss.D_wgangp_acgan') # Options for discriminator loss.
49
+ sched = EasyDict() # Options for train.TrainingSchedule.
50
+ grid = EasyDict(size='1080p', layout='random') # Options for train.setup_snapshot_image_grid().
51
+
52
+ # Dataset (choose one).
53
+ desc += '-celebahq'; dataset = EasyDict(tfrecord_dir='celebahq'); train.mirror_augment = True
54
+ #desc += '-celeba'; dataset = EasyDict(tfrecord_dir='celeba'); train.mirror_augment = True
55
+ #desc += '-cifar10'; dataset = EasyDict(tfrecord_dir='cifar10')
56
+ #desc += '-cifar100'; dataset = EasyDict(tfrecord_dir='cifar100')
57
+ #desc += '-svhn'; dataset = EasyDict(tfrecord_dir='svhn')
58
+ #desc += '-mnist'; dataset = EasyDict(tfrecord_dir='mnist')
59
+ #desc += '-mnistrgb'; dataset = EasyDict(tfrecord_dir='mnistrgb')
60
+ #desc += '-syn1024rgb'; dataset = EasyDict(class_name='dataset.SyntheticDataset', resolution=1024, num_channels=3)
61
+ #desc += '-lsun-airplane'; dataset = EasyDict(tfrecord_dir='lsun-airplane-100k'); train.mirror_augment = True
62
+ #desc += '-lsun-bedroom'; dataset = EasyDict(tfrecord_dir='lsun-bedroom-100k'); train.mirror_augment = True
63
+ #desc += '-lsun-bicycle'; dataset = EasyDict(tfrecord_dir='lsun-bicycle-100k'); train.mirror_augment = True
64
+ #desc += '-lsun-bird'; dataset = EasyDict(tfrecord_dir='lsun-bird-100k'); train.mirror_augment = True
65
+ #desc += '-lsun-boat'; dataset = EasyDict(tfrecord_dir='lsun-boat-100k'); train.mirror_augment = True
66
+ #desc += '-lsun-bottle'; dataset = EasyDict(tfrecord_dir='lsun-bottle-100k'); train.mirror_augment = True
67
+ #desc += '-lsun-bridge'; dataset = EasyDict(tfrecord_dir='lsun-bridge-100k'); train.mirror_augment = True
68
+ #desc += '-lsun-bus'; dataset = EasyDict(tfrecord_dir='lsun-bus-100k'); train.mirror_augment = True
69
+ #desc += '-lsun-car'; dataset = EasyDict(tfrecord_dir='lsun-car-100k'); train.mirror_augment = True
70
+ #desc += '-lsun-cat'; dataset = EasyDict(tfrecord_dir='lsun-cat-100k'); train.mirror_augment = True
71
+ #desc += '-lsun-chair'; dataset = EasyDict(tfrecord_dir='lsun-chair-100k'); train.mirror_augment = True
72
+ #desc += '-lsun-churchoutdoor'; dataset = EasyDict(tfrecord_dir='lsun-churchoutdoor-100k'); train.mirror_augment = True
73
+ #desc += '-lsun-classroom'; dataset = EasyDict(tfrecord_dir='lsun-classroom-100k'); train.mirror_augment = True
74
+ #desc += '-lsun-conferenceroom'; dataset = EasyDict(tfrecord_dir='lsun-conferenceroom-100k'); train.mirror_augment = True
75
+ #desc += '-lsun-cow'; dataset = EasyDict(tfrecord_dir='lsun-cow-100k'); train.mirror_augment = True
76
+ #desc += '-lsun-diningroom'; dataset = EasyDict(tfrecord_dir='lsun-diningroom-100k'); train.mirror_augment = True
77
+ #desc += '-lsun-diningtable'; dataset = EasyDict(tfrecord_dir='lsun-diningtable-100k'); train.mirror_augment = True
78
+ #desc += '-lsun-dog'; dataset = EasyDict(tfrecord_dir='lsun-dog-100k'); train.mirror_augment = True
79
+ #desc += '-lsun-horse'; dataset = EasyDict(tfrecord_dir='lsun-horse-100k'); train.mirror_augment = True
80
+ #desc += '-lsun-kitchen'; dataset = EasyDict(tfrecord_dir='lsun-kitchen-100k'); train.mirror_augment = True
81
+ #desc += '-lsun-livingroom'; dataset = EasyDict(tfrecord_dir='lsun-livingroom-100k'); train.mirror_augment = True
82
+ #desc += '-lsun-motorbike'; dataset = EasyDict(tfrecord_dir='lsun-motorbike-100k'); train.mirror_augment = True
83
+ #desc += '-lsun-person'; dataset = EasyDict(tfrecord_dir='lsun-person-100k'); train.mirror_augment = True
84
+ #desc += '-lsun-pottedplant'; dataset = EasyDict(tfrecord_dir='lsun-pottedplant-100k'); train.mirror_augment = True
85
+ #desc += '-lsun-restaurant'; dataset = EasyDict(tfrecord_dir='lsun-restaurant-100k'); train.mirror_augment = True
86
+ #desc += '-lsun-sheep'; dataset = EasyDict(tfrecord_dir='lsun-sheep-100k'); train.mirror_augment = True
87
+ #desc += '-lsun-sofa'; dataset = EasyDict(tfrecord_dir='lsun-sofa-100k'); train.mirror_augment = True
88
+ #desc += '-lsun-tower'; dataset = EasyDict(tfrecord_dir='lsun-tower-100k'); train.mirror_augment = True
89
+ #desc += '-lsun-train'; dataset = EasyDict(tfrecord_dir='lsun-train-100k'); train.mirror_augment = True
90
+ #desc += '-lsun-tvmonitor'; dataset = EasyDict(tfrecord_dir='lsun-tvmonitor-100k'); train.mirror_augment = True
91
+
92
+ # Conditioning & snapshot options.
93
+ #desc += '-cond'; dataset.max_label_size = 'full' # conditioned on full label
94
+ #desc += '-cond1'; dataset.max_label_size = 1 # conditioned on first component of the label
95
+ #desc += '-g4k'; grid.size = '4k'
96
+ #desc += '-grpc'; grid.layout = 'row_per_class'
97
+
98
+ # Config presets (choose one).
99
+ #desc += '-preset-v1-1gpu'; num_gpus = 1; D.mbstd_group_size = 16; sched.minibatch_base = 16; sched.minibatch_dict = {256: 14, 512: 6, 1024: 3}; sched.lod_training_kimg = 800; sched.lod_transition_kimg = 800; train.total_kimg = 19000
100
+ desc += '-preset-v2-1gpu'; num_gpus = 1; sched.minibatch_base = 4; sched.minibatch_dict = {4: 128, 8: 128, 16: 128, 32: 64, 64: 32, 128: 16, 256: 8, 512: 4}; sched.G_lrate_dict = {1024: 0.0015}; sched.D_lrate_dict = EasyDict(sched.G_lrate_dict); train.total_kimg = 12000
101
+ #desc += '-preset-v2-2gpus'; num_gpus = 2; sched.minibatch_base = 8; sched.minibatch_dict = {4: 256, 8: 256, 16: 128, 32: 64, 64: 32, 128: 16, 256: 8}; sched.G_lrate_dict = {512: 0.0015, 1024: 0.002}; sched.D_lrate_dict = EasyDict(sched.G_lrate_dict); train.total_kimg = 12000
102
+ #desc += '-preset-v2-4gpus'; num_gpus = 4; sched.minibatch_base = 16; sched.minibatch_dict = {4: 512, 8: 256, 16: 128, 32: 64, 64: 32, 128: 16}; sched.G_lrate_dict = {256: 0.0015, 512: 0.002, 1024: 0.003}; sched.D_lrate_dict = EasyDict(sched.G_lrate_dict); train.total_kimg = 12000
103
+ #desc += '-preset-v2-8gpus'; num_gpus = 8; sched.minibatch_base = 32; sched.minibatch_dict = {4: 512, 8: 256, 16: 128, 32: 64, 64: 32}; sched.G_lrate_dict = {128: 0.0015, 256: 0.002, 512: 0.003, 1024: 0.003}; sched.D_lrate_dict = EasyDict(sched.G_lrate_dict); train.total_kimg = 12000
104
+
105
+ # Numerical precision (choose one).
106
+ desc += '-fp32'; sched.max_minibatch_per_gpu = {256: 16, 512: 8, 1024: 4}
107
+ #desc += '-fp16'; G.dtype = 'float16'; D.dtype = 'float16'; G.pixelnorm_epsilon=1e-4; G_opt.use_loss_scaling = True; D_opt.use_loss_scaling = True; sched.max_minibatch_per_gpu = {512: 16, 1024: 8}
108
+
109
+ # Disable individual features.
110
+ #desc += '-nogrowing'; sched.lod_initial_resolution = 1024; sched.lod_training_kimg = 0; sched.lod_transition_kimg = 0; train.total_kimg = 10000
111
+ #desc += '-nopixelnorm'; G.use_pixelnorm = False
112
+ #desc += '-nowscale'; G.use_wscale = False; D.use_wscale = False
113
+ #desc += '-noleakyrelu'; G.use_leakyrelu = False
114
+ #desc += '-nosmoothing'; train.G_smoothing = 0.0
115
+ #desc += '-norepeat'; train.minibatch_repeats = 1
116
+ #desc += '-noreset'; train.reset_opt_for_new_lod = False
117
+
118
+ # Special modes.
119
+ #desc += '-BENCHMARK'; sched.lod_initial_resolution = 4; sched.lod_training_kimg = 3; sched.lod_transition_kimg = 3; train.total_kimg = (8*2+1)*3; sched.tick_kimg_base = 1; sched.tick_kimg_dict = {}; train.image_snapshot_ticks = 1000; train.network_snapshot_ticks = 1000
120
+ #desc += '-BENCHMARK0'; sched.lod_initial_resolution = 1024; train.total_kimg = 10; sched.tick_kimg_base = 1; sched.tick_kimg_dict = {}; train.image_snapshot_ticks = 1000; train.network_snapshot_ticks = 1000
121
+ #desc += '-VERBOSE'; sched.tick_kimg_base = 1; sched.tick_kimg_dict = {}; train.image_snapshot_ticks = 1; train.network_snapshot_ticks = 100
122
+ #desc += '-GRAPH'; train.save_tf_graph = True
123
+ #desc += '-HIST'; train.save_weight_histograms = True
124
+
125
+ #----------------------------------------------------------------------------
126
+ # Utility scripts.
127
+ # To run, uncomment the appropriate line and launch train.py.
128
+
129
+ #train = EasyDict(func='util_scripts.generate_fake_images', run_id=23, num_pngs=1000); num_gpus = 1; desc = 'fake-images-' + str(train.run_id)
130
+ #train = EasyDict(func='util_scripts.generate_fake_images', run_id=23, grid_size=[15,8], num_pngs=10, image_shrink=4); num_gpus = 1; desc = 'fake-grids-' + str(train.run_id)
131
+ #train = EasyDict(func='util_scripts.generate_interpolation_video', run_id=23, grid_size=[1,1], duration_sec=60.0, smoothing_sec=1.0); num_gpus = 1; desc = 'interpolation-video-' + str(train.run_id)
132
+ #train = EasyDict(func='util_scripts.generate_training_video', run_id=23, duration_sec=20.0); num_gpus = 1; desc = 'training-video-' + str(train.run_id)
133
+
134
+ #train = EasyDict(func='util_scripts.evaluate_metrics', run_id=23, log='metric-swd-16k.txt', metrics=['swd'], num_images=16384, real_passes=2); num_gpus = 1; desc = train.log.split('.')[0] + '-' + str(train.run_id)
135
+ #train = EasyDict(func='util_scripts.evaluate_metrics', run_id=23, log='metric-fid-10k.txt', metrics=['fid'], num_images=10000, real_passes=1); num_gpus = 1; desc = train.log.split('.')[0] + '-' + str(train.run_id)
136
+ #train = EasyDict(func='util_scripts.evaluate_metrics', run_id=23, log='metric-fid-50k.txt', metrics=['fid'], num_images=50000, real_passes=1); num_gpus = 1; desc = train.log.split('.')[0] + '-' + str(train.run_id)
137
+ #train = EasyDict(func='util_scripts.evaluate_metrics', run_id=23, log='metric-is-50k.txt', metrics=['is'], num_images=50000, real_passes=1); num_gpus = 1; desc = train.log.split('.')[0] + '-' + str(train.run_id)
138
+ #train = EasyDict(func='util_scripts.evaluate_metrics', run_id=23, log='metric-msssim-20k.txt', metrics=['msssim'], num_images=20000, real_passes=1); num_gpus = 1; desc = train.log.split('.')[0] + '-' + str(train.run_id)
139
+
140
+ #----------------------------------------------------------------------------
EEGFaceSem/pgan/dataset.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # This work is licensed under the Creative Commons Attribution-NonCommercial
4
+ # 4.0 International License. To view a copy of this license, visit
5
+
6
+ # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
7
+
8
+ import os
9
+ import glob
10
+ import numpy as np
11
+ import tensorflow as tf
12
+ import tfutil
13
+
14
+ #----------------------------------------------------------------------------
15
+ # Parse individual image from a tfrecords file.
16
+
17
+ def parse_tfrecord_tf(record):
18
+ features = tf.parse_single_example(record, features={
19
+ 'shape': tf.FixedLenFeature([3], tf.int64),
20
+ 'data': tf.FixedLenFeature([], tf.string)})
21
+ data = tf.decode_raw(features['data'], tf.uint8)
22
+ return tf.reshape(data, features['shape'])
23
+
24
+ def parse_tfrecord_np(record):
25
+ ex = tf.train.Example()
26
+ ex.ParseFromString(record)
27
+ shape = ex.features.feature['shape'].int64_list.value
28
+ data = ex.features.feature['data'].bytes_list.value[0]
29
+ return np.fromstring(data, np.uint8).reshape(shape)
30
+
31
+ #----------------------------------------------------------------------------
32
+ # Dataset class that loads data from tfrecords files.
33
+
34
+ class TFRecordDataset:
35
+ def __init__(self,
36
+ tfrecord_dir, # Directory containing a collection of tfrecords files.
37
+ resolution = None, # Dataset resolution, None = autodetect.
38
+ label_file = None, # Relative path of the labels file, None = autodetect.
39
+ max_label_size = 0, # 0 = no labels, 'full' = full labels, <int> = N first label components.
40
+ repeat = True, # Repeat dataset indefinitely.
41
+ shuffle_mb = 4096, # Shuffle data within specified window (megabytes), 0 = disable shuffling.
42
+ prefetch_mb = 2048, # Amount of data to prefetch (megabytes), 0 = disable prefetching.
43
+ buffer_mb = 256, # Read buffer size (megabytes).
44
+ num_threads = 2): # Number of concurrent threads.
45
+
46
+ self.tfrecord_dir = tfrecord_dir
47
+ self.resolution = None
48
+ self.resolution_log2 = None
49
+ self.shape = [] # [channel, height, width]
50
+ self.dtype = 'uint8'
51
+ self.dynamic_range = [0, 255]
52
+ self.label_file = label_file
53
+ self.label_size = None # [component]
54
+ self.label_dtype = None
55
+ self._np_labels = None
56
+ self._tf_minibatch_in = None
57
+ self._tf_labels_var = None
58
+ self._tf_labels_dataset = None
59
+ self._tf_datasets = dict()
60
+ self._tf_iterator = None
61
+ self._tf_init_ops = dict()
62
+ self._tf_minibatch_np = None
63
+ self._cur_minibatch = -1
64
+ self._cur_lod = -1
65
+
66
+ # List tfrecords files and inspect their shapes.
67
+ assert os.path.isdir(self.tfrecord_dir)
68
+ tfr_files = sorted(glob.glob(os.path.join(self.tfrecord_dir, '*.tfrecords')))
69
+ assert len(tfr_files) >= 1
70
+ tfr_shapes = []
71
+ for tfr_file in tfr_files:
72
+ tfr_opt = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.NONE)
73
+ for record in tf.python_io.tf_record_iterator(tfr_file, tfr_opt):
74
+ tfr_shapes.append(parse_tfrecord_np(record).shape)
75
+ break
76
+
77
+ # Autodetect label filename.
78
+ if self.label_file is None:
79
+ guess = sorted(glob.glob(os.path.join(self.tfrecord_dir, '*.labels')))
80
+ if len(guess):
81
+ self.label_file = guess[0]
82
+ elif not os.path.isfile(self.label_file):
83
+ guess = os.path.join(self.tfrecord_dir, self.label_file)
84
+ if os.path.isfile(guess):
85
+ self.label_file = guess
86
+
87
+ # Determine shape and resolution.
88
+ max_shape = max(tfr_shapes, key=lambda shape: np.prod(shape))
89
+ self.resolution = resolution if resolution is not None else max_shape[1]
90
+ self.resolution_log2 = int(np.log2(self.resolution))
91
+ self.shape = [max_shape[0], self.resolution, self.resolution]
92
+ tfr_lods = [self.resolution_log2 - int(np.log2(shape[1])) for shape in tfr_shapes]
93
+ assert all(shape[0] == max_shape[0] for shape in tfr_shapes)
94
+ assert all(shape[1] == shape[2] for shape in tfr_shapes)
95
+ assert all(shape[1] == self.resolution // (2**lod) for shape, lod in zip(tfr_shapes, tfr_lods))
96
+ assert all(lod in tfr_lods for lod in range(self.resolution_log2 - 1))
97
+
98
+ # Load labels.
99
+ assert max_label_size == 'full' or max_label_size >= 0
100
+ self._np_labels = np.zeros([1<<20, 0], dtype=np.float32)
101
+ if self.label_file is not None and max_label_size != 0:
102
+ self._np_labels = np.load(self.label_file)
103
+ assert self._np_labels.ndim == 2
104
+ if max_label_size != 'full' and self._np_labels.shape[1] > max_label_size:
105
+ self._np_labels = self._np_labels[:, :max_label_size]
106
+ self.label_size = self._np_labels.shape[1]
107
+ self.label_dtype = self._np_labels.dtype.name
108
+
109
+ # Build TF expressions.
110
+ with tf.name_scope('Dataset'), tf.device('/cpu:0'):
111
+ self._tf_minibatch_in = tf.placeholder(tf.int64, name='minibatch_in', shape=[])
112
+ tf_labels_init = tf.zeros(self._np_labels.shape, self._np_labels.dtype)
113
+ self._tf_labels_var = tf.Variable(tf_labels_init, name='labels_var')
114
+ tfutil.set_vars({self._tf_labels_var: self._np_labels})
115
+ self._tf_labels_dataset = tf.data.Dataset.from_tensor_slices(self._tf_labels_var)
116
+ for tfr_file, tfr_shape, tfr_lod in zip(tfr_files, tfr_shapes, tfr_lods):
117
+ if tfr_lod < 0:
118
+ continue
119
+ dset = tf.data.TFRecordDataset(tfr_file, compression_type='', buffer_size=buffer_mb<<20)
120
+ dset = dset.map(parse_tfrecord_tf, num_parallel_calls=num_threads)
121
+ dset = tf.data.Dataset.zip((dset, self._tf_labels_dataset))
122
+ bytes_per_item = np.prod(tfr_shape) * np.dtype(self.dtype).itemsize
123
+ if shuffle_mb > 0:
124
+ dset = dset.shuffle(((shuffle_mb << 20) - 1) // bytes_per_item + 1)
125
+ if repeat:
126
+ dset = dset.repeat()
127
+ if prefetch_mb > 0:
128
+ dset = dset.prefetch(((prefetch_mb << 20) - 1) // bytes_per_item + 1)
129
+ dset = dset.batch(self._tf_minibatch_in)
130
+ self._tf_datasets[tfr_lod] = dset
131
+ self._tf_iterator = tf.data.Iterator.from_structure(self._tf_datasets[0].output_types, self._tf_datasets[0].output_shapes)
132
+ self._tf_init_ops = {lod: self._tf_iterator.make_initializer(dset) for lod, dset in self._tf_datasets.items()}
133
+
134
+ # Use the given minibatch size and level-of-detail for the data returned by get_minibatch_tf().
135
+ def configure(self, minibatch_size, lod=0):
136
+ lod = int(np.floor(lod))
137
+ assert minibatch_size >= 1 and lod in self._tf_datasets
138
+ if self._cur_minibatch != minibatch_size or self._cur_lod != lod:
139
+ self._tf_init_ops[lod].run({self._tf_minibatch_in: minibatch_size})
140
+ self._cur_minibatch = minibatch_size
141
+ self._cur_lod = lod
142
+
143
+ # Get next minibatch as TensorFlow expressions.
144
+ def get_minibatch_tf(self): # => images, labels
145
+ return self._tf_iterator.get_next()
146
+
147
+ # Get next minibatch as NumPy arrays.
148
+ def get_minibatch_np(self, minibatch_size, lod=0): # => images, labels
149
+ self.configure(minibatch_size, lod)
150
+ if self._tf_minibatch_np is None:
151
+ self._tf_minibatch_np = self.get_minibatch_tf()
152
+ return tfutil.run(self._tf_minibatch_np)
153
+
154
+ # Get random labels as TensorFlow expression.
155
+ def get_random_labels_tf(self, minibatch_size): # => labels
156
+ if self.label_size > 0:
157
+ return tf.gather(self._tf_labels_var, tf.random_uniform([minibatch_size], 0, self._np_labels.shape[0], dtype=tf.int32))
158
+ else:
159
+ return tf.zeros([minibatch_size, 0], self.label_dtype)
160
+
161
+ # Get random labels as NumPy array.
162
+ def get_random_labels_np(self, minibatch_size): # => labels
163
+ if self.label_size > 0:
164
+ return self._np_labels[np.random.randint(self._np_labels.shape[0], size=[minibatch_size])]
165
+ else:
166
+ return np.zeros([minibatch_size, 0], self.label_dtype)
167
+
168
+ #----------------------------------------------------------------------------
169
+ # Base class for datasets that are generated on the fly.
170
+
171
+ class SyntheticDataset:
172
+ def __init__(self, resolution=1024, num_channels=3, dtype='uint8', dynamic_range=[0,255], label_size=0, label_dtype='float32'):
173
+ self.resolution = resolution
174
+ self.resolution_log2 = int(np.log2(resolution))
175
+ self.shape = [num_channels, resolution, resolution]
176
+ self.dtype = dtype
177
+ self.dynamic_range = dynamic_range
178
+ self.label_size = label_size
179
+ self.label_dtype = label_dtype
180
+ self._tf_minibatch_var = None
181
+ self._tf_lod_var = None
182
+ self._tf_minibatch_np = None
183
+ self._tf_labels_np = None
184
+
185
+ assert self.resolution == 2 ** self.resolution_log2
186
+ with tf.name_scope('Dataset'):
187
+ self._tf_minibatch_var = tf.Variable(np.int32(0), name='minibatch_var')
188
+ self._tf_lod_var = tf.Variable(np.int32(0), name='lod_var')
189
+
190
+ def configure(self, minibatch_size, lod=0):
191
+ lod = int(np.floor(lod))
192
+ assert minibatch_size >= 1 and lod >= 0 and lod <= self.resolution_log2
193
+ tfutil.set_vars({self._tf_minibatch_var: minibatch_size, self._tf_lod_var: lod})
194
+
195
+ def get_minibatch_tf(self): # => images, labels
196
+ with tf.name_scope('SyntheticDataset'):
197
+ shrink = tf.cast(2.0 ** tf.cast(self._tf_lod_var, tf.float32), tf.int32)
198
+ shape = [self.shape[0], self.shape[1] // shrink, self.shape[2] // shrink]
199
+ images = self._generate_images(self._tf_minibatch_var, self._tf_lod_var, shape)
200
+ labels = self._generate_labels(self._tf_minibatch_var)
201
+ return images, labels
202
+
203
+ def get_minibatch_np(self, minibatch_size, lod=0): # => images, labels
204
+ self.configure(minibatch_size, lod)
205
+ if self._tf_minibatch_np is None:
206
+ self._tf_minibatch_np = self.get_minibatch_tf()
207
+ return tfutil.run(self._tf_minibatch_np)
208
+
209
+ def get_random_labels_tf(self, minibatch_size): # => labels
210
+ with tf.name_scope('SyntheticDataset'):
211
+ return self._generate_labels(minibatch_size)
212
+
213
+ def get_random_labels_np(self, minibatch_size): # => labels
214
+ self.configure(minibatch_size)
215
+ if self._tf_labels_np is None:
216
+ self._tf_labels_np = self.get_random_labels_tf()
217
+ return tfutil.run(self._tf_labels_np)
218
+
219
+ def _generate_images(self, minibatch, lod, shape): # to be overridden by subclasses
220
+ return tf.zeros([minibatch] + shape, self.dtype)
221
+
222
+ def _generate_labels(self, minibatch): # to be overridden by subclasses
223
+ return tf.zeros([minibatch, self.label_size], self.label_dtype)
224
+
225
+ #----------------------------------------------------------------------------
226
+ # Helper func for constructing a dataset object using the given options.
227
+
228
+ def load_dataset(class_name='dataset.TFRecordDataset', data_dir=None, verbose=False, **kwargs):
229
+ adjusted_kwargs = dict(kwargs)
230
+ if 'tfrecord_dir' in adjusted_kwargs and data_dir is not None:
231
+ adjusted_kwargs['tfrecord_dir'] = os.path.join(data_dir, adjusted_kwargs['tfrecord_dir'])
232
+ if verbose:
233
+ print('Streaming data using %s...' % class_name)
234
+ dataset = tfutil.import_obj(class_name)(**adjusted_kwargs)
235
+ if verbose:
236
+ print('Dataset shape =', np.int32(dataset.shape).tolist())
237
+ print('Dynamic range =', dataset.dynamic_range)
238
+ print('Label size =', dataset.label_size)
239
+ return dataset
240
+
241
+ #----------------------------------------------------------------------------
EEGFaceSem/pgan/dataset_tool.py ADDED
@@ -0,0 +1,740 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # This work is licensed under the Creative Commons Attribution-NonCommercial
4
+ # 4.0 International License. To view a copy of this license, visit
5
+
6
+ # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
7
+
8
+ import os
9
+ import sys
10
+ import glob
11
+ import argparse
12
+ import threading
13
+ import six.moves.queue as Queue
14
+ import traceback
15
+ import numpy as np
16
+ import tensorflow as tf
17
+ import PIL.Image
18
+
19
+ import tfutil
20
+ import dataset
21
+
22
+ #----------------------------------------------------------------------------
23
+
24
+ def error(msg):
25
+ print('Error: ' + msg)
26
+ exit(1)
27
+
28
+ #----------------------------------------------------------------------------
29
+
30
+ class TFRecordExporter:
31
+ def __init__(self, tfrecord_dir, expected_images, print_progress=True, progress_interval=10):
32
+ self.tfrecord_dir = tfrecord_dir
33
+ self.tfr_prefix = os.path.join(self.tfrecord_dir, os.path.basename(self.tfrecord_dir))
34
+ self.expected_images = expected_images
35
+ self.cur_images = 0
36
+ self.shape = None
37
+ self.resolution_log2 = None
38
+ self.tfr_writers = []
39
+ self.print_progress = print_progress
40
+ self.progress_interval = progress_interval
41
+ if self.print_progress:
42
+ print('Creating dataset "%s"' % tfrecord_dir)
43
+ if not os.path.isdir(self.tfrecord_dir):
44
+ os.makedirs(self.tfrecord_dir)
45
+ assert(os.path.isdir(self.tfrecord_dir))
46
+
47
+ def close(self):
48
+ if self.print_progress:
49
+ print('%-40s\r' % 'Flushing data...', end='', flush=True)
50
+ for tfr_writer in self.tfr_writers:
51
+ tfr_writer.close()
52
+ self.tfr_writers = []
53
+ if self.print_progress:
54
+ print('%-40s\r' % '', end='', flush=True)
55
+ print('Added %d images.' % self.cur_images)
56
+
57
+ def choose_shuffled_order(self): # Note: Images and labels must be added in shuffled order.
58
+ order = np.arange(self.expected_images)
59
+ np.random.RandomState(123).shuffle(order)
60
+ return order
61
+
62
+ def add_image(self, img):
63
+ if self.print_progress and self.cur_images % self.progress_interval == 0:
64
+ print('%d / %d\r' % (self.cur_images, self.expected_images), end='', flush=True)
65
+ if self.shape is None:
66
+ self.shape = img.shape
67
+ self.resolution_log2 = int(np.log2(self.shape[1]))
68
+ assert self.shape[0] in [1, 3]
69
+ assert self.shape[1] == self.shape[2]
70
+ assert self.shape[1] == 2**self.resolution_log2
71
+ tfr_opt = tf.python_io.TFRecordOptions(tf.python_io.TFRecordCompressionType.NONE)
72
+ for lod in range(self.resolution_log2 - 1):
73
+ tfr_file = self.tfr_prefix + '-r%02d.tfrecords' % (self.resolution_log2 - lod)
74
+ self.tfr_writers.append(tf.python_io.TFRecordWriter(tfr_file, tfr_opt))
75
+ assert img.shape == self.shape
76
+ for lod, tfr_writer in enumerate(self.tfr_writers):
77
+ if lod:
78
+ img = img.astype(np.float32)
79
+ img = (img[:, 0::2, 0::2] + img[:, 0::2, 1::2] + img[:, 1::2, 0::2] + img[:, 1::2, 1::2]) * 0.25
80
+ quant = np.rint(img).clip(0, 255).astype(np.uint8)
81
+ ex = tf.train.Example(features=tf.train.Features(feature={
82
+ 'shape': tf.train.Feature(int64_list=tf.train.Int64List(value=quant.shape)),
83
+ 'data': tf.train.Feature(bytes_list=tf.train.BytesList(value=[quant.tostring()]))}))
84
+ tfr_writer.write(ex.SerializeToString())
85
+ self.cur_images += 1
86
+
87
+ def add_labels(self, labels):
88
+ if self.print_progress:
89
+ print('%-40s\r' % 'Saving labels...', end='', flush=True)
90
+ assert labels.shape[0] == self.cur_images
91
+ with open(self.tfr_prefix + '-rxx.labels', 'wb') as f:
92
+ np.save(f, labels.astype(np.float32))
93
+
94
+ def __enter__(self):
95
+ return self
96
+
97
+ def __exit__(self, *args):
98
+ self.close()
99
+
100
+ #----------------------------------------------------------------------------
101
+
102
+ class ExceptionInfo(object):
103
+ def __init__(self):
104
+ self.value = sys.exc_info()[1]
105
+ self.traceback = traceback.format_exc()
106
+
107
+ #----------------------------------------------------------------------------
108
+
109
+ class WorkerThread(threading.Thread):
110
+ def __init__(self, task_queue):
111
+ threading.Thread.__init__(self)
112
+ self.task_queue = task_queue
113
+
114
+ def run(self):
115
+ while True:
116
+ func, args, result_queue = self.task_queue.get()
117
+ if func is None:
118
+ break
119
+ try:
120
+ result = func(*args)
121
+ except:
122
+ result = ExceptionInfo()
123
+ result_queue.put((result, args))
124
+
125
+ #----------------------------------------------------------------------------
126
+
127
+ class ThreadPool(object):
128
+ def __init__(self, num_threads):
129
+ assert num_threads >= 1
130
+ self.task_queue = Queue.Queue()
131
+ self.result_queues = dict()
132
+ self.num_threads = num_threads
133
+ for idx in range(self.num_threads):
134
+ thread = WorkerThread(self.task_queue)
135
+ thread.daemon = True
136
+ thread.start()
137
+
138
+ def add_task(self, func, args=()):
139
+ assert hasattr(func, '__call__') # must be a function
140
+ if func not in self.result_queues:
141
+ self.result_queues[func] = Queue.Queue()
142
+ self.task_queue.put((func, args, self.result_queues[func]))
143
+
144
+ def get_result(self, func): # returns (result, args)
145
+ result, args = self.result_queues[func].get()
146
+ if isinstance(result, ExceptionInfo):
147
+ print('\n\nWorker thread caught an exception:\n' + result.traceback)
148
+ raise result.value
149
+ return result, args
150
+
151
+ def finish(self):
152
+ for idx in range(self.num_threads):
153
+ self.task_queue.put((None, (), None))
154
+
155
+ def __enter__(self): # for 'with' statement
156
+ return self
157
+
158
+ def __exit__(self, *excinfo):
159
+ self.finish()
160
+
161
+ def process_items_concurrently(self, item_iterator, process_func=lambda x: x, pre_func=lambda x: x, post_func=lambda x: x, max_items_in_flight=None):
162
+ if max_items_in_flight is None: max_items_in_flight = self.num_threads * 4
163
+ assert max_items_in_flight >= 1
164
+ results = []
165
+ retire_idx = [0]
166
+
167
+ def task_func(prepared, idx):
168
+ return process_func(prepared)
169
+
170
+ def retire_result():
171
+ processed, (prepared, idx) = self.get_result(task_func)
172
+ results[idx] = processed
173
+ while retire_idx[0] < len(results) and results[retire_idx[0]] is not None:
174
+ yield post_func(results[retire_idx[0]])
175
+ results[retire_idx[0]] = None
176
+ retire_idx[0] += 1
177
+
178
+ for idx, item in enumerate(item_iterator):
179
+ prepared = pre_func(item)
180
+ results.append(None)
181
+ self.add_task(func=task_func, args=(prepared, idx))
182
+ while retire_idx[0] < idx - max_items_in_flight + 2:
183
+ for res in retire_result(): yield res
184
+ while retire_idx[0] < len(results):
185
+ for res in retire_result(): yield res
186
+
187
+ #----------------------------------------------------------------------------
188
+
189
+ def display(tfrecord_dir):
190
+ print('Loading dataset "%s"' % tfrecord_dir)
191
+ tfutil.init_tf({'gpu_options.allow_growth': True})
192
+ dset = dataset.TFRecordDataset(tfrecord_dir, max_label_size='full', repeat=False, shuffle_mb=0)
193
+ tfutil.init_uninited_vars()
194
+
195
+ idx = 0
196
+ while True:
197
+ try:
198
+ images, labels = dset.get_minibatch_np(1)
199
+ except tf.errors.OutOfRangeError:
200
+ break
201
+ if idx == 0:
202
+ print('Displaying images')
203
+ import cv2 # pip install opencv-python
204
+ cv2.namedWindow('dataset_tool')
205
+ print('Press SPACE or ENTER to advance, ESC to exit')
206
+ print('\nidx = %-8d\nlabel = %s' % (idx, labels[0].tolist()))
207
+ cv2.imshow('dataset_tool', images[0].transpose(1, 2, 0)[:, :, ::-1]) # CHW => HWC, RGB => BGR
208
+ idx += 1
209
+ if cv2.waitKey() == 27:
210
+ break
211
+ print('\nDisplayed %d images.' % idx)
212
+
213
+ #----------------------------------------------------------------------------
214
+
215
+ def extract(tfrecord_dir, output_dir):
216
+ print('Loading dataset "%s"' % tfrecord_dir)
217
+ tfutil.init_tf({'gpu_options.allow_growth': True})
218
+ dset = dataset.TFRecordDataset(tfrecord_dir, max_label_size=0, repeat=False, shuffle_mb=0)
219
+ tfutil.init_uninited_vars()
220
+
221
+ print('Extracting images to "%s"' % output_dir)
222
+ if not os.path.isdir(output_dir):
223
+ os.makedirs(output_dir)
224
+ idx = 0
225
+ while True:
226
+ if idx % 10 == 0:
227
+ print('%d\r' % idx, end='', flush=True)
228
+ try:
229
+ images, labels = dset.get_minibatch_np(1)
230
+ except tf.errors.OutOfRangeError:
231
+ break
232
+ if images.shape[1] == 1:
233
+ img = PIL.Image.fromarray(images[0][0], 'L')
234
+ else:
235
+ img = PIL.Image.fromarray(images[0].transpose(1, 2, 0), 'RGB')
236
+ img.save(os.path.join(output_dir, 'img%08d.png' % idx))
237
+ idx += 1
238
+ print('Extracted %d images.' % idx)
239
+
240
+ #----------------------------------------------------------------------------
241
+
242
+ def compare(tfrecord_dir_a, tfrecord_dir_b, ignore_labels):
243
+ max_label_size = 0 if ignore_labels else 'full'
244
+ print('Loading dataset "%s"' % tfrecord_dir_a)
245
+ tfutil.init_tf({'gpu_options.allow_growth': True})
246
+ dset_a = dataset.TFRecordDataset(tfrecord_dir_a, max_label_size=max_label_size, repeat=False, shuffle_mb=0)
247
+ print('Loading dataset "%s"' % tfrecord_dir_b)
248
+ dset_b = dataset.TFRecordDataset(tfrecord_dir_b, max_label_size=max_label_size, repeat=False, shuffle_mb=0)
249
+ tfutil.init_uninited_vars()
250
+
251
+ print('Comparing datasets')
252
+ idx = 0
253
+ identical_images = 0
254
+ identical_labels = 0
255
+ while True:
256
+ if idx % 100 == 0:
257
+ print('%d\r' % idx, end='', flush=True)
258
+ try:
259
+ images_a, labels_a = dset_a.get_minibatch_np(1)
260
+ except tf.errors.OutOfRangeError:
261
+ images_a, labels_a = None, None
262
+ try:
263
+ images_b, labels_b = dset_b.get_minibatch_np(1)
264
+ except tf.errors.OutOfRangeError:
265
+ images_b, labels_b = None, None
266
+ if images_a is None or images_b is None:
267
+ if images_a is not None or images_b is not None:
268
+ print('Datasets contain different number of images')
269
+ break
270
+ if images_a.shape == images_b.shape and np.all(images_a == images_b):
271
+ identical_images += 1
272
+ else:
273
+ print('Image %d is different' % idx)
274
+ if labels_a.shape == labels_b.shape and np.all(labels_a == labels_b):
275
+ identical_labels += 1
276
+ else:
277
+ print('Label %d is different' % idx)
278
+ idx += 1
279
+ print('Identical images: %d / %d' % (identical_images, idx))
280
+ if not ignore_labels:
281
+ print('Identical labels: %d / %d' % (identical_labels, idx))
282
+
283
+ #----------------------------------------------------------------------------
284
+
285
+ def create_mnist(tfrecord_dir, mnist_dir):
286
+ print('Loading MNIST from "%s"' % mnist_dir)
287
+ import gzip
288
+ with gzip.open(os.path.join(mnist_dir, 'train-images-idx3-ubyte.gz'), 'rb') as file:
289
+ images = np.frombuffer(file.read(), np.uint8, offset=16)
290
+ with gzip.open(os.path.join(mnist_dir, 'train-labels-idx1-ubyte.gz'), 'rb') as file:
291
+ labels = np.frombuffer(file.read(), np.uint8, offset=8)
292
+ images = images.reshape(-1, 1, 28, 28)
293
+ images = np.pad(images, [(0,0), (0,0), (2,2), (2,2)], 'constant', constant_values=0)
294
+ assert images.shape == (60000, 1, 32, 32) and images.dtype == np.uint8
295
+ assert labels.shape == (60000,) and labels.dtype == np.uint8
296
+ assert np.min(images) == 0 and np.max(images) == 255
297
+ assert np.min(labels) == 0 and np.max(labels) == 9
298
+ onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)
299
+ onehot[np.arange(labels.size), labels] = 1.0
300
+
301
+ with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:
302
+ order = tfr.choose_shuffled_order()
303
+ for idx in range(order.size):
304
+ tfr.add_image(images[order[idx]])
305
+ tfr.add_labels(onehot[order])
306
+
307
+ #----------------------------------------------------------------------------
308
+
309
+ def create_mnistrgb(tfrecord_dir, mnist_dir, num_images=1000000, random_seed=123):
310
+ print('Loading MNIST from "%s"' % mnist_dir)
311
+ import gzip
312
+ with gzip.open(os.path.join(mnist_dir, 'train-images-idx3-ubyte.gz'), 'rb') as file:
313
+ images = np.frombuffer(file.read(), np.uint8, offset=16)
314
+ images = images.reshape(-1, 28, 28)
315
+ images = np.pad(images, [(0,0), (2,2), (2,2)], 'constant', constant_values=0)
316
+ assert images.shape == (60000, 32, 32) and images.dtype == np.uint8
317
+ assert np.min(images) == 0 and np.max(images) == 255
318
+
319
+ with TFRecordExporter(tfrecord_dir, num_images) as tfr:
320
+ rnd = np.random.RandomState(random_seed)
321
+ for idx in range(num_images):
322
+ tfr.add_image(images[rnd.randint(images.shape[0], size=3)])
323
+
324
+ #----------------------------------------------------------------------------
325
+
326
+ def create_cifar10(tfrecord_dir, cifar10_dir):
327
+ print('Loading CIFAR-10 from "%s"' % cifar10_dir)
328
+ import pickle
329
+ images = []
330
+ labels = []
331
+ for batch in range(1, 6):
332
+ with open(os.path.join(cifar10_dir, 'data_batch_%d' % batch), 'rb') as file:
333
+ data = pickle.load(file, encoding='latin1')
334
+ images.append(data['data'].reshape(-1, 3, 32, 32))
335
+ labels.append(data['labels'])
336
+ images = np.concatenate(images)
337
+ labels = np.concatenate(labels)
338
+ assert images.shape == (50000, 3, 32, 32) and images.dtype == np.uint8
339
+ assert labels.shape == (50000,) and labels.dtype == np.int32
340
+ assert np.min(images) == 0 and np.max(images) == 255
341
+ assert np.min(labels) == 0 and np.max(labels) == 9
342
+ onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)
343
+ onehot[np.arange(labels.size), labels] = 1.0
344
+
345
+ with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:
346
+ order = tfr.choose_shuffled_order()
347
+ for idx in range(order.size):
348
+ tfr.add_image(images[order[idx]])
349
+ tfr.add_labels(onehot[order])
350
+
351
+ #----------------------------------------------------------------------------
352
+
353
+ def create_cifar100(tfrecord_dir, cifar100_dir):
354
+ print('Loading CIFAR-100 from "%s"' % cifar100_dir)
355
+ import pickle
356
+ with open(os.path.join(cifar100_dir, 'train'), 'rb') as file:
357
+ data = pickle.load(file, encoding='latin1')
358
+ images = data['data'].reshape(-1, 3, 32, 32)
359
+ labels = np.array(data['fine_labels'])
360
+ assert images.shape == (50000, 3, 32, 32) and images.dtype == np.uint8
361
+ assert labels.shape == (50000,) and labels.dtype == np.int32
362
+ assert np.min(images) == 0 and np.max(images) == 255
363
+ assert np.min(labels) == 0 and np.max(labels) == 99
364
+ onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)
365
+ onehot[np.arange(labels.size), labels] = 1.0
366
+
367
+ with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:
368
+ order = tfr.choose_shuffled_order()
369
+ for idx in range(order.size):
370
+ tfr.add_image(images[order[idx]])
371
+ tfr.add_labels(onehot[order])
372
+
373
+ #----------------------------------------------------------------------------
374
+
375
+ def create_svhn(tfrecord_dir, svhn_dir):
376
+ print('Loading SVHN from "%s"' % svhn_dir)
377
+ import pickle
378
+ images = []
379
+ labels = []
380
+ for batch in range(1, 4):
381
+ with open(os.path.join(svhn_dir, 'train_%d.pkl' % batch), 'rb') as file:
382
+ data = pickle.load(file, encoding='latin1')
383
+ images.append(data[0])
384
+ labels.append(data[1])
385
+ images = np.concatenate(images)
386
+ labels = np.concatenate(labels)
387
+ assert images.shape == (73257, 3, 32, 32) and images.dtype == np.uint8
388
+ assert labels.shape == (73257,) and labels.dtype == np.uint8
389
+ assert np.min(images) == 0 and np.max(images) == 255
390
+ assert np.min(labels) == 0 and np.max(labels) == 9
391
+ onehot = np.zeros((labels.size, np.max(labels) + 1), dtype=np.float32)
392
+ onehot[np.arange(labels.size), labels] = 1.0
393
+
394
+ with TFRecordExporter(tfrecord_dir, images.shape[0]) as tfr:
395
+ order = tfr.choose_shuffled_order()
396
+ for idx in range(order.size):
397
+ tfr.add_image(images[order[idx]])
398
+ tfr.add_labels(onehot[order])
399
+
400
+ #----------------------------------------------------------------------------
401
+
402
+ def create_lsun(tfrecord_dir, lmdb_dir, resolution=256, max_images=None):
403
+ print('Loading LSUN dataset from "%s"' % lmdb_dir)
404
+ import lmdb # pip install lmdb
405
+ import cv2 # pip install opencv-python
406
+ import io
407
+ with lmdb.open(lmdb_dir, readonly=True).begin(write=False) as txn:
408
+ total_images = txn.stat()['entries']
409
+ if max_images is None:
410
+ max_images = total_images
411
+ with TFRecordExporter(tfrecord_dir, max_images) as tfr:
412
+ for idx, (key, value) in enumerate(txn.cursor()):
413
+ try:
414
+ try:
415
+ img = cv2.imdecode(np.fromstring(value, dtype=np.uint8), 1)
416
+ if img is None:
417
+ raise IOError('cv2.imdecode failed')
418
+ img = img[:, :, ::-1] # BGR => RGB
419
+ except IOError:
420
+ img = np.asarray(PIL.Image.open(io.BytesIO(value)))
421
+ crop = np.min(img.shape[:2])
422
+ img = img[(img.shape[0] - crop) // 2 : (img.shape[0] + crop) // 2, (img.shape[1] - crop) // 2 : (img.shape[1] + crop) // 2]
423
+ img = PIL.Image.fromarray(img, 'RGB')
424
+ img = img.resize((resolution, resolution), PIL.Image.ANTIALIAS)
425
+ img = np.asarray(img)
426
+ img = img.transpose(2, 0, 1) # HWC => CHW
427
+ tfr.add_image(img)
428
+ except:
429
+ print(sys.exc_info()[1])
430
+ if tfr.cur_images == max_images:
431
+ break
432
+
433
+ #----------------------------------------------------------------------------
434
+
435
+ def create_celeba(tfrecord_dir, celeba_dir, cx=89, cy=121):
436
+ print('Loading CelebA from "%s"' % celeba_dir)
437
+ glob_pattern = os.path.join(celeba_dir, 'img_align_celeba_png', '*.png')
438
+ image_filenames = sorted(glob.glob(glob_pattern))
439
+ expected_images = 202599
440
+ if len(image_filenames) != expected_images:
441
+ error('Expected to find %d images' % expected_images)
442
+
443
+ with TFRecordExporter(tfrecord_dir, len(image_filenames)) as tfr:
444
+ order = tfr.choose_shuffled_order()
445
+ for idx in range(order.size):
446
+ img = np.asarray(PIL.Image.open(image_filenames[order[idx]]))
447
+ assert img.shape == (218, 178, 3)
448
+ img = img[cy - 64 : cy + 64, cx - 64 : cx + 64]
449
+ img = img.transpose(2, 0, 1) # HWC => CHW
450
+ tfr.add_image(img)
451
+
452
+ #----------------------------------------------------------------------------
453
+
454
+ def create_celebahq(tfrecord_dir, celeba_dir, delta_dir, num_threads=4, num_tasks=100):
455
+ print('Loading CelebA from "%s"' % celeba_dir)
456
+ expected_images = 202599
457
+ if len(glob.glob(os.path.join(celeba_dir, 'img_celeba', '*.jpg'))) != expected_images:
458
+ error('Expected to find %d images' % expected_images)
459
+ with open(os.path.join(celeba_dir, 'Anno', 'list_landmarks_celeba.txt'), 'rt') as file:
460
+ landmarks = [[float(value) for value in line.split()[1:]] for line in file.readlines()[2:]]
461
+ landmarks = np.float32(landmarks).reshape(-1, 5, 2)
462
+
463
+ print('Loading CelebA-HQ deltas from "%s"' % delta_dir)
464
+ import scipy.ndimage
465
+ import hashlib
466
+ import bz2
467
+ import zipfile
468
+ import base64
469
+ import cryptography.hazmat.primitives.hashes
470
+ import cryptography.hazmat.backends
471
+ import cryptography.hazmat.primitives.kdf.pbkdf2
472
+ import cryptography.fernet
473
+ expected_zips = 30
474
+ if len(glob.glob(os.path.join(delta_dir, 'delta*.zip'))) != expected_zips:
475
+ error('Expected to find %d zips' % expected_zips)
476
+ with open(os.path.join(delta_dir, 'image_list.txt'), 'rt') as file:
477
+ lines = [line.split() for line in file]
478
+ fields = dict()
479
+ for idx, field in enumerate(lines[0]):
480
+ type = int if field.endswith('idx') else str
481
+ fields[field] = [type(line[idx]) for line in lines[1:]]
482
+ indices = np.array(fields['idx'])
483
+
484
+ # Must use pillow version 3.1.1 for everything to work correctly.
485
+ if getattr(PIL, 'PILLOW_VERSION', '') != '3.1.1':
486
+ error('create_celebahq requires pillow version 3.1.1') # conda install pillow=3.1.1
487
+
488
+ # Must use libjpeg version 8d for everything to work correctly.
489
+ img = np.array(PIL.Image.open(os.path.join(celeba_dir, 'img_celeba', '000001.jpg')))
490
+ md5 = hashlib.md5()
491
+ md5.update(img.tobytes())
492
+ if md5.hexdigest() != '9cad8178d6cb0196b36f7b34bc5eb6d3':
493
+ error('create_celebahq requires libjpeg version 8d') # conda install jpeg=8d
494
+
495
+ def rot90(v):
496
+ return np.array([-v[1], v[0]])
497
+
498
+ def process_func(idx):
499
+ # Load original image.
500
+ orig_idx = fields['orig_idx'][idx]
501
+ orig_file = fields['orig_file'][idx]
502
+ orig_path = os.path.join(celeba_dir, 'img_celeba', orig_file)
503
+ img = PIL.Image.open(orig_path)
504
+
505
+ # Choose oriented crop rectangle.
506
+ lm = landmarks[orig_idx]
507
+ eye_avg = (lm[0] + lm[1]) * 0.5 + 0.5
508
+ mouth_avg = (lm[3] + lm[4]) * 0.5 + 0.5
509
+ eye_to_eye = lm[1] - lm[0]
510
+ eye_to_mouth = mouth_avg - eye_avg
511
+ x = eye_to_eye - rot90(eye_to_mouth)
512
+ x /= np.hypot(*x)
513
+ x *= max(np.hypot(*eye_to_eye) * 2.0, np.hypot(*eye_to_mouth) * 1.8)
514
+ y = rot90(x)
515
+ c = eye_avg + eye_to_mouth * 0.1
516
+ quad = np.stack([c - x - y, c - x + y, c + x + y, c + x - y])
517
+ zoom = 1024 / (np.hypot(*x) * 2)
518
+
519
+ # Shrink.
520
+ shrink = int(np.floor(0.5 / zoom))
521
+ if shrink > 1:
522
+ size = (int(np.round(float(img.size[0]) / shrink)), int(np.round(float(img.size[1]) / shrink)))
523
+ img = img.resize(size, PIL.Image.ANTIALIAS)
524
+ quad /= shrink
525
+ zoom *= shrink
526
+
527
+ # Crop.
528
+ border = max(int(np.round(1024 * 0.1 / zoom)), 3)
529
+ crop = (int(np.floor(min(quad[:,0]))), int(np.floor(min(quad[:,1]))), int(np.ceil(max(quad[:,0]))), int(np.ceil(max(quad[:,1]))))
530
+ crop = (max(crop[0] - border, 0), max(crop[1] - border, 0), min(crop[2] + border, img.size[0]), min(crop[3] + border, img.size[1]))
531
+ if crop[2] - crop[0] < img.size[0] or crop[3] - crop[1] < img.size[1]:
532
+ img = img.crop(crop)
533
+ quad -= crop[0:2]
534
+
535
+ # Simulate super-resolution.
536
+ superres = int(np.exp2(np.ceil(np.log2(zoom))))
537
+ if superres > 1:
538
+ img = img.resize((img.size[0] * superres, img.size[1] * superres), PIL.Image.ANTIALIAS)
539
+ quad *= superres
540
+ zoom /= superres
541
+
542
+ # Pad.
543
+ pad = (int(np.floor(min(quad[:,0]))), int(np.floor(min(quad[:,1]))), int(np.ceil(max(quad[:,0]))), int(np.ceil(max(quad[:,1]))))
544
+ pad = (max(-pad[0] + border, 0), max(-pad[1] + border, 0), max(pad[2] - img.size[0] + border, 0), max(pad[3] - img.size[1] + border, 0))
545
+ if max(pad) > border - 4:
546
+ pad = np.maximum(pad, int(np.round(1024 * 0.3 / zoom)))
547
+ img = np.pad(np.float32(img), ((pad[1], pad[3]), (pad[0], pad[2]), (0, 0)), 'reflect')
548
+ h, w, _ = img.shape
549
+ y, x, _ = np.mgrid[:h, :w, :1]
550
+ mask = 1.0 - np.minimum(np.minimum(np.float32(x) / pad[0], np.float32(y) / pad[1]), np.minimum(np.float32(w-1-x) / pad[2], np.float32(h-1-y) / pad[3]))
551
+ blur = 1024 * 0.02 / zoom
552
+ img += (scipy.ndimage.gaussian_filter(img, [blur, blur, 0]) - img) * np.clip(mask * 3.0 + 1.0, 0.0, 1.0)
553
+ img += (np.median(img, axis=(0,1)) - img) * np.clip(mask, 0.0, 1.0)
554
+ img = PIL.Image.fromarray(np.uint8(np.clip(np.round(img), 0, 255)), 'RGB')
555
+ quad += pad[0:2]
556
+
557
+ # Transform.
558
+ img = img.transform((4096, 4096), PIL.Image.QUAD, (quad + 0.5).flatten(), PIL.Image.BILINEAR)
559
+ img = img.resize((1024, 1024), PIL.Image.ANTIALIAS)
560
+ img = np.asarray(img).transpose(2, 0, 1)
561
+
562
+ # Verify MD5.
563
+ md5 = hashlib.md5()
564
+ md5.update(img.tobytes())
565
+ assert md5.hexdigest() == fields['proc_md5'][idx]
566
+
567
+ # Load delta image and original JPG.
568
+ with zipfile.ZipFile(os.path.join(delta_dir, 'deltas%05d.zip' % (idx - idx % 1000)), 'r') as zip:
569
+ delta_bytes = zip.read('delta%05d.dat' % idx)
570
+ with open(orig_path, 'rb') as file:
571
+ orig_bytes = file.read()
572
+
573
+ # Decrypt delta image, using original JPG data as decryption key.
574
+ algorithm = cryptography.hazmat.primitives.hashes.SHA256()
575
+ backend = cryptography.hazmat.backends.default_backend()
576
+ salt = bytes(orig_file, 'ascii')
577
+ kdf = cryptography.hazmat.primitives.kdf.pbkdf2.PBKDF2HMAC(algorithm=algorithm, length=32, salt=salt, iterations=100000, backend=backend)
578
+ key = base64.urlsafe_b64encode(kdf.derive(orig_bytes))
579
+ delta = np.frombuffer(bz2.decompress(cryptography.fernet.Fernet(key).decrypt(delta_bytes)), dtype=np.uint8).reshape(3, 1024, 1024)
580
+
581
+ # Apply delta image.
582
+ img = img + delta
583
+
584
+ # Verify MD5.
585
+ md5 = hashlib.md5()
586
+ md5.update(img.tobytes())
587
+ assert md5.hexdigest() == fields['final_md5'][idx]
588
+ return img
589
+
590
+ with TFRecordExporter(tfrecord_dir, indices.size) as tfr:
591
+ order = tfr.choose_shuffled_order()
592
+ with ThreadPool(num_threads) as pool:
593
+ for img in pool.process_items_concurrently(indices[order].tolist(), process_func=process_func, max_items_in_flight=num_tasks):
594
+ tfr.add_image(img)
595
+
596
+ #----------------------------------------------------------------------------
597
+
598
+ def create_from_images(tfrecord_dir, image_dir, shuffle):
599
+ print('Loading images from "%s"' % image_dir)
600
+ image_filenames = sorted(glob.glob(os.path.join(image_dir, '*')))
601
+ if len(image_filenames) == 0:
602
+ error('No input images found')
603
+
604
+ img = np.asarray(PIL.Image.open(image_filenames[0]))
605
+ resolution = img.shape[0]
606
+ channels = img.shape[2] if img.ndim == 3 else 1
607
+ if img.shape[1] != resolution:
608
+ error('Input images must have the same width and height')
609
+ if resolution != 2 ** int(np.floor(np.log2(resolution))):
610
+ error('Input image resolution must be a power-of-two')
611
+ if channels not in [1, 3]:
612
+ error('Input images must be stored as RGB or grayscale')
613
+
614
+ with TFRecordExporter(tfrecord_dir, len(image_filenames)) as tfr:
615
+ order = tfr.choose_shuffled_order() if shuffle else np.arange(len(image_filenames))
616
+ for idx in range(order.size):
617
+ img = np.asarray(PIL.Image.open(image_filenames[order[idx]]))
618
+ if channels == 1:
619
+ img = img[np.newaxis, :, :] # HW => CHW
620
+ else:
621
+ img = img.transpose(2, 0, 1) # HWC => CHW
622
+ tfr.add_image(img)
623
+
624
+ #----------------------------------------------------------------------------
625
+
626
+ def create_from_hdf5(tfrecord_dir, hdf5_filename, shuffle):
627
+ print('Loading HDF5 archive from "%s"' % hdf5_filename)
628
+ import h5py # conda install h5py
629
+ with h5py.File(hdf5_filename, 'r') as hdf5_file:
630
+ hdf5_data = max([value for key, value in hdf5_file.items() if key.startswith('data')], key=lambda lod: lod.shape[3])
631
+ with TFRecordExporter(tfrecord_dir, hdf5_data.shape[0]) as tfr:
632
+ order = tfr.choose_shuffled_order() if shuffle else np.arange(hdf5_data.shape[0])
633
+ for idx in range(order.size):
634
+ tfr.add_image(hdf5_data[order[idx]])
635
+ npy_filename = os.path.splitext(hdf5_filename)[0] + '-labels.npy'
636
+ if os.path.isfile(npy_filename):
637
+ tfr.add_labels(np.load(npy_filename)[order])
638
+
639
+ #----------------------------------------------------------------------------
640
+
641
+ def execute_cmdline(argv):
642
+ prog = argv[0]
643
+ parser = argparse.ArgumentParser(
644
+ prog = prog,
645
+ description = 'Tool for creating, extracting, and visualizing Progressive GAN datasets.',
646
+ epilog = 'Type "%s <command> -h" for more information.' % prog)
647
+
648
+ subparsers = parser.add_subparsers(dest='command')
649
+ subparsers.required = True
650
+ def add_command(cmd, desc, example=None):
651
+ epilog = 'Example: %s %s' % (prog, example) if example is not None else None
652
+ return subparsers.add_parser(cmd, description=desc, help=desc, epilog=epilog)
653
+
654
+ p = add_command( 'display', 'Display images in dataset.',
655
+ 'display datasets/mnist')
656
+ p.add_argument( 'tfrecord_dir', help='Directory containing dataset')
657
+
658
+ p = add_command( 'extract', 'Extract images from dataset.',
659
+ 'extract datasets/mnist mnist-images')
660
+ p.add_argument( 'tfrecord_dir', help='Directory containing dataset')
661
+ p.add_argument( 'output_dir', help='Directory to extract the images into')
662
+
663
+ p = add_command( 'compare', 'Compare two datasets.',
664
+ 'compare datasets/mydataset datasets/mnist')
665
+ p.add_argument( 'tfrecord_dir_a', help='Directory containing first dataset')
666
+ p.add_argument( 'tfrecord_dir_b', help='Directory containing second dataset')
667
+ p.add_argument( '--ignore_labels', help='Ignore labels (default: 0)', type=int, default=0)
668
+
669
+ p = add_command( 'create_mnist', 'Create dataset for MNIST.',
670
+ 'create_mnist datasets/mnist ~/downloads/mnist')
671
+ p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
672
+ p.add_argument( 'mnist_dir', help='Directory containing MNIST')
673
+
674
+ p = add_command( 'create_mnistrgb', 'Create dataset for MNIST-RGB.',
675
+ 'create_mnistrgb datasets/mnistrgb ~/downloads/mnist')
676
+ p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
677
+ p.add_argument( 'mnist_dir', help='Directory containing MNIST')
678
+ p.add_argument( '--num_images', help='Number of composite images to create (default: 1000000)', type=int, default=1000000)
679
+ p.add_argument( '--random_seed', help='Random seed (default: 123)', type=int, default=123)
680
+
681
+ p = add_command( 'create_cifar10', 'Create dataset for CIFAR-10.',
682
+ 'create_cifar10 datasets/cifar10 ~/downloads/cifar10')
683
+ p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
684
+ p.add_argument( 'cifar10_dir', help='Directory containing CIFAR-10')
685
+
686
+ p = add_command( 'create_cifar100', 'Create dataset for CIFAR-100.',
687
+ 'create_cifar100 datasets/cifar100 ~/downloads/cifar100')
688
+ p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
689
+ p.add_argument( 'cifar100_dir', help='Directory containing CIFAR-100')
690
+
691
+ p = add_command( 'create_svhn', 'Create dataset for SVHN.',
692
+ 'create_svhn datasets/svhn ~/downloads/svhn')
693
+ p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
694
+ p.add_argument( 'svhn_dir', help='Directory containing SVHN')
695
+
696
+ p = add_command( 'create_lsun', 'Create dataset for single LSUN category.',
697
+ 'create_lsun datasets/lsun-car-100k ~/downloads/lsun/car_lmdb --resolution 256 --max_images 100000')
698
+ p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
699
+ p.add_argument( 'lmdb_dir', help='Directory containing LMDB database')
700
+ p.add_argument( '--resolution', help='Output resolution (default: 256)', type=int, default=256)
701
+ p.add_argument( '--max_images', help='Maximum number of images (default: none)', type=int, default=None)
702
+
703
+ p = add_command( 'create_celeba', 'Create dataset for CelebA.',
704
+ 'create_celeba datasets/celeba ~/downloads/celeba')
705
+ p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
706
+ p.add_argument( 'celeba_dir', help='Directory containing CelebA')
707
+ p.add_argument( '--cx', help='Center X coordinate (default: 89)', type=int, default=89)
708
+ p.add_argument( '--cy', help='Center Y coordinate (default: 121)', type=int, default=121)
709
+
710
+ p = add_command( 'create_celebahq', 'Create dataset for CelebA-HQ.',
711
+ 'create_celebahq datasets/celebahq ~/downloads/celeba ~/downloads/celeba-hq-deltas')
712
+ p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
713
+ p.add_argument( 'celeba_dir', help='Directory containing CelebA')
714
+ p.add_argument( 'delta_dir', help='Directory containing CelebA-HQ deltas')
715
+ p.add_argument( '--num_threads', help='Number of concurrent threads (default: 4)', type=int, default=4)
716
+ p.add_argument( '--num_tasks', help='Number of concurrent processing tasks (default: 100)', type=int, default=100)
717
+
718
+ p = add_command( 'create_from_images', 'Create dataset from a directory full of images.',
719
+ 'create_from_images datasets/mydataset myimagedir')
720
+ p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
721
+ p.add_argument( 'image_dir', help='Directory containing the images')
722
+ p.add_argument( '--shuffle', help='Randomize image order (default: 1)', type=int, default=1)
723
+
724
+ p = add_command( 'create_from_hdf5', 'Create dataset from legacy HDF5 archive.',
725
+ 'create_from_hdf5 datasets/celebahq ~/downloads/celeba-hq-1024x1024.h5')
726
+ p.add_argument( 'tfrecord_dir', help='New dataset directory to be created')
727
+ p.add_argument( 'hdf5_filename', help='HDF5 archive containing the images')
728
+ p.add_argument( '--shuffle', help='Randomize image order (default: 1)', type=int, default=1)
729
+
730
+ args = parser.parse_args(argv[1:] if len(argv) > 1 else ['-h'])
731
+ func = globals()[args.command]
732
+ del args.command
733
+ func(**vars(args))
734
+
735
+ #----------------------------------------------------------------------------
736
+
737
+ if __name__ == "__main__":
738
+ execute_cmdline(sys.argv)
739
+
740
+ #----------------------------------------------------------------------------
EEGFaceSem/pgan/legacy.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # This work is licensed under the Creative Commons Attribution-NonCommercial
4
+ # 4.0 International License. To view a copy of this license, visit
5
+
6
+ # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
7
+
8
+ import pickle
9
+ import inspect
10
+ import numpy as np
11
+
12
+ import tfutil
13
+ import networks
14
+
15
+ #----------------------------------------------------------------------------
16
+ # Custom unpickler that is able to load network pickles produced by
17
+ # the old Theano implementation.
18
+
19
+ class LegacyUnpickler(pickle.Unpickler):
20
+ def __init__(self, *args, **kwargs):
21
+ super().__init__(*args, **kwargs)
22
+
23
+ def find_class(self, module, name):
24
+ if module == 'network' and name == 'Network':
25
+ return tfutil.Network
26
+ return super().find_class(module, name)
27
+
28
+ #----------------------------------------------------------------------------
29
+ # Import handler for tfutil.Network that silently converts networks produced
30
+ # by the old Theano implementation to a suitable format.
31
+
32
+ theano_gan_remap = {
33
+ 'G_paper': 'G_paper',
34
+ 'G_progressive_8': 'G_paper',
35
+ 'D_paper': 'D_paper',
36
+ 'D_progressive_8': 'D_paper'}
37
+
38
+ def patch_theano_gan(state):
39
+ if 'version' in state or state['build_func_spec']['func'] not in theano_gan_remap:
40
+ return state
41
+
42
+ spec = dict(state['build_func_spec'])
43
+ func = spec.pop('func')
44
+ resolution = spec.get('resolution', 32)
45
+ resolution_log2 = int(np.log2(resolution))
46
+ use_wscale = spec.get('use_wscale', True)
47
+
48
+ assert spec.pop('label_size', 0) == 0
49
+ assert spec.pop('use_batchnorm', False) == False
50
+ assert spec.pop('tanh_at_end', None) is None
51
+ assert spec.pop('mbstat_func', 'Tstdeps') == 'Tstdeps'
52
+ assert spec.pop('mbstat_avg', 'all') == 'all'
53
+ assert spec.pop('mbdisc_kernels', None) is None
54
+ spec.pop( 'use_gdrop', True) # doesn't make a difference
55
+ assert spec.pop('use_layernorm', False) == False
56
+ spec[ 'fused_scale'] = False
57
+ spec[ 'mbstd_group_size'] = 16
58
+
59
+ vars = []
60
+ param_iter = iter(state['param_values'])
61
+ relu = np.sqrt(2); linear = 1.0
62
+ def flatten2(w): return w.reshape(w.shape[0], -1)
63
+ def he_std(gain, w): return gain / np.sqrt(np.prod(w.shape[:-1]))
64
+ def wscale(gain, w): return w * next(param_iter) / he_std(gain, w) if use_wscale else w
65
+ def layer(name, gain, w): return [(name + '/weight', wscale(gain, w)), (name + '/bias', next(param_iter))]
66
+
67
+ if func.startswith('G'):
68
+ vars += layer('4x4/Dense', relu/4, flatten2(next(param_iter).transpose(1,0,2,3)))
69
+ vars += layer('4x4/Conv', relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1])
70
+ for res in range(3, resolution_log2 + 1):
71
+ vars += layer('%dx%d/Conv0' % (2**res, 2**res), relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1])
72
+ vars += layer('%dx%d/Conv1' % (2**res, 2**res), relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1])
73
+ for lod in range(0, resolution_log2 - 1):
74
+ vars += layer('ToRGB_lod%d' % lod, linear, next(param_iter)[np.newaxis, np.newaxis])
75
+
76
+ if func.startswith('D'):
77
+ vars += layer('FromRGB_lod0', relu, next(param_iter)[np.newaxis, np.newaxis])
78
+ for res in range(resolution_log2, 2, -1):
79
+ vars += layer('%dx%d/Conv0' % (2**res, 2**res), relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1])
80
+ vars += layer('%dx%d/Conv1' % (2**res, 2**res), relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1])
81
+ vars += layer('FromRGB_lod%d' % (resolution_log2 - (res - 1)), relu, next(param_iter)[np.newaxis, np.newaxis])
82
+ vars += layer('4x4/Conv', relu, next(param_iter).transpose(2,3,1,0)[::-1,::-1])
83
+ vars += layer('4x4/Dense0', relu, flatten2(next(param_iter)[:,:,::-1,::-1]).transpose())
84
+ vars += layer('4x4/Dense1', linear, next(param_iter))
85
+
86
+ vars += [('lod', state['toplevel_params']['cur_lod'])]
87
+
88
+ return {
89
+ 'version': 2,
90
+ 'name': func,
91
+ 'build_module_src': inspect.getsource(networks),
92
+ 'build_func_name': theano_gan_remap[func],
93
+ 'static_kwargs': spec,
94
+ 'variables': vars}
95
+
96
+ tfutil.network_import_handlers.append(patch_theano_gan)
97
+
98
+ #----------------------------------------------------------------------------
99
+ # Import handler for tfutil.Network that ignores unsupported/deprecated
100
+ # networks produced by older versions of the code.
101
+
102
+ def ignore_unknown_theano_network(state):
103
+ if 'version' in state:
104
+ return state
105
+
106
+ print('Ignoring unknown Theano network:', state['build_func_spec']['func'])
107
+ return {
108
+ 'version': 2,
109
+ 'name': 'Dummy',
110
+ 'build_module_src': 'def dummy(input, **kwargs): input.set_shape([None, 1]); return input',
111
+ 'build_func_name': 'dummy',
112
+ 'static_kwargs': {},
113
+ 'variables': []}
114
+
115
+ tfutil.network_import_handlers.append(ignore_unknown_theano_network)
116
+
117
+ #----------------------------------------------------------------------------
EEGFaceSem/pgan/loss.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # This work is licensed under the Creative Commons Attribution-NonCommercial
4
+ # 4.0 International License. To view a copy of this license, visit
5
+
6
+ # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
7
+
8
+ import numpy as np
9
+ import tensorflow as tf
10
+
11
+ import tfutil
12
+
13
+ #----------------------------------------------------------------------------
14
+ # Convenience func that casts all of its arguments to tf.float32.
15
+
16
+ def fp32(*values):
17
+ if len(values) == 1 and isinstance(values[0], tuple):
18
+ values = values[0]
19
+ values = tuple(tf.cast(v, tf.float32) for v in values)
20
+ return values if len(values) >= 2 else values[0]
21
+
22
+ #----------------------------------------------------------------------------
23
+ # Generator loss function used in the paper (WGAN + AC-GAN).
24
+
25
+ def G_wgan_acgan(G, D, opt, training_set, minibatch_size,
26
+ cond_weight = 1.0): # Weight of the conditioning term.
27
+
28
+ latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:])
29
+ labels = training_set.get_random_labels_tf(minibatch_size)
30
+ fake_images_out = G.get_output_for(latents, labels, is_training=True)
31
+ fake_scores_out, fake_labels_out = fp32(D.get_output_for(fake_images_out, is_training=True))
32
+ loss = -fake_scores_out
33
+
34
+ if D.output_shapes[1][1] > 0:
35
+ with tf.name_scope('LabelPenalty'):
36
+ label_penalty_fakes = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=fake_labels_out)
37
+ loss += label_penalty_fakes * cond_weight
38
+ return loss
39
+
40
+ #----------------------------------------------------------------------------
41
+ # Discriminator loss function used in the paper (WGAN-GP + AC-GAN).
42
+
43
+ def D_wgangp_acgan(G, D, opt, training_set, minibatch_size, reals, labels,
44
+ wgan_lambda = 10.0, # Weight for the gradient penalty term.
45
+ wgan_epsilon = 0.001, # Weight for the epsilon term, \epsilon_{drift}.
46
+ wgan_target = 1.0, # Target value for gradient magnitudes.
47
+ cond_weight = 1.0): # Weight of the conditioning terms.
48
+
49
+ latents = tf.random_normal([minibatch_size] + G.input_shapes[0][1:])
50
+ fake_images_out = G.get_output_for(latents, labels, is_training=True)
51
+ real_scores_out, real_labels_out = fp32(D.get_output_for(reals, is_training=True))
52
+ fake_scores_out, fake_labels_out = fp32(D.get_output_for(fake_images_out, is_training=True))
53
+ real_scores_out = tfutil.autosummary('Loss/real_scores', real_scores_out)
54
+ fake_scores_out = tfutil.autosummary('Loss/fake_scores', fake_scores_out)
55
+ loss = fake_scores_out - real_scores_out
56
+
57
+ with tf.name_scope('GradientPenalty'):
58
+ mixing_factors = tf.random_uniform([minibatch_size, 1, 1, 1], 0.0, 1.0, dtype=fake_images_out.dtype)
59
+ mixed_images_out = tfutil.lerp(tf.cast(reals, fake_images_out.dtype), fake_images_out, mixing_factors)
60
+ mixed_scores_out, mixed_labels_out = fp32(D.get_output_for(mixed_images_out, is_training=True))
61
+ mixed_scores_out = tfutil.autosummary('Loss/mixed_scores', mixed_scores_out)
62
+ mixed_loss = opt.apply_loss_scaling(tf.reduce_sum(mixed_scores_out))
63
+ mixed_grads = opt.undo_loss_scaling(fp32(tf.gradients(mixed_loss, [mixed_images_out])[0]))
64
+ mixed_norms = tf.sqrt(tf.reduce_sum(tf.square(mixed_grads), axis=[1,2,3]))
65
+ mixed_norms = tfutil.autosummary('Loss/mixed_norms', mixed_norms)
66
+ gradient_penalty = tf.square(mixed_norms - wgan_target)
67
+ loss += gradient_penalty * (wgan_lambda / (wgan_target**2))
68
+
69
+ with tf.name_scope('EpsilonPenalty'):
70
+ epsilon_penalty = tfutil.autosummary('Loss/epsilon_penalty', tf.square(real_scores_out))
71
+ loss += epsilon_penalty * wgan_epsilon
72
+
73
+ if D.output_shapes[1][1] > 0:
74
+ with tf.name_scope('LabelPenalty'):
75
+ label_penalty_reals = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=real_labels_out)
76
+ label_penalty_fakes = tf.nn.softmax_cross_entropy_with_logits_v2(labels=labels, logits=fake_labels_out)
77
+ label_penalty_reals = tfutil.autosummary('Loss/label_penalty_reals', label_penalty_reals)
78
+ label_penalty_fakes = tfutil.autosummary('Loss/label_penalty_fakes', label_penalty_fakes)
79
+ loss += (label_penalty_reals + label_penalty_fakes) * cond_weight
80
+ return loss
81
+
82
+ #----------------------------------------------------------------------------
EEGFaceSem/pgan/misc.py ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # This work is licensed under the Creative Commons Attribution-NonCommercial
4
+ # 4.0 International License. To view a copy of this license, visit
5
+
6
+ # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
7
+
8
+ import os
9
+ import sys
10
+ import glob
11
+ import datetime
12
+ import pickle
13
+ import re
14
+ import numpy as np
15
+ from collections import OrderedDict
16
+ import scipy.ndimage
17
+ import PIL.Image
18
+
19
+ import config
20
+ import dataset
21
+ import legacy
22
+
23
+ #----------------------------------------------------------------------------
24
+ # Convenience wrappers for pickle that are able to load data produced by
25
+ # older versions of the code.
26
+
27
+ def load_pkl(filename):
28
+ with open(filename, 'rb') as file:
29
+ return legacy.LegacyUnpickler(file, encoding='latin1').load()
30
+
31
+ def save_pkl(obj, filename):
32
+ with open(filename, 'wb') as file:
33
+ pickle.dump(obj, file, protocol=pickle.HIGHEST_PROTOCOL)
34
+
35
+ #----------------------------------------------------------------------------
36
+ # Image utils.
37
+
38
+ def adjust_dynamic_range(data, drange_in, drange_out):
39
+ if drange_in != drange_out:
40
+ scale = (np.float32(drange_out[1]) - np.float32(drange_out[0])) / (np.float32(drange_in[1]) - np.float32(drange_in[0]))
41
+ bias = (np.float32(drange_out[0]) - np.float32(drange_in[0]) * scale)
42
+ data = data * scale + bias
43
+ return data
44
+
45
+ def create_image_grid(images, grid_size=None):
46
+ assert images.ndim == 3 or images.ndim == 4
47
+ num, img_w, img_h = images.shape[0], images.shape[-1], images.shape[-2]
48
+
49
+ if grid_size is not None:
50
+ grid_w, grid_h = tuple(grid_size)
51
+ else:
52
+ grid_w = max(int(np.ceil(np.sqrt(num))), 1)
53
+ grid_h = max((num - 1) // grid_w + 1, 1)
54
+
55
+ grid = np.zeros(list(images.shape[1:-2]) + [grid_h * img_h, grid_w * img_w], dtype=images.dtype)
56
+ for idx in range(num):
57
+ x = (idx % grid_w) * img_w
58
+ y = (idx // grid_w) * img_h
59
+ grid[..., y : y + img_h, x : x + img_w] = images[idx]
60
+ return grid
61
+
62
+ def convert_to_pil_image(image, drange=[0,1]):
63
+ assert image.ndim == 2 or image.ndim == 3
64
+ if image.ndim == 3:
65
+ if image.shape[0] == 1:
66
+ image = image[0] # grayscale CHW => HW
67
+ else:
68
+ image = image.transpose(1, 2, 0) # CHW -> HWC
69
+
70
+ image = adjust_dynamic_range(image, drange, [0,255])
71
+ image = np.rint(image).clip(0, 255).astype(np.uint8)
72
+ format = 'RGB' if image.ndim == 3 else 'L'
73
+ return PIL.Image.fromarray(image, format)
74
+
75
+ def save_image(image, filename, drange=[0,1], quality=95):
76
+ img = convert_to_pil_image(image, drange)
77
+ if '.jpg' in filename:
78
+ img.save(filename,"JPEG", quality=quality, optimize=True)
79
+ else:
80
+ img.save(filename)
81
+
82
+ def save_image_grid(images, filename, drange=[0,1], grid_size=None):
83
+ convert_to_pil_image(create_image_grid(images, grid_size), drange).save(filename)
84
+
85
+ #----------------------------------------------------------------------------
86
+ # Logging of stdout and stderr to a file.
87
+
88
+ class OutputLogger(object):
89
+ def __init__(self):
90
+ self.file = None
91
+ self.buffer = ''
92
+
93
+ def set_log_file(self, filename, mode='wt'):
94
+ assert self.file is None
95
+ self.file = open(filename, mode)
96
+ if self.buffer is not None:
97
+ self.file.write(self.buffer)
98
+ self.buffer = None
99
+
100
+ def write(self, data):
101
+ if self.file is not None:
102
+ self.file.write(data)
103
+ if self.buffer is not None:
104
+ self.buffer += data
105
+
106
+ def flush(self):
107
+ if self.file is not None:
108
+ self.file.flush()
109
+
110
+ class TeeOutputStream(object):
111
+ def __init__(self, child_streams, autoflush=False):
112
+ self.child_streams = child_streams
113
+ self.autoflush = autoflush
114
+
115
+ def write(self, data):
116
+ for stream in self.child_streams:
117
+ stream.write(data)
118
+ if self.autoflush:
119
+ self.flush()
120
+
121
+ def flush(self):
122
+ for stream in self.child_streams:
123
+ stream.flush()
124
+
125
+ output_logger = None
126
+
127
+ def init_output_logging():
128
+ global output_logger
129
+ if output_logger is None:
130
+ output_logger = OutputLogger()
131
+ sys.stdout = TeeOutputStream([sys.stdout, output_logger], autoflush=True)
132
+ sys.stderr = TeeOutputStream([sys.stderr, output_logger], autoflush=True)
133
+
134
+ def set_output_log_file(filename, mode='wt'):
135
+ if output_logger is not None:
136
+ output_logger.set_log_file(filename, mode)
137
+
138
+ #----------------------------------------------------------------------------
139
+ # Reporting results.
140
+
141
+ def create_result_subdir(result_dir, desc):
142
+
143
+ # Select run ID and create subdir.
144
+ while True:
145
+ run_id = 0
146
+ for fname in glob.glob(os.path.join(result_dir, '*')):
147
+ try:
148
+ fbase = os.path.basename(fname)
149
+ ford = int(fbase[:fbase.find('-')])
150
+ run_id = max(run_id, ford + 1)
151
+ except ValueError:
152
+ pass
153
+
154
+ result_subdir = os.path.join(result_dir, '%03d-%s' % (run_id, desc))
155
+ try:
156
+ os.makedirs(result_subdir)
157
+ break
158
+ except OSError:
159
+ if os.path.isdir(result_subdir):
160
+ continue
161
+ raise
162
+
163
+ print("Saving results to", result_subdir)
164
+ set_output_log_file(os.path.join(result_subdir, 'log.txt'))
165
+
166
+ # Export config.
167
+ try:
168
+ with open(os.path.join(result_subdir, 'config.txt'), 'wt') as fout:
169
+ for k, v in sorted(config.__dict__.items()):
170
+ if not k.startswith('_'):
171
+ fout.write("%s = %s\n" % (k, str(v)))
172
+ except:
173
+ pass
174
+
175
+ return result_subdir
176
+
177
+ def format_time(seconds):
178
+ s = int(np.rint(seconds))
179
+ if s < 60: return '%ds' % (s)
180
+ elif s < 60*60: return '%dm %02ds' % (s // 60, s % 60)
181
+ elif s < 24*60*60: return '%dh %02dm %02ds' % (s // (60*60), (s // 60) % 60, s % 60)
182
+ else: return '%dd %02dh %02dm' % (s // (24*60*60), (s // (60*60)) % 24, (s // 60) % 60)
183
+
184
+ #----------------------------------------------------------------------------
185
+ # Locating results.
186
+
187
+ def locate_result_subdir(run_id_or_result_subdir):
188
+ if isinstance(run_id_or_result_subdir, str) and os.path.isdir(run_id_or_result_subdir):
189
+ return run_id_or_result_subdir
190
+
191
+ searchdirs = []
192
+ searchdirs += ['']
193
+ searchdirs += ['results']
194
+ searchdirs += ['networks']
195
+
196
+ for searchdir in searchdirs:
197
+ dir = config.result_dir if searchdir == '' else os.path.join(config.result_dir, searchdir)
198
+ dir = os.path.join(dir, str(run_id_or_result_subdir))
199
+ if os.path.isdir(dir):
200
+ return dir
201
+ prefix = '%03d' % run_id_or_result_subdir if isinstance(run_id_or_result_subdir, int) else str(run_id_or_result_subdir)
202
+ dirs = sorted(glob.glob(os.path.join(config.result_dir, searchdir, prefix + '-*')))
203
+ dirs = [dir for dir in dirs if os.path.isdir(dir)]
204
+ if len(dirs) == 1:
205
+ return dirs[0]
206
+ raise IOError('Cannot locate result subdir for run', run_id_or_result_subdir)
207
+
208
+ def list_network_pkls(run_id_or_result_subdir, include_final=True):
209
+ result_subdir = locate_result_subdir(run_id_or_result_subdir)
210
+ pkls = sorted(glob.glob(os.path.join(result_subdir, 'network-*.pkl')))
211
+ if len(pkls) >= 1 and os.path.basename(pkls[0]) == 'network-final.pkl':
212
+ if include_final:
213
+ pkls.append(pkls[0])
214
+ del pkls[0]
215
+ return pkls
216
+
217
+ def locate_network_pkl(run_id_or_result_subdir_or_network_pkl, snapshot=None):
218
+ if isinstance(run_id_or_result_subdir_or_network_pkl, str) and os.path.isfile(run_id_or_result_subdir_or_network_pkl):
219
+ return run_id_or_result_subdir_or_network_pkl
220
+
221
+ pkls = list_network_pkls(run_id_or_result_subdir_or_network_pkl)
222
+ if len(pkls) >= 1 and snapshot is None:
223
+ return pkls[-1]
224
+ for pkl in pkls:
225
+ try:
226
+ name = os.path.splitext(os.path.basename(pkl))[0]
227
+ number = int(name.split('-')[-1])
228
+ if number == snapshot:
229
+ return pkl
230
+ except ValueError: pass
231
+ except IndexError: pass
232
+ raise IOError('Cannot locate network pkl for snapshot', snapshot)
233
+
234
+ def get_id_string_for_network_pkl(network_pkl):
235
+ p = network_pkl.replace('.pkl', '').replace('\\', '/').split('/')
236
+ return '-'.join(p[max(len(p) - 2, 0):])
237
+
238
+ #----------------------------------------------------------------------------
239
+ # Loading and using trained networks.
240
+
241
+ def load_network_pkl(run_id_or_result_subdir_or_network_pkl, snapshot=None):
242
+ return load_pkl(locate_network_pkl(run_id_or_result_subdir_or_network_pkl, snapshot))
243
+
244
+ def random_latents(num_latents, G, random_state=None):
245
+ if random_state is not None:
246
+ return random_state.randn(num_latents, *G.input_shape[1:]).astype(np.float32)
247
+ else:
248
+ return np.random.randn(num_latents, *G.input_shape[1:]).astype(np.float32)
249
+
250
+ def load_dataset_for_previous_run(run_id, **kwargs): # => dataset_obj, mirror_augment
251
+ result_subdir = locate_result_subdir(run_id)
252
+
253
+ # Parse config.txt.
254
+ parsed_cfg = dict()
255
+ with open(os.path.join(result_subdir, 'config.txt'), 'rt') as f:
256
+ for line in f:
257
+ if line.startswith('dataset =') or line.startswith('train ='):
258
+ exec(line, parsed_cfg, parsed_cfg)
259
+ dataset_cfg = parsed_cfg.get('dataset', dict())
260
+ train_cfg = parsed_cfg.get('train', dict())
261
+ mirror_augment = train_cfg.get('mirror_augment', False)
262
+
263
+ # Handle legacy options.
264
+ if 'h5_path' in dataset_cfg:
265
+ dataset_cfg['tfrecord_dir'] = dataset_cfg.pop('h5_path').replace('.h5', '')
266
+ if 'mirror_augment' in dataset_cfg:
267
+ mirror_augment = dataset_cfg.pop('mirror_augment')
268
+ if 'max_labels' in dataset_cfg:
269
+ v = dataset_cfg.pop('max_labels')
270
+ if v is None: v = 0
271
+ if v == 'all': v = 'full'
272
+ dataset_cfg['max_label_size'] = v
273
+ if 'max_images' in dataset_cfg:
274
+ dataset_cfg.pop('max_images')
275
+
276
+ # Handle legacy dataset names.
277
+ v = dataset_cfg['tfrecord_dir']
278
+ v = v.replace('-32x32', '').replace('-32', '')
279
+ v = v.replace('-128x128', '').replace('-128', '')
280
+ v = v.replace('-256x256', '').replace('-256', '')
281
+ v = v.replace('-1024x1024', '').replace('-1024', '')
282
+ v = v.replace('celeba-hq', 'celebahq')
283
+ v = v.replace('cifar-10', 'cifar10')
284
+ v = v.replace('cifar-100', 'cifar100')
285
+ v = v.replace('mnist-rgb', 'mnistrgb')
286
+ v = re.sub('lsun-100k-([^-]*)', 'lsun-\\1-100k', v)
287
+ v = re.sub('lsun-full-([^-]*)', 'lsun-\\1-full', v)
288
+ dataset_cfg['tfrecord_dir'] = v
289
+
290
+ # Load dataset.
291
+ dataset_cfg.update(kwargs)
292
+ dataset_obj = dataset.load_dataset(data_dir=config.data_dir, **dataset_cfg)
293
+ return dataset_obj, mirror_augment
294
+
295
+ def apply_mirror_augment(minibatch):
296
+ mask = np.random.rand(minibatch.shape[0]) < 0.5
297
+ minibatch = np.array(minibatch)
298
+ minibatch[mask] = minibatch[mask, :, :, ::-1]
299
+ return minibatch
300
+
301
+ #----------------------------------------------------------------------------
302
+ # Text labels.
303
+
304
+ _text_label_cache = OrderedDict()
305
+
306
+ def draw_text_label(img, text, x, y, alignx=0.5, aligny=0.5, color=255, opacity=1.0, glow_opacity=1.0, **kwargs):
307
+ color = np.array(color).flatten().astype(np.float32)
308
+ assert img.ndim == 3 and img.shape[2] == color.size or color.size == 1
309
+ alpha, glow = setup_text_label(text, **kwargs)
310
+ xx, yy = int(np.rint(x - alpha.shape[1] * alignx)), int(np.rint(y - alpha.shape[0] * aligny))
311
+ xb, yb = max(-xx, 0), max(-yy, 0)
312
+ xe, ye = min(alpha.shape[1], img.shape[1] - xx), min(alpha.shape[0], img.shape[0] - yy)
313
+ img = np.array(img)
314
+ slice = img[yy+yb : yy+ye, xx+xb : xx+xe, :]
315
+ slice[:] = slice * (1.0 - (1.0 - (1.0 - alpha[yb:ye, xb:xe]) * (1.0 - glow[yb:ye, xb:xe] * glow_opacity)) * opacity)[:, :, np.newaxis]
316
+ slice[:] = slice + alpha[yb:ye, xb:xe, np.newaxis] * (color * opacity)[np.newaxis, np.newaxis, :]
317
+ return img
318
+
319
+ def setup_text_label(text, font='Calibri', fontsize=32, padding=6, glow_size=2.0, glow_coef=3.0, glow_exp=2.0, cache_size=100): # => (alpha, glow)
320
+ # Lookup from cache.
321
+ key = (text, font, fontsize, padding, glow_size, glow_coef, glow_exp)
322
+ if key in _text_label_cache:
323
+ value = _text_label_cache[key]
324
+ del _text_label_cache[key] # LRU policy
325
+ _text_label_cache[key] = value
326
+ return value
327
+
328
+ # Limit cache size.
329
+ while len(_text_label_cache) >= cache_size:
330
+ _text_label_cache.popitem(last=False)
331
+
332
+ # Render text.
333
+ import moviepy.editor # pip install moviepy
334
+ alpha = moviepy.editor.TextClip(text, font=font, fontsize=fontsize).mask.make_frame(0)
335
+ alpha = np.pad(alpha, padding, mode='constant', constant_values=0.0)
336
+ glow = scipy.ndimage.gaussian_filter(alpha, glow_size)
337
+ glow = 1.0 - np.maximum(1.0 - glow * glow_coef, 0.0) ** glow_exp
338
+
339
+ # Add to cache.
340
+ value = (alpha, glow)
341
+ _text_label_cache[key] = value
342
+ return value
343
+
344
+ #----------------------------------------------------------------------------
EEGFaceSem/pgan/networks.py ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # This work is licensed under the Creative Commons Attribution-NonCommercial
4
+ # 4.0 International License. To view a copy of this license, visit
5
+
6
+ # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
7
+
8
+ import numpy as np
9
+ import tensorflow.compat.v1 as tf
10
+ tf.disable_v2_behavior()
11
+
12
+ # NOTE: Do not import any application-specific modules here!
13
+
14
+ #----------------------------------------------------------------------------
15
+
16
+ def lerp(a, b, t): return a + (b - a) * t
17
+ def lerp_clip(a, b, t): return a + (b - a) * tf.clip_by_value(t, 0.0, 1.0)
18
+ def cset(cur_lambda, new_cond, new_lambda): return lambda: tf.cond(new_cond, new_lambda, cur_lambda)
19
+
20
+ #----------------------------------------------------------------------------
21
+ # Get/create weight tensor for a convolutional or fully-connected layer.
22
+
23
+ def get_weight(shape, gain=np.sqrt(2), use_wscale=False, fan_in=None):
24
+ if fan_in is None: fan_in = np.prod(shape[:-1])
25
+ std = gain / np.sqrt(fan_in) # He init
26
+ if use_wscale:
27
+ wscale = tf.constant(np.float32(std), name='wscale')
28
+ return tf.compat.v1.get_variable('weight', shape=shape, initializer=tf.initializers.random_normal()) * wscale
29
+ else:
30
+ return tf.compat.v1.get_variable('weight', shape=shape, initializer=tf.initializers.random_normal(0, std))
31
+
32
+ #----------------------------------------------------------------------------
33
+ # Fully-connected layer.
34
+
35
+ def dense(x, fmaps, gain=np.sqrt(2), use_wscale=False):
36
+ if len(x.shape) > 2:
37
+ x = tf.reshape(x, [-1, np.prod([d.value for d in x.shape[1:]])])
38
+ w = get_weight([x.shape[1].value, fmaps], gain=gain, use_wscale=use_wscale)
39
+ w = tf.cast(w, x.dtype)
40
+ return tf.matmul(x, w)
41
+
42
+ #----------------------------------------------------------------------------
43
+ # Convolutional layer.
44
+
45
+ def conv2d(x, fmaps, kernel, gain=np.sqrt(2), use_wscale=False):
46
+ assert kernel >= 1 and kernel % 2 == 1
47
+ w = get_weight([kernel, kernel, x.shape[1].value, fmaps], gain=gain, use_wscale=use_wscale)
48
+ w = tf.cast(w, x.dtype)
49
+ return tf.nn.conv2d(x, w, strides=[1,1,1,1], padding='SAME', data_format='NCHW')
50
+
51
+ #----------------------------------------------------------------------------
52
+ # Apply bias to the given activation tensor.
53
+
54
+ def apply_bias(x):
55
+ b = tf.compat.v1.get_variable('bias', shape=[x.shape[1]], initializer=tf.initializers.zeros())
56
+ b = tf.cast(b, x.dtype)
57
+ if len(x.shape) == 2:
58
+ return x + b
59
+ else:
60
+ return x + tf.reshape(b, [1, -1, 1, 1])
61
+
62
+ #----------------------------------------------------------------------------
63
+ # Leaky ReLU activation. Same as tf.nn.leaky_relu, but supports FP16.
64
+
65
+ def leaky_relu(x, alpha=0.2):
66
+ with tf.name_scope('LeakyRelu'):
67
+ alpha = tf.constant(alpha, dtype=x.dtype, name='alpha')
68
+ return tf.maximum(x * alpha, x)
69
+
70
+ #----------------------------------------------------------------------------
71
+ # Nearest-neighbor upscaling layer.
72
+
73
+ def upscale2d(x, factor=2):
74
+ assert isinstance(factor, int) and factor >= 1
75
+ if factor == 1: return x
76
+ with tf.variable_scope('Upscale2D'):
77
+ s = x.shape
78
+ x = tf.reshape(x, [-1, s[1], s[2], 1, s[3], 1])
79
+ x = tf.tile(x, [1, 1, 1, factor, 1, factor])
80
+ x = tf.reshape(x, [-1, s[1], s[2] * factor, s[3] * factor])
81
+ return x
82
+
83
+ #----------------------------------------------------------------------------
84
+ # Fused upscale2d + conv2d.
85
+ # Faster and uses less memory than performing the operations separately.
86
+
87
+ def upscale2d_conv2d(x, fmaps, kernel, gain=np.sqrt(2), use_wscale=False):
88
+ assert kernel >= 1 and kernel % 2 == 1
89
+ w = get_weight([kernel, kernel, fmaps, x.shape[1].value], gain=gain, use_wscale=use_wscale, fan_in=(kernel**2)*x.shape[1].value)
90
+ w = tf.pad(w, [[1,1], [1,1], [0,0], [0,0]], mode='CONSTANT')
91
+ w = tf.add_n([w[1:, 1:], w[:-1, 1:], w[1:, :-1], w[:-1, :-1]])
92
+ w = tf.cast(w, x.dtype)
93
+ os = [tf.shape(x)[0], fmaps, x.shape[2] * 2, x.shape[3] * 2]
94
+ return tf.nn.conv2d_transpose(x, w, os, strides=[1,1,2,2], padding='SAME', data_format='NCHW')
95
+
96
+ #----------------------------------------------------------------------------
97
+ # Box filter downscaling layer.
98
+
99
+ def downscale2d(x, factor=2):
100
+ assert isinstance(factor, int) and factor >= 1
101
+ if factor == 1: return x
102
+ with tf.variable_scope('Downscale2D'):
103
+ ksize = [1, 1, factor, factor]
104
+ return tf.nn.avg_pool(x, ksize=ksize, strides=ksize, padding='VALID', data_format='NCHW') # NOTE: requires tf_config['graph_options.place_pruned_graph'] = True
105
+
106
+ #----------------------------------------------------------------------------
107
+ # Fused conv2d + downscale2d.
108
+ # Faster and uses less memory than performing the operations separately.
109
+
110
+ def conv2d_downscale2d(x, fmaps, kernel, gain=np.sqrt(2), use_wscale=False):
111
+ assert kernel >= 1 and kernel % 2 == 1
112
+ w = get_weight([kernel, kernel, x.shape[1].value, fmaps], gain=gain, use_wscale=use_wscale)
113
+ w = tf.pad(w, [[1,1], [1,1], [0,0], [0,0]], mode='CONSTANT')
114
+ w = tf.add_n([w[1:, 1:], w[:-1, 1:], w[1:, :-1], w[:-1, :-1]]) * 0.25
115
+ w = tf.cast(w, x.dtype)
116
+ return tf.nn.conv2d(x, w, strides=[1,1,2,2], padding='SAME', data_format='NCHW')
117
+
118
+ #----------------------------------------------------------------------------
119
+ # Pixelwise feature vector normalization.
120
+
121
+ def pixel_norm(x, epsilon=1e-8):
122
+ with tf.variable_scope('PixelNorm'):
123
+ return x * tf.rsqrt(tf.reduce_mean(tf.square(x), axis=1, keepdims=True) + epsilon)
124
+
125
+ #----------------------------------------------------------------------------
126
+ # Minibatch standard deviation.
127
+
128
+ def minibatch_stddev_layer(x, group_size=4):
129
+ with tf.variable_scope('MinibatchStddev'):
130
+ group_size = tf.minimum(group_size, tf.shape(x)[0]) # Minibatch must be divisible by (or smaller than) group_size.
131
+ s = x.shape # [NCHW] Input shape.
132
+ y = tf.reshape(x, [group_size, -1, s[1], s[2], s[3]]) # [GMCHW] Split minibatch into M groups of size G.
133
+ y = tf.cast(y, tf.float32) # [GMCHW] Cast to FP32.
134
+ y -= tf.reduce_mean(y, axis=0, keepdims=True) # [GMCHW] Subtract mean over group.
135
+ y = tf.reduce_mean(tf.square(y), axis=0) # [MCHW] Calc variance over group.
136
+ y = tf.sqrt(y + 1e-8) # [MCHW] Calc stddev over group.
137
+ y = tf.reduce_mean(y, axis=[1,2,3], keepdims=True) # [M111] Take average over fmaps and pixels.
138
+ y = tf.cast(y, x.dtype) # [M111] Cast back to original data type.
139
+ y = tf.tile(y, [group_size, 1, s[2], s[3]]) # [N1HW] Replicate over group and pixels.
140
+ return tf.concat([x, y], axis=1) # [NCHW] Append as new fmap.
141
+
142
+ #----------------------------------------------------------------------------
143
+ # Generator network used in the paper.
144
+
145
+ def G_paper(
146
+ latents_in, # First input: Latent vectors [minibatch, latent_size].
147
+ labels_in, # Second input: Labels [minibatch, label_size].
148
+ num_channels = 1, # Number of output color channels. Overridden based on dataset.
149
+ resolution = 32, # Output resolution. Overridden based on dataset.
150
+ label_size = 0, # Dimensionality of the labels, 0 if no labels. Overridden based on dataset.
151
+ fmap_base = 8192, # Overall multiplier for the number of feature maps.
152
+ fmap_decay = 1.0, # log2 feature map reduction when doubling the resolution.
153
+ fmap_max = 512, # Maximum number of feature maps in any layer.
154
+ latent_size = None, # Dimensionality of the latent vectors. None = min(fmap_base, fmap_max).
155
+ normalize_latents = True, # Normalize latent vectors before feeding them to the network?
156
+ use_wscale = True, # Enable equalized learning rate?
157
+ use_pixelnorm = True, # Enable pixelwise feature vector normalization?
158
+ pixelnorm_epsilon = 1e-8, # Constant epsilon for pixelwise feature vector normalization.
159
+ use_leakyrelu = True, # True = leaky ReLU, False = ReLU.
160
+ dtype = 'float32', # Data type to use for activations and outputs.
161
+ fused_scale = True, # True = use fused upscale2d + conv2d, False = separate upscale2d layers.
162
+ structure = None, # 'linear' = human-readable, 'recursive' = efficient, None = select automatically.
163
+ is_template_graph = False, # True = template graph constructed by the Network class, False = actual evaluation.
164
+ **kwargs): # Ignore unrecognized keyword args.
165
+ # print(":!!!")
166
+ resolution_log2 = int(np.log2(resolution))
167
+ assert resolution == 2**resolution_log2 and resolution >= 4
168
+ def nf(stage): return min(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_max)
169
+ def PN(x): return pixel_norm(x, epsilon=pixelnorm_epsilon) if use_pixelnorm else x
170
+ if latent_size is None: latent_size = nf(0)
171
+ if structure is None: structure = 'linear' if is_template_graph else 'recursive'
172
+ act = leaky_relu if use_leakyrelu else tf.nn.relu
173
+
174
+ latents_in.set_shape([None, latent_size])
175
+ labels_in.set_shape([None, label_size])
176
+ combo_in = tf.cast(tf.concat([latents_in, labels_in], axis=1), dtype)
177
+ lod_in = tf.cast(tf.compat.v1.get_variable('lod', initializer=np.float32(0.0), trainable=False), dtype)
178
+
179
+ # Building blocks.
180
+ def block(x, res): # res = 2..resolution_log2
181
+ with tf.variable_scope('%dx%d' % (2**res, 2**res)):
182
+ if res == 2: # 4x4
183
+ if normalize_latents: x = pixel_norm(x, epsilon=pixelnorm_epsilon)
184
+ with tf.variable_scope('Dense'):
185
+ x = dense(x, fmaps=nf(res-1)*16, gain=np.sqrt(2)/4, use_wscale=use_wscale) # override gain to match the original Theano implementation
186
+ x = tf.reshape(x, [-1, nf(res-1), 4, 4])
187
+ x = PN(act(apply_bias(x)))
188
+ with tf.variable_scope('Conv'):
189
+ x = PN(act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale))))
190
+ else: # 8x8 and up
191
+ if fused_scale:
192
+ with tf.variable_scope('Conv0_up'):
193
+ x = PN(act(apply_bias(upscale2d_conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale))))
194
+ else:
195
+ x = upscale2d(x)
196
+ with tf.variable_scope('Conv0'):
197
+ x = PN(act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale))))
198
+ with tf.variable_scope('Conv1'):
199
+ x = PN(act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale))))
200
+ return x
201
+ def torgb(x, res): # res = 2..resolution_log2
202
+ lod = resolution_log2 - res
203
+ with tf.variable_scope('ToRGB_lod%d' % lod):
204
+ return apply_bias(conv2d(x, fmaps=num_channels, kernel=1, gain=1, use_wscale=use_wscale))
205
+
206
+ # Linear structure: simple but inefficient.
207
+ if structure == 'linear':
208
+ x = block(combo_in, 2)
209
+ images_out = torgb(x, 2)
210
+ for res in range(3, resolution_log2 + 1):
211
+ lod = resolution_log2 - res
212
+ x = block(x, res)
213
+ img = torgb(x, res)
214
+ images_out = upscale2d(images_out)
215
+ with tf.variable_scope('Grow_lod%d' % lod):
216
+ images_out = lerp_clip(img, images_out, lod_in - lod)
217
+
218
+ # Recursive structure: complex but efficient.
219
+ if structure == 'recursive':
220
+ def grow(x, res, lod):
221
+ y = block(x, res)
222
+ img = lambda: upscale2d(torgb(y, res), 2**lod)
223
+ if res > 2: img = cset(img, (lod_in > lod), lambda: upscale2d(lerp(torgb(y, res), upscale2d(torgb(x, res - 1)), lod_in - lod), 2**lod))
224
+ if lod > 0: img = cset(img, (lod_in < lod), lambda: grow(y, res + 1, lod - 1))
225
+ return img()
226
+ images_out = grow(combo_in, 2, resolution_log2 - 2)
227
+
228
+ assert images_out.dtype == tf.as_dtype(dtype)
229
+ images_out = tf.identity(images_out, name='images_out')
230
+ return images_out
231
+
232
+ #----------------------------------------------------------------------------
233
+ # Discriminator network used in the paper.
234
+
235
+ def D_paper(
236
+ images_in, # Input: Images [minibatch, channel, height, width].
237
+ num_channels = 1, # Number of input color channels. Overridden based on dataset.
238
+ resolution = 32, # Input resolution. Overridden based on dataset.
239
+ label_size = 0, # Dimensionality of the labels, 0 if no labels. Overridden based on dataset.
240
+ fmap_base = 8192, # Overall multiplier for the number of feature maps.
241
+ fmap_decay = 1.0, # log2 feature map reduction when doubling the resolution.
242
+ fmap_max = 512, # Maximum number of feature maps in any layer.
243
+ use_wscale = True, # Enable equalized learning rate?
244
+ mbstd_group_size = 4, # Group size for the minibatch standard deviation layer, 0 = disable.
245
+ dtype = 'float32', # Data type to use for activations and outputs.
246
+ fused_scale = True, # True = use fused conv2d + downscale2d, False = separate downscale2d layers.
247
+ structure = None, # 'linear' = human-readable, 'recursive' = efficient, None = select automatically
248
+ is_template_graph = False, # True = template graph constructed by the Network class, False = actual evaluation.
249
+ **kwargs): # Ignore unrecognized keyword args.
250
+
251
+ resolution_log2 = int(np.log2(resolution))
252
+ assert resolution == 2**resolution_log2 and resolution >= 4
253
+ def nf(stage): return min(int(fmap_base / (2.0 ** (stage * fmap_decay))), fmap_max)
254
+ if structure is None: structure = 'linear' if is_template_graph else 'recursive'
255
+ act = leaky_relu
256
+
257
+ images_in.set_shape([None, num_channels, resolution, resolution])
258
+ images_in = tf.cast(images_in, dtype)
259
+ lod_in = tf.cast(tf.compat.v1.get_variable('lod', initializer=np.float32(0.0), trainable=False), dtype)
260
+
261
+ # Building blocks.
262
+ def fromrgb(x, res): # res = 2..resolution_log2
263
+ with tf.variable_scope('FromRGB_lod%d' % (resolution_log2 - res)):
264
+ return act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=1, use_wscale=use_wscale)))
265
+ def block(x, res): # res = 2..resolution_log2
266
+ with tf.variable_scope('%dx%d' % (2**res, 2**res)):
267
+ if res >= 3: # 8x8 and up
268
+ with tf.variable_scope('Conv0'):
269
+ x = act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale)))
270
+ if fused_scale:
271
+ with tf.variable_scope('Conv1_down'):
272
+ x = act(apply_bias(conv2d_downscale2d(x, fmaps=nf(res-2), kernel=3, use_wscale=use_wscale)))
273
+ else:
274
+ with tf.variable_scope('Conv1'):
275
+ x = act(apply_bias(conv2d(x, fmaps=nf(res-2), kernel=3, use_wscale=use_wscale)))
276
+ x = downscale2d(x)
277
+ else: # 4x4
278
+ if mbstd_group_size > 1:
279
+ x = minibatch_stddev_layer(x, mbstd_group_size)
280
+ with tf.variable_scope('Conv'):
281
+ x = act(apply_bias(conv2d(x, fmaps=nf(res-1), kernel=3, use_wscale=use_wscale)))
282
+ with tf.variable_scope('Dense0'):
283
+ x = act(apply_bias(dense(x, fmaps=nf(res-2), use_wscale=use_wscale)))
284
+ with tf.variable_scope('Dense1'):
285
+ x = apply_bias(dense(x, fmaps=1+label_size, gain=1, use_wscale=use_wscale))
286
+ return x
287
+
288
+ # Linear structure: simple but inefficient.
289
+ if structure == 'linear':
290
+ img = images_in
291
+ x = fromrgb(img, resolution_log2)
292
+ for res in range(resolution_log2, 2, -1):
293
+ lod = resolution_log2 - res
294
+ x = block(x, res)
295
+ img = downscale2d(img)
296
+ y = fromrgb(img, res - 1)
297
+ with tf.variable_scope('Grow_lod%d' % lod):
298
+ x = lerp_clip(x, y, lod_in - lod)
299
+ combo_out = block(x, 2)
300
+
301
+ # Recursive structure: complex but efficient.
302
+ if structure == 'recursive':
303
+ def grow(res, lod):
304
+ x = lambda: fromrgb(downscale2d(images_in, 2**lod), res)
305
+ if lod > 0: x = cset(x, (lod_in < lod), lambda: grow(res + 1, lod - 1))
306
+ x = block(x(), res); y = lambda: x
307
+ if res > 2: y = cset(y, (lod_in > lod), lambda: lerp(x, fromrgb(downscale2d(images_in, 2**(lod+1)), res - 1), lod_in - lod))
308
+ return y()
309
+ combo_out = grow(2, resolution_log2 - 2)
310
+
311
+ assert combo_out.dtype == tf.as_dtype(dtype)
312
+ scores_out = tf.identity(combo_out[:, :1], name='scores_out')
313
+ labels_out = tf.identity(combo_out[:, 1:], name='labels_out')
314
+ return scores_out, labels_out
315
+
316
+ #----------------------------------------------------------------------------
EEGFaceSem/pgan/tfutil.py ADDED
@@ -0,0 +1,770 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # This work is licensed under the Creative Commons Attribution-NonCommercial
4
+ # 4.0 International License. To view a copy of this license, visit
5
+
6
+ # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
7
+
8
+ import os
9
+ import sys
10
+ import inspect
11
+ import importlib
12
+ import imp
13
+ import numpy as np
14
+ from collections import OrderedDict
15
+ import tensorflow.compat.v1 as tf
16
+ tf.disable_v2_behavior()
17
+ import networks
18
+
19
+ #----------------------------------------------------------------------------
20
+ # Convenience.
21
+
22
+ def run(*args, **kwargs): # Run the specified ops in the default session.
23
+ return tf.get_default_session().run(*args, **kwargs)
24
+
25
+ def is_tf_expression(x):
26
+ return isinstance(x, tf.Tensor) or isinstance(x, tf.Variable) or isinstance(x, tf.Operation)
27
+
28
+ def shape_to_list(shape):
29
+ return [dim.value for dim in shape]
30
+
31
+ def flatten(x):
32
+ with tf.name_scope('Flatten'):
33
+ return tf.reshape(x, [-1])
34
+
35
+ def log2(x):
36
+ with tf.name_scope('Log2'):
37
+ return tf.log(x) * np.float32(1.0 / np.log(2.0))
38
+
39
+ def exp2(x):
40
+ with tf.name_scope('Exp2'):
41
+ return tf.exp(x * np.float32(np.log(2.0)))
42
+
43
+ def lerp(a, b, t):
44
+ with tf.name_scope('Lerp'):
45
+ return a + (b - a) * t
46
+
47
+ def lerp_clip(a, b, t):
48
+ with tf.name_scope('LerpClip'):
49
+ return a + (b - a) * tf.clip_by_value(t, 0.0, 1.0)
50
+
51
+ def absolute_name_scope(scope): # Forcefully enter the specified name scope, ignoring any surrounding scopes.
52
+ return tf.name_scope(scope + '/')
53
+
54
+ #----------------------------------------------------------------------------
55
+ # Initialize TensorFlow graph and session using good default settings.
56
+
57
+ def init_tf(config_dict=dict()):
58
+ if tf.get_default_session() is None:
59
+ tf.set_random_seed(np.random.randint(1 << 31))
60
+ create_session(config_dict, force_as_default=True)
61
+
62
+ #----------------------------------------------------------------------------
63
+ # Create tf.Session based on config dict of the form
64
+ # {'gpu_options.allow_growth': True}
65
+
66
+ def create_session(config_dict=dict(), force_as_default=False):
67
+ config = tf.ConfigProto()
68
+ for key, value in config_dict.items():
69
+ fields = key.split('.')
70
+ obj = config
71
+ for field in fields[:-1]:
72
+ obj = getattr(obj, field)
73
+ setattr(obj, fields[-1], value)
74
+ session = tf.Session(config=config)
75
+ if force_as_default:
76
+ session._default_session = session.as_default()
77
+ session._default_session.enforce_nesting = False
78
+ session._default_session.__enter__()
79
+ return session
80
+
81
+ #----------------------------------------------------------------------------
82
+ # Initialize all tf.Variables that have not already been initialized.
83
+ # Equivalent to the following, but more efficient and does not bloat the tf graph:
84
+ # tf.variables_initializer(tf.report_unitialized_variables()).run()
85
+
86
+ def init_uninited_vars(vars=None):
87
+ if vars is None: vars = tf.global_variables()
88
+ test_vars = []; test_ops = []
89
+ with tf.control_dependencies(None): # ignore surrounding control_dependencies
90
+ for var in vars:
91
+ assert is_tf_expression(var)
92
+ try:
93
+ tf.get_default_graph().get_tensor_by_name(var.name.replace(':0', '/IsVariableInitialized:0'))
94
+ except KeyError:
95
+ # Op does not exist => variable may be uninitialized.
96
+ test_vars.append(var)
97
+ with absolute_name_scope(var.name.split(':')[0]):
98
+ test_ops.append(tf.is_variable_initialized(var))
99
+ init_vars = [var for var, inited in zip(test_vars, run(test_ops)) if not inited]
100
+ run([var.initializer for var in init_vars])
101
+
102
+ #----------------------------------------------------------------------------
103
+ # Set the values of given tf.Variables.
104
+ # Equivalent to the following, but more efficient and does not bloat the tf graph:
105
+ # tfutil.run([tf.assign(var, value) for var, value in var_to_value_dict.items()]
106
+
107
+ def set_vars(var_to_value_dict):
108
+ ops = []
109
+ feed_dict = {}
110
+ for var, value in var_to_value_dict.items():
111
+ assert is_tf_expression(var)
112
+ try:
113
+ setter = tf.get_default_graph().get_tensor_by_name(var.name.replace(':0', '/setter:0')) # look for existing op
114
+ except KeyError:
115
+ with absolute_name_scope(var.name.split(':')[0]):
116
+ with tf.control_dependencies(None): # ignore surrounding control_dependencies
117
+ setter = tf.assign(var, tf.placeholder(var.dtype, var.shape, 'new_value'), name='setter') # create new setter
118
+ ops.append(setter)
119
+ feed_dict[setter.op.inputs[1]] = value
120
+ run(ops, feed_dict)
121
+
122
+ #----------------------------------------------------------------------------
123
+ # Autosummary creates an identity op that internally keeps track of the input
124
+ # values and automatically shows up in TensorBoard. The reported value
125
+ # represents an average over input components. The average is accumulated
126
+ # constantly over time and flushed when save_summaries() is called.
127
+ #
128
+ # Notes:
129
+ # - The output tensor must be used as an input for something else in the
130
+ # graph. Otherwise, the autosummary op will not get executed, and the average
131
+ # value will not get accumulated.
132
+ # - It is perfectly fine to include autosummaries with the same name in
133
+ # several places throughout the graph, even if they are executed concurrently.
134
+ # - It is ok to also pass in a python scalar or numpy array. In this case, it
135
+ # is added to the average immediately.
136
+
137
+ _autosummary_vars = OrderedDict() # name => [var, ...]
138
+ _autosummary_immediate = OrderedDict() # name => update_op, update_value
139
+ _autosummary_finalized = False
140
+
141
+ def autosummary(name, value):
142
+ id = name.replace('/', '_')
143
+ if is_tf_expression(value):
144
+ with tf.name_scope('summary_' + id), tf.device(value.device):
145
+ update_op = _create_autosummary_var(name, value)
146
+ with tf.control_dependencies([update_op]):
147
+ return tf.identity(value)
148
+ else: # python scalar or numpy array
149
+ if name not in _autosummary_immediate:
150
+ with absolute_name_scope('Autosummary/' + id), tf.device(None), tf.control_dependencies(None):
151
+ update_value = tf.placeholder(tf.float32)
152
+ update_op = _create_autosummary_var(name, update_value)
153
+ _autosummary_immediate[name] = update_op, update_value
154
+ update_op, update_value = _autosummary_immediate[name]
155
+ run(update_op, {update_value: np.float32(value)})
156
+ return value
157
+
158
+ # Create the necessary ops to include autosummaries in TensorBoard report.
159
+ # Note: This should be done only once per graph.
160
+ def finalize_autosummaries():
161
+ global _autosummary_finalized
162
+ if _autosummary_finalized:
163
+ return
164
+ _autosummary_finalized = True
165
+ init_uninited_vars([var for vars in _autosummary_vars.values() for var in vars])
166
+ with tf.device(None), tf.control_dependencies(None):
167
+ for name, vars in _autosummary_vars.items():
168
+ id = name.replace('/', '_')
169
+ with absolute_name_scope('Autosummary/' + id):
170
+ sum = tf.add_n(vars)
171
+ avg = sum[0] / sum[1]
172
+ with tf.control_dependencies([avg]): # read before resetting
173
+ reset_ops = [tf.assign(var, tf.zeros(2)) for var in vars]
174
+ with tf.name_scope(None), tf.control_dependencies(reset_ops): # reset before reporting
175
+ tf.summary.scalar(name, avg)
176
+
177
+ # Internal helper for creating autosummary accumulators.
178
+ def _create_autosummary_var(name, value_expr):
179
+ assert not _autosummary_finalized
180
+ v = tf.cast(value_expr, tf.float32)
181
+ if v.shape.ndims is 0:
182
+ v = [v, np.float32(1.0)]
183
+ elif v.shape.ndims is 1:
184
+ v = [tf.reduce_sum(v), tf.cast(tf.shape(v)[0], tf.float32)]
185
+ else:
186
+ v = [tf.reduce_sum(v), tf.reduce_prod(tf.cast(tf.shape(v), tf.float32))]
187
+ v = tf.cond(tf.is_finite(v[0]), lambda: tf.stack(v), lambda: tf.zeros(2))
188
+ with tf.control_dependencies(None):
189
+ var = tf.Variable(tf.zeros(2)) # [numerator, denominator]
190
+ update_op = tf.cond(tf.is_variable_initialized(var), lambda: tf.assign_add(var, v), lambda: tf.assign(var, v))
191
+ if name in _autosummary_vars:
192
+ _autosummary_vars[name].append(var)
193
+ else:
194
+ _autosummary_vars[name] = [var]
195
+ return update_op
196
+
197
+ #----------------------------------------------------------------------------
198
+ # Call filewriter.add_summary() with all summaries in the default graph,
199
+ # automatically finalizing and merging them on the first call.
200
+
201
+ _summary_merge_op = None
202
+
203
+ def save_summaries(filewriter, global_step=None):
204
+ global _summary_merge_op
205
+ if _summary_merge_op is None:
206
+ finalize_autosummaries()
207
+ with tf.device(None), tf.control_dependencies(None):
208
+ _summary_merge_op = tf.summary.merge_all()
209
+ filewriter.add_summary(_summary_merge_op.eval(), global_step)
210
+
211
+ #----------------------------------------------------------------------------
212
+ # Utilities for importing modules and objects by name.
213
+
214
+ def import_module(module_or_obj_name):
215
+ parts = module_or_obj_name.split('.')
216
+ parts[0] = {'np': 'numpy', 'tf': 'tensorflow'}.get(parts[0], parts[0])
217
+ for i in range(len(parts), 0, -1):
218
+ try:
219
+ module = importlib.import_module('.'.join(parts[:i]))
220
+ relative_obj_name = '.'.join(parts[i:])
221
+ return module, relative_obj_name
222
+ except ImportError:
223
+ pass
224
+ raise ImportError(module_or_obj_name)
225
+
226
+ def find_obj_in_module(module, relative_obj_name):
227
+ obj = module
228
+ for part in relative_obj_name.split('.'):
229
+ obj = getattr(obj, part)
230
+ return obj
231
+
232
+ def import_obj(obj_name):
233
+ module, relative_obj_name = import_module(obj_name)
234
+ return find_obj_in_module(module, relative_obj_name)
235
+
236
+ def call_func_by_name(*args, func=None, **kwargs):
237
+ assert func is not None
238
+ return import_obj(func)(*args, **kwargs)
239
+
240
+ #----------------------------------------------------------------------------
241
+ # Wrapper for tf.train.Optimizer that automatically takes care of:
242
+ # - Gradient averaging for multi-GPU training.
243
+ # - Dynamic loss scaling and typecasts for FP16 training.
244
+ # - Ignoring corrupted gradients that contain NaNs/Infs.
245
+ # - Reporting statistics.
246
+ # - Well-chosen default settings.
247
+
248
+ class Optimizer:
249
+ def __init__(
250
+ self,
251
+ name = 'Train',
252
+ tf_optimizer = 'tf.train.AdamOptimizer',
253
+ learning_rate = 0.001,
254
+ use_loss_scaling = False,
255
+ loss_scaling_init = 64.0,
256
+ loss_scaling_inc = 0.0005,
257
+ loss_scaling_dec = 1.0,
258
+ **kwargs):
259
+
260
+ # Init fields.
261
+ self.name = name
262
+ self.learning_rate = tf.convert_to_tensor(learning_rate)
263
+ self.id = self.name.replace('/', '.')
264
+ self.scope = tf.get_default_graph().unique_name(self.id)
265
+ self.optimizer_class = import_obj(tf_optimizer)
266
+ self.optimizer_kwargs = dict(kwargs)
267
+ self.use_loss_scaling = use_loss_scaling
268
+ self.loss_scaling_init = loss_scaling_init
269
+ self.loss_scaling_inc = loss_scaling_inc
270
+ self.loss_scaling_dec = loss_scaling_dec
271
+ self._grad_shapes = None # [shape, ...]
272
+ self._dev_opt = OrderedDict() # device => optimizer
273
+ self._dev_grads = OrderedDict() # device => [[(grad, var), ...], ...]
274
+ self._dev_ls_var = OrderedDict() # device => variable (log2 of loss scaling factor)
275
+ self._updates_applied = False
276
+
277
+ # Register the gradients of the given loss function with respect to the given variables.
278
+ # Intended to be called once per GPU.
279
+ def register_gradients(self, loss, vars):
280
+ assert not self._updates_applied
281
+
282
+ # Validate arguments.
283
+ if isinstance(vars, dict):
284
+ vars = list(vars.values()) # allow passing in Network.trainables as vars
285
+ assert isinstance(vars, list) and len(vars) >= 1
286
+ assert all(is_tf_expression(expr) for expr in vars + [loss])
287
+ if self._grad_shapes is None:
288
+ self._grad_shapes = [shape_to_list(var.shape) for var in vars]
289
+ assert len(vars) == len(self._grad_shapes)
290
+ assert all(shape_to_list(var.shape) == var_shape for var, var_shape in zip(vars, self._grad_shapes))
291
+ dev = loss.device
292
+ assert all(var.device == dev for var in vars)
293
+
294
+ # Register device and compute gradients.
295
+ with tf.name_scope(self.id + '_grad'), tf.device(dev):
296
+ if dev not in self._dev_opt:
297
+ opt_name = self.scope.replace('/', '_') + '_opt%d' % len(self._dev_opt)
298
+ self._dev_opt[dev] = self.optimizer_class(name=opt_name, learning_rate=self.learning_rate, **self.optimizer_kwargs)
299
+ self._dev_grads[dev] = []
300
+ loss = self.apply_loss_scaling(tf.cast(loss, tf.float32))
301
+ grads = self._dev_opt[dev].compute_gradients(loss, vars, gate_gradients=tf.train.Optimizer.GATE_NONE) # disable gating to reduce memory usage
302
+ grads = [(g, v) if g is not None else (tf.zeros_like(v), v) for g, v in grads] # replace disconnected gradients with zeros
303
+ self._dev_grads[dev].append(grads)
304
+
305
+ # Construct training op to update the registered variables based on their gradients.
306
+ def apply_updates(self):
307
+ assert not self._updates_applied
308
+ self._updates_applied = True
309
+ devices = list(self._dev_grads.keys())
310
+ total_grads = sum(len(grads) for grads in self._dev_grads.values())
311
+ assert len(devices) >= 1 and total_grads >= 1
312
+ ops = []
313
+ with absolute_name_scope(self.scope):
314
+
315
+ # Cast gradients to FP32 and calculate partial sum within each device.
316
+ dev_grads = OrderedDict() # device => [(grad, var), ...]
317
+ for dev_idx, dev in enumerate(devices):
318
+ with tf.name_scope('ProcessGrads%d' % dev_idx), tf.device(dev):
319
+ sums = []
320
+ for gv in zip(*self._dev_grads[dev]):
321
+ assert all(v is gv[0][1] for g, v in gv)
322
+ g = [tf.cast(g, tf.float32) for g, v in gv]
323
+ g = g[0] if len(g) == 1 else tf.add_n(g)
324
+ sums.append((g, gv[0][1]))
325
+ dev_grads[dev] = sums
326
+
327
+ # Sum gradients across devices.
328
+ if len(devices) > 1:
329
+ with tf.name_scope('SumAcrossGPUs'), tf.device(None):
330
+ for var_idx, grad_shape in enumerate(self._grad_shapes):
331
+ g = [dev_grads[dev][var_idx][0] for dev in devices]
332
+ if np.prod(grad_shape): # nccl does not support zero-sized tensors
333
+ g = tf.contrib.nccl.all_sum(g)
334
+ for dev, gg in zip(devices, g):
335
+ dev_grads[dev][var_idx] = (gg, dev_grads[dev][var_idx][1])
336
+
337
+ # Apply updates separately on each device.
338
+ for dev_idx, (dev, grads) in enumerate(dev_grads.items()):
339
+ with tf.name_scope('ApplyGrads%d' % dev_idx), tf.device(dev):
340
+
341
+ # Scale gradients as needed.
342
+ if self.use_loss_scaling or total_grads > 1:
343
+ with tf.name_scope('Scale'):
344
+ coef = tf.constant(np.float32(1.0 / total_grads), name='coef')
345
+ coef = self.undo_loss_scaling(coef)
346
+ grads = [(g * coef, v) for g, v in grads]
347
+
348
+ # Check for overflows.
349
+ with tf.name_scope('CheckOverflow'):
350
+ grad_ok = tf.reduce_all(tf.stack([tf.reduce_all(tf.is_finite(g)) for g, v in grads]))
351
+
352
+ # Update weights and adjust loss scaling.
353
+ with tf.name_scope('UpdateWeights'):
354
+ opt = self._dev_opt[dev]
355
+ ls_var = self.get_loss_scaling_var(dev)
356
+ if not self.use_loss_scaling:
357
+ ops.append(tf.cond(grad_ok, lambda: opt.apply_gradients(grads), tf.no_op))
358
+ else:
359
+ ops.append(tf.cond(grad_ok,
360
+ lambda: tf.group(tf.assign_add(ls_var, self.loss_scaling_inc), opt.apply_gradients(grads)),
361
+ lambda: tf.group(tf.assign_sub(ls_var, self.loss_scaling_dec))))
362
+
363
+ # Report statistics on the last device.
364
+ if dev == devices[-1]:
365
+ with tf.name_scope('Statistics'):
366
+ ops.append(autosummary(self.id + '/learning_rate', self.learning_rate))
367
+ ops.append(autosummary(self.id + '/overflow_frequency', tf.where(grad_ok, 0, 1)))
368
+ if self.use_loss_scaling:
369
+ ops.append(autosummary(self.id + '/loss_scaling_log2', ls_var))
370
+
371
+ # Initialize variables and group everything into a single op.
372
+ self.reset_optimizer_state()
373
+ init_uninited_vars(list(self._dev_ls_var.values()))
374
+ return tf.group(*ops, name='TrainingOp')
375
+
376
+ # Reset internal state of the underlying optimizer.
377
+ def reset_optimizer_state(self):
378
+ run([var.initializer for opt in self._dev_opt.values() for var in opt.variables()])
379
+
380
+ # Get or create variable representing log2 of the current dynamic loss scaling factor.
381
+ def get_loss_scaling_var(self, device):
382
+ if not self.use_loss_scaling:
383
+ return None
384
+ if device not in self._dev_ls_var:
385
+ with absolute_name_scope(self.scope + '/LossScalingVars'), tf.control_dependencies(None):
386
+ self._dev_ls_var[device] = tf.Variable(np.float32(self.loss_scaling_init), name='loss_scaling_var')
387
+ return self._dev_ls_var[device]
388
+
389
+ # Apply dynamic loss scaling for the given expression.
390
+ def apply_loss_scaling(self, value):
391
+ assert is_tf_expression(value)
392
+ if not self.use_loss_scaling:
393
+ return value
394
+ return value * exp2(self.get_loss_scaling_var(value.device))
395
+
396
+ # Undo the effect of dynamic loss scaling for the given expression.
397
+ def undo_loss_scaling(self, value):
398
+ assert is_tf_expression(value)
399
+ if not self.use_loss_scaling:
400
+ return value
401
+ return value * exp2(-self.get_loss_scaling_var(value.device))
402
+
403
+ #----------------------------------------------------------------------------
404
+ # Generic network abstraction.
405
+ #
406
+ # Acts as a convenience wrapper for a parameterized network construction
407
+ # function, providing several utility methods and convenient access to
408
+ # the inputs/outputs/weights.
409
+ #
410
+ # Network objects can be safely pickled and unpickled for long-term
411
+ # archival purposes. The pickling works reliably as long as the underlying
412
+ # network construction function is defined in a standalone Python module
413
+ # that has no side effects or application-specific imports.
414
+
415
+ network_import_handlers = [] # Custom import handlers for dealing with legacy data in pickle import.
416
+ _network_import_modules = [] # Temporary modules create during pickle import.
417
+
418
+ class Network:
419
+ def __init__(self,
420
+ name=None, # Network name. Used to select TensorFlow name and variable scopes.
421
+ func=None, # Fully qualified name of the underlying network construction function.
422
+ **static_kwargs): # Keyword arguments to be passed in to the network construction function.
423
+
424
+ self._init_fields()
425
+ self.name = name
426
+ self.static_kwargs = dict(static_kwargs)
427
+
428
+ # Init build func.
429
+ module, self._build_func_name = import_module(func)
430
+ self._build_module_src = inspect.getsource(module)
431
+ self._build_func = find_obj_in_module(module, self._build_func_name)
432
+
433
+ # Init graph.
434
+ self._init_graph()
435
+ self.reset_vars()
436
+
437
+ def _init_fields(self):
438
+ self.name = None # User-specified name, defaults to build func name if None.
439
+ self.scope = None # Unique TF graph scope, derived from the user-specified name.
440
+ self.static_kwargs = dict() # Arguments passed to the user-supplied build func.
441
+ self.num_inputs = 0 # Number of input tensors.
442
+ self.num_outputs = 0 # Number of output tensors.
443
+ self.input_shapes = [[]] # Input tensor shapes (NC or NCHW), including minibatch dimension.
444
+ self.output_shapes = [[]] # Output tensor shapes (NC or NCHW), including minibatch dimension.
445
+ self.input_shape = [] # Short-hand for input_shapes[0].
446
+ self.output_shape = [] # Short-hand for output_shapes[0].
447
+ self.input_templates = [] # Input placeholders in the template graph.
448
+ self.output_templates = [] # Output tensors in the template graph.
449
+ self.input_names = [] # Name string for each input.
450
+ self.output_names = [] # Name string for each output.
451
+ self.vars = OrderedDict() # All variables (localname => var).
452
+ self.trainables = OrderedDict() # Trainable variables (localname => var).
453
+ self._build_func = None # User-supplied build function that constructs the network.
454
+ self._build_func_name = None # Name of the build function.
455
+ self._build_module_src = None # Full source code of the module containing the build function.
456
+ self._run_cache = dict() # Cached graph data for Network.run().
457
+
458
+ def _init_graph(self):
459
+ # Collect inputs.
460
+ self.input_names = []
461
+ for param in inspect.signature(self._build_func).parameters.values():
462
+ if param.kind == param.POSITIONAL_OR_KEYWORD and param.default is param.empty:
463
+ self.input_names.append(param.name)
464
+ self.num_inputs = len(self.input_names)
465
+ assert self.num_inputs >= 1
466
+
467
+ # Choose name and scope.
468
+ if self.name is None:
469
+ self.name = self._build_func_name
470
+ self.scope = tf.get_default_graph().unique_name(self.name.replace('/', '_'), mark_as_used=False)
471
+
472
+ # Build template graph.
473
+ with tf.variable_scope(self.scope, reuse=tf.AUTO_REUSE):
474
+ assert tf.get_variable_scope().name == self.scope
475
+ with absolute_name_scope(self.scope): # ignore surrounding name_scope
476
+ with tf.control_dependencies(None): # ignore surrounding control_dependencies
477
+ self.input_templates = [tf.placeholder(tf.float32, name=name) for name in self.input_names]
478
+ out_expr = self._build_func(*self.input_templates, is_template_graph=True, **self.static_kwargs)
479
+
480
+ # Collect outputs.
481
+ assert is_tf_expression(out_expr) or isinstance(out_expr, tuple)
482
+ self.output_templates = [out_expr] if is_tf_expression(out_expr) else list(out_expr)
483
+ self.output_names = [t.name.split('/')[-1].split(':')[0] for t in self.output_templates]
484
+ self.num_outputs = len(self.output_templates)
485
+ assert self.num_outputs >= 1
486
+
487
+ # Populate remaining fields.
488
+ self.input_shapes = [shape_to_list(t.shape) for t in self.input_templates]
489
+ self.output_shapes = [shape_to_list(t.shape) for t in self.output_templates]
490
+ self.input_shape = self.input_shapes[0]
491
+ self.output_shape = self.output_shapes[0]
492
+ print('scope ', self.scope + '/')
493
+ # for var in tf.global_variables(self.scope + '/'):
494
+ # print('find ', self.get_var_localname(var), var)
495
+ self.vars = OrderedDict([(self.get_var_localname(var), var) for var in tf.global_variables(self.scope + '/')])
496
+ self.trainables = OrderedDict([(self.get_var_localname(var), var) for var in tf.trainable_variables(self.scope + '/')])
497
+
498
+ # Run initializers for all variables defined by this network.
499
+ def reset_vars(self):
500
+ run([var.initializer for var in self.vars.values()])
501
+
502
+ # Run initializers for all trainable variables defined by this network.
503
+ def reset_trainables(self):
504
+ run([var.initializer for var in self.trainables.values()])
505
+
506
+ # Get TensorFlow expression(s) for the output(s) of this network, given the inputs.
507
+ def get_output_for(self, *in_expr, return_as_list=False, **dynamic_kwargs):
508
+ assert len(in_expr) == self.num_inputs
509
+ all_kwargs = dict(self.static_kwargs)
510
+ all_kwargs.update(dynamic_kwargs)
511
+ with tf.variable_scope(self.scope, reuse=True):
512
+ assert tf.get_variable_scope().name == self.scope
513
+ named_inputs = [tf.identity(expr, name=name) for expr, name in zip(in_expr, self.input_names)]
514
+ out_expr = self._build_func(*named_inputs, **all_kwargs)
515
+ assert is_tf_expression(out_expr) or isinstance(out_expr, tuple)
516
+ if return_as_list:
517
+ out_expr = [out_expr] if is_tf_expression(out_expr) else list(out_expr)
518
+ return out_expr
519
+
520
+ # Get the local name of a given variable, excluding any surrounding name scopes.
521
+ def get_var_localname(self, var_or_globalname):
522
+ assert is_tf_expression(var_or_globalname) or isinstance(var_or_globalname, str)
523
+ globalname = var_or_globalname if isinstance(var_or_globalname, str) else var_or_globalname.name
524
+ assert globalname.startswith(self.scope + '/')
525
+ localname = globalname[len(self.scope) + 1:]
526
+ localname = localname.split(':')[0]
527
+ return localname
528
+
529
+ # Find variable by local or global name.
530
+ def find_var(self, var_or_localname):
531
+ assert is_tf_expression(var_or_localname) or isinstance(var_or_localname, str)
532
+ return self.vars[var_or_localname] if isinstance(var_or_localname, str) else var_or_localname
533
+
534
+ # Get the value of a given variable as NumPy array.
535
+ # Note: This method is very inefficient -- prefer to use tfutil.run(list_of_vars) whenever possible.
536
+ def get_var(self, var_or_localname):
537
+ return self.find_var(var_or_localname).eval()
538
+
539
+ # Set the value of a given variable based on the given NumPy array.
540
+ # Note: This method is very inefficient -- prefer to use tfutil.set_vars() whenever possible.
541
+ def set_var(self, var_or_localname, new_value):
542
+ return set_vars({self.find_var(var_or_localname): new_value})
543
+
544
+ # Pickle export.
545
+ def __getstate__(self):
546
+ return {
547
+ 'version': 2,
548
+ 'name': self.name,
549
+ 'static_kwargs': self.static_kwargs,
550
+ 'build_module_src': self._build_module_src,
551
+ 'build_func_name': self._build_func_name,
552
+ 'variables': list(zip(self.vars.keys(), run(list(self.vars.values()))))}
553
+
554
+ # Pickle import.
555
+ def __setstate__(self, state):
556
+ self._init_fields()
557
+
558
+ # Execute custom import handlers.
559
+ for handler in network_import_handlers:
560
+ state = handler(state)
561
+
562
+ # Set basic fields.
563
+ assert state['version'] == 2
564
+ self.name = state['name']
565
+ self.static_kwargs = state['static_kwargs']
566
+ self._build_module_src = state['build_module_src']
567
+ self._build_func_name = state['build_func_name']
568
+
569
+ # Parse imported module.
570
+ module = imp.new_module('_tfutil_network_import_module_%d' % len(_network_import_modules))
571
+ exec(self._build_module_src, module.__dict__)
572
+ # print(self._build_func_name, '???', module)
573
+ # self._build_func = find_obj_in_module(module, self._build_func_name)
574
+ if 'G_paper' in self._build_func_name:
575
+ self._build_func = networks.G_paper
576
+ elif 'D_paper' in self._build_func_name:
577
+ self._build_func = networks.D_paper
578
+ else:
579
+ print(self._build_func_name, 'not found')
580
+ exit(1)
581
+ # print(self._build_func)
582
+ # self._build_func(0, 0, 0)
583
+ _network_import_modules.append(module) # avoid gc
584
+
585
+ # Init graph.
586
+ self._init_graph()
587
+ self.reset_vars()
588
+ # for v in self.vars:
589
+ # print('self ', v)
590
+ # self.vars[var_or_localname] if isinstance(var_or_localname, str) else var_or_localname
591
+ set_vars({self.find_var(name): value for name, value in state['variables'] if name in self.vars})
592
+ # for name, value in state['variables']:
593
+ # print('name ', name)
594
+ # print('var ', self.find_var(name))
595
+
596
+ # Create a clone of this network with its own copy of the variables.
597
+ def clone(self, name=None):
598
+ net = object.__new__(Network)
599
+ net._init_fields()
600
+ net.name = name if name is not None else self.name
601
+ net.static_kwargs = dict(self.static_kwargs)
602
+ net._build_module_src = self._build_module_src
603
+ net._build_func_name = self._build_func_name
604
+ net._build_func = self._build_func
605
+ net._init_graph()
606
+ net.copy_vars_from(self)
607
+ return net
608
+
609
+ # Copy the values of all variables from the given network.
610
+ def copy_vars_from(self, src_net):
611
+ assert isinstance(src_net, Network)
612
+ name_to_value = run({name: src_net.find_var(name) for name in self.vars.keys()})
613
+ set_vars({self.find_var(name): value for name, value in name_to_value.items()})
614
+
615
+ # Copy the values of all trainable variables from the given network.
616
+ def copy_trainables_from(self, src_net):
617
+ assert isinstance(src_net, Network)
618
+ name_to_value = run({name: src_net.find_var(name) for name in self.trainables.keys()})
619
+ set_vars({self.find_var(name): value for name, value in name_to_value.items()})
620
+
621
+ # Create new network with the given parameters, and copy all variables from this network.
622
+ def convert(self, name=None, func=None, **static_kwargs):
623
+ net = Network(name, func, **static_kwargs)
624
+ net.copy_vars_from(self)
625
+ return net
626
+
627
+ # Construct a TensorFlow op that updates the variables of this network
628
+ # to be slightly closer to those of the given network.
629
+ def setup_as_moving_average_of(self, src_net, beta=0.99, beta_nontrainable=0.0):
630
+ assert isinstance(src_net, Network)
631
+ with absolute_name_scope(self.scope):
632
+ with tf.name_scope('MovingAvg'):
633
+ ops = []
634
+ for name, var in self.vars.items():
635
+ if name in src_net.vars:
636
+ cur_beta = beta if name in self.trainables else beta_nontrainable
637
+ new_value = lerp(src_net.vars[name], var, cur_beta)
638
+ ops.append(var.assign(new_value))
639
+ return tf.group(*ops)
640
+
641
+ # Run this network for the given NumPy array(s), and return the output(s) as NumPy array(s).
642
+ def run(self, *in_arrays,
643
+ return_as_list = False, # True = return a list of NumPy arrays, False = return a single NumPy array, or a tuple if there are multiple outputs.
644
+ print_progress = False, # Print progress to the console? Useful for very large input arrays.
645
+ minibatch_size = None, # Maximum minibatch size to use, None = disable batching.
646
+ num_gpus = 1, # Number of GPUs to use.
647
+ out_mul = 1.0, # Multiplicative constant to apply to the output(s).
648
+ out_add = 0.0, # Additive constant to apply to the output(s).
649
+ out_shrink = 1, # Shrink the spatial dimensions of the output(s) by the given factor.
650
+ out_dtype = None, # Convert the output to the specified data type.
651
+ **dynamic_kwargs): # Additional keyword arguments to pass into the network construction function.
652
+
653
+ assert len(in_arrays) == self.num_inputs
654
+ num_items = in_arrays[0].shape[0]
655
+ if minibatch_size is None:
656
+ minibatch_size = num_items
657
+ key = str([list(sorted(dynamic_kwargs.items())), num_gpus, out_mul, out_add, out_shrink, out_dtype])
658
+
659
+ # Build graph.
660
+ if key not in self._run_cache:
661
+ with absolute_name_scope(self.scope + '/Run'), tf.control_dependencies(None):
662
+ in_split = list(zip(*[tf.split(x, num_gpus) for x in self.input_templates]))
663
+ out_split = []
664
+ for gpu in range(num_gpus):
665
+ with tf.device('/gpu:%d' % gpu):
666
+ out_expr = self.get_output_for(*in_split[gpu], return_as_list=True, **dynamic_kwargs)
667
+ if out_mul != 1.0:
668
+ out_expr = [x * out_mul for x in out_expr]
669
+ if out_add != 0.0:
670
+ out_expr = [x + out_add for x in out_expr]
671
+ if out_shrink > 1:
672
+ ksize = [1, 1, out_shrink, out_shrink]
673
+ out_expr = [tf.nn.avg_pool(x, ksize=ksize, strides=ksize, padding='VALID', data_format='NCHW') for x in out_expr]
674
+ if out_dtype is not None:
675
+ if tf.as_dtype(out_dtype).is_integer:
676
+ out_expr = [tf.round(x) for x in out_expr]
677
+ out_expr = [tf.saturate_cast(x, out_dtype) for x in out_expr]
678
+ out_split.append(out_expr)
679
+ self._run_cache[key] = [tf.concat(outputs, axis=0) for outputs in zip(*out_split)]
680
+
681
+ # Run minibatches.
682
+ out_expr = self._run_cache[key]
683
+ out_arrays = [np.empty([num_items] + shape_to_list(expr.shape)[1:], expr.dtype.name) for expr in out_expr]
684
+ for mb_begin in range(0, num_items, minibatch_size):
685
+ if print_progress:
686
+ print('\r%d / %d' % (mb_begin, num_items), end='')
687
+ mb_end = min(mb_begin + minibatch_size, num_items)
688
+ mb_in = [src[mb_begin : mb_end] for src in in_arrays]
689
+ mb_out = tf.get_default_session().run(out_expr, dict(zip(self.input_templates, mb_in)))
690
+ for dst, src in zip(out_arrays, mb_out):
691
+ dst[mb_begin : mb_end] = src
692
+
693
+ # Done.
694
+ if print_progress:
695
+ print('\r%d / %d' % (num_items, num_items))
696
+ if not return_as_list:
697
+ out_arrays = out_arrays[0] if len(out_arrays) == 1 else tuple(out_arrays)
698
+ return out_arrays
699
+
700
+ # Returns a list of (name, output_expr, trainable_vars) tuples corresponding to
701
+ # individual layers of the network. Mainly intended to be used for reporting.
702
+ def list_layers(self):
703
+ patterns_to_ignore = ['/Setter', '/new_value', '/Shape', '/strided_slice', '/Cast', '/concat']
704
+ all_ops = tf.get_default_graph().get_operations()
705
+ all_ops = [op for op in all_ops if not any(p in op.name for p in patterns_to_ignore)]
706
+ layers = []
707
+
708
+ def recurse(scope, parent_ops, level):
709
+ prefix = scope + '/'
710
+ ops = [op for op in parent_ops if op.name == scope or op.name.startswith(prefix)]
711
+
712
+ # Does not contain leaf nodes => expand immediate children.
713
+ if level == 0 or all('/' in op.name[len(prefix):] for op in ops):
714
+ visited = set()
715
+ for op in ops:
716
+ suffix = op.name[len(prefix):]
717
+ if '/' in suffix:
718
+ suffix = suffix[:suffix.index('/')]
719
+ if suffix not in visited:
720
+ recurse(prefix + suffix, ops, level + 1)
721
+ visited.add(suffix)
722
+
723
+ # Otherwise => interpret as a layer.
724
+ else:
725
+ layer_name = scope[len(self.scope)+1:]
726
+ layer_output = ops[-1].outputs[0]
727
+ layer_trainables = [op.outputs[0] for op in ops if op.type.startswith('Variable') and self.get_var_localname(op.name) in self.trainables]
728
+ layers.append((layer_name, layer_output, layer_trainables))
729
+
730
+ recurse(self.scope, all_ops, 0)
731
+ return layers
732
+
733
+ # Print a summary table of the network structure.
734
+ def print_layers(self, title=None, hide_layers_with_no_params=False):
735
+ if title is None: title = self.name
736
+ print()
737
+ print('%-28s%-12s%-24s%-24s' % (title, 'Params', 'OutputShape', 'WeightShape'))
738
+ print('%-28s%-12s%-24s%-24s' % (('---',) * 4))
739
+
740
+ total_params = 0
741
+ for layer_name, layer_output, layer_trainables in self.list_layers():
742
+ weights = [var for var in layer_trainables if var.name.endswith('/weight:0')]
743
+ num_params = sum(np.prod(shape_to_list(var.shape)) for var in layer_trainables)
744
+ total_params += num_params
745
+ if hide_layers_with_no_params and num_params == 0:
746
+ continue
747
+
748
+ print('%-28s%-12s%-24s%-24s' % (
749
+ layer_name,
750
+ num_params if num_params else '-',
751
+ layer_output.shape,
752
+ weights[0].shape if len(weights) == 1 else '-'))
753
+
754
+ print('%-28s%-12s%-24s%-24s' % (('---',) * 4))
755
+ print('%-28s%-12s%-24s%-24s' % ('Total', total_params, '', ''))
756
+ print()
757
+
758
+ # Construct summary ops to include histograms of all trainable parameters in TensorBoard.
759
+ def setup_weight_histograms(self, title=None):
760
+ if title is None: title = self.name
761
+ with tf.name_scope(None), tf.device(None), tf.control_dependencies(None):
762
+ for localname, var in self.trainables.items():
763
+ if '/' in localname:
764
+ p = localname.split('/')
765
+ name = title + '_' + p[-1] + '/' + '_'.join(p[:-1])
766
+ else:
767
+ name = title + '_toplevel/' + localname
768
+ tf.summary.histogram(name, var)
769
+
770
+ #----------------------------------------------------------------------------
EEGFaceSem/pgan/util_scripts.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
2
+ #
3
+ # This work is licensed under the Creative Commons Attribution-NonCommercial
4
+ # 4.0 International License. To view a copy of this license, visit
5
+
6
+ # Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
7
+
8
+ import os
9
+ import time
10
+ import re
11
+ import bisect
12
+ from collections import OrderedDict
13
+ import numpy as np
14
+ import tensorflow as tf
15
+ import scipy.ndimage
16
+ import scipy.misc
17
+
18
+ import config
19
+ import misc
20
+ import tfutil
21
+ import train
22
+ import dataset
23
+
24
+ #----------------------------------------------------------------------------
25
+ # Generate random images or image grids using a previously trained network.
26
+ # To run, uncomment the appropriate line in config.py and launch train.py.
27
+
28
+ def generate_fake_images(run_id, snapshot=None, grid_size=[1,1], num_pngs=1, image_shrink=1, png_prefix=None, random_seed=1000, minibatch_size=8):
29
+ network_pkl = misc.locate_network_pkl(run_id, snapshot)
30
+ if png_prefix is None:
31
+ png_prefix = misc.get_id_string_for_network_pkl(network_pkl) + '-'
32
+ random_state = np.random.RandomState(random_seed)
33
+
34
+ print('Loading network from "%s"...' % network_pkl)
35
+ G, D, Gs = misc.load_network_pkl(run_id, snapshot)
36
+
37
+ result_subdir = misc.create_result_subdir(config.result_dir, config.desc)
38
+ for png_idx in range(num_pngs):
39
+ print('Generating png %d / %d...' % (png_idx, num_pngs))
40
+ latents = misc.random_latents(np.prod(grid_size), Gs, random_state=random_state)
41
+ labels = np.zeros([latents.shape[0], 0], np.float32)
42
+ images = Gs.run(latents, labels, minibatch_size=minibatch_size, num_gpus=config.num_gpus, out_mul=127.5, out_add=127.5, out_shrink=image_shrink, out_dtype=np.uint8)
43
+ misc.save_image_grid(images, os.path.join(result_subdir, '%s%06d.png' % (png_prefix, png_idx)), [0,255], grid_size)
44
+ open(os.path.join(result_subdir, '_done.txt'), 'wt').close()
45
+
46
+ #----------------------------------------------------------------------------
47
+ # Generate MP4 video of random interpolations using a previously trained network.
48
+ # To run, uncomment the appropriate line in config.py and launch train.py.
49
+
50
+ def generate_interpolation_video(run_id, snapshot=None, grid_size=[1,1], image_shrink=1, image_zoom=1, duration_sec=60.0, smoothing_sec=1.0, mp4=None, mp4_fps=30, mp4_codec='libx265', mp4_bitrate='16M', random_seed=1000, minibatch_size=8):
51
+ network_pkl = misc.locate_network_pkl(run_id, snapshot)
52
+ if mp4 is None:
53
+ mp4 = misc.get_id_string_for_network_pkl(network_pkl) + '-lerp.mp4'
54
+ num_frames = int(np.rint(duration_sec * mp4_fps))
55
+ random_state = np.random.RandomState(random_seed)
56
+
57
+ print('Loading network from "%s"...' % network_pkl)
58
+ G, D, Gs = misc.load_network_pkl(run_id, snapshot)
59
+
60
+ print('Generating latent vectors...')
61
+ shape = [num_frames, np.prod(grid_size)] + Gs.input_shape[1:] # [frame, image, channel, component]
62
+ all_latents = random_state.randn(*shape).astype(np.float32)
63
+ all_latents = scipy.ndimage.gaussian_filter(all_latents, [smoothing_sec * mp4_fps] + [0] * len(Gs.input_shape), mode='wrap')
64
+ all_latents /= np.sqrt(np.mean(np.square(all_latents)))
65
+
66
+ # Frame generation func for moviepy.
67
+ def make_frame(t):
68
+ frame_idx = int(np.clip(np.round(t * mp4_fps), 0, num_frames - 1))
69
+ latents = all_latents[frame_idx]
70
+ labels = np.zeros([latents.shape[0], 0], np.float32)
71
+ images = Gs.run(latents, labels, minibatch_size=minibatch_size, num_gpus=config.num_gpus, out_mul=127.5, out_add=127.5, out_shrink=image_shrink, out_dtype=np.uint8)
72
+ grid = misc.create_image_grid(images, grid_size).transpose(1, 2, 0) # HWC
73
+ if image_zoom > 1:
74
+ grid = scipy.ndimage.zoom(grid, [image_zoom, image_zoom, 1], order=0)
75
+ if grid.shape[2] == 1:
76
+ grid = grid.repeat(3, 2) # grayscale => RGB
77
+ return grid
78
+
79
+ # Generate video.
80
+ import moviepy.editor # pip install moviepy
81
+ result_subdir = misc.create_result_subdir(config.result_dir, config.desc)
82
+ moviepy.editor.VideoClip(make_frame, duration=duration_sec).write_videofile(os.path.join(result_subdir, mp4), fps=mp4_fps, codec='libx264', bitrate=mp4_bitrate)
83
+ open(os.path.join(result_subdir, '_done.txt'), 'wt').close()
84
+
85
+ #----------------------------------------------------------------------------
86
+ # Generate MP4 video of training progress for a previous training run.
87
+ # To run, uncomment the appropriate line in config.py and launch train.py.
88
+
89
+ def generate_training_video(run_id, duration_sec=20.0, time_warp=1.5, mp4=None, mp4_fps=30, mp4_codec='libx265', mp4_bitrate='16M'):
90
+ src_result_subdir = misc.locate_result_subdir(run_id)
91
+ if mp4 is None:
92
+ mp4 = os.path.basename(src_result_subdir) + '-train.mp4'
93
+
94
+ # Parse log.
95
+ times = []
96
+ snaps = [] # [(png, kimg, lod), ...]
97
+ with open(os.path.join(src_result_subdir, 'log.txt'), 'rt') as log:
98
+ for line in log:
99
+ k = re.search(r'kimg ([\d\.]+) ', line)
100
+ l = re.search(r'lod ([\d\.]+) ', line)
101
+ t = re.search(r'time (\d+d)? *(\d+h)? *(\d+m)? *(\d+s)? ', line)
102
+ if k and l and t:
103
+ k = float(k.group(1))
104
+ l = float(l.group(1))
105
+ t = [int(t.group(i)[:-1]) if t.group(i) else 0 for i in range(1, 5)]
106
+ t = t[0] * 24*60*60 + t[1] * 60*60 + t[2] * 60 + t[3]
107
+ png = os.path.join(src_result_subdir, 'fakes%06d.png' % int(np.floor(k)))
108
+ if os.path.isfile(png):
109
+ times.append(t)
110
+ snaps.append((png, k, l))
111
+ assert len(times)
112
+
113
+ # Frame generation func for moviepy.
114
+ png_cache = [None, None] # [png, img]
115
+ def make_frame(t):
116
+ wallclock = ((t / duration_sec) ** time_warp) * times[-1]
117
+ png, kimg, lod = snaps[max(bisect.bisect(times, wallclock) - 1, 0)]
118
+ if png_cache[0] == png:
119
+ img = png_cache[1]
120
+ else:
121
+ img = scipy.misc.imread(png)
122
+ while img.shape[1] > 1920 or img.shape[0] > 1080:
123
+ img = img.astype(np.float32).reshape(img.shape[0]//2, 2, img.shape[1]//2, 2, -1).mean(axis=(1,3))
124
+ png_cache[:] = [png, img]
125
+ img = misc.draw_text_label(img, 'lod %.2f' % lod, 16, img.shape[0]-4, alignx=0.0, aligny=1.0)
126
+ img = misc.draw_text_label(img, misc.format_time(int(np.rint(wallclock))), img.shape[1]//2, img.shape[0]-4, alignx=0.5, aligny=1.0)
127
+ img = misc.draw_text_label(img, '%.0f kimg' % kimg, img.shape[1]-16, img.shape[0]-4, alignx=1.0, aligny=1.0)
128
+ return img
129
+
130
+ # Generate video.
131
+ import moviepy.editor # pip install moviepy
132
+ result_subdir = misc.create_result_subdir(config.result_dir, config.desc)
133
+ moviepy.editor.VideoClip(make_frame, duration=duration_sec).write_videofile(os.path.join(result_subdir, mp4), fps=mp4_fps, codec='libx264', bitrate=mp4_bitrate)
134
+ open(os.path.join(result_subdir, '_done.txt'), 'wt').close()
135
+
136
+ #----------------------------------------------------------------------------
137
+ # Evaluate one or more metrics for a previous training run.
138
+ # To run, uncomment one of the appropriate lines in config.py and launch train.py.
139
+
140
+ def evaluate_metrics(run_id, log, metrics, num_images, real_passes, minibatch_size=None):
141
+ metric_class_names = {
142
+ 'swd': 'metrics.sliced_wasserstein.API',
143
+ 'fid': 'metrics.frechet_inception_distance.API',
144
+ 'is': 'metrics.inception_score.API',
145
+ 'msssim': 'metrics.ms_ssim.API',
146
+ }
147
+
148
+ # Locate training run and initialize logging.
149
+ result_subdir = misc.locate_result_subdir(run_id)
150
+ snapshot_pkls = misc.list_network_pkls(result_subdir, include_final=False)
151
+ assert len(snapshot_pkls) >= 1
152
+ log_file = os.path.join(result_subdir, log)
153
+ print('Logging output to', log_file)
154
+ misc.set_output_log_file(log_file)
155
+
156
+ # Initialize dataset and select minibatch size.
157
+ dataset_obj, mirror_augment = misc.load_dataset_for_previous_run(result_subdir, verbose=True, shuffle_mb=0)
158
+ if minibatch_size is None:
159
+ minibatch_size = np.clip(8192 // dataset_obj.shape[1], 4, 256)
160
+
161
+ # Initialize metrics.
162
+ metric_objs = []
163
+ for name in metrics:
164
+ class_name = metric_class_names.get(name, name)
165
+ print('Initializing %s...' % class_name)
166
+ class_def = tfutil.import_obj(class_name)
167
+ image_shape = [3] + dataset_obj.shape[1:]
168
+ obj = class_def(num_images=num_images, image_shape=image_shape, image_dtype=np.uint8, minibatch_size=minibatch_size)
169
+ tfutil.init_uninited_vars()
170
+ mode = 'warmup'
171
+ obj.begin(mode)
172
+ for idx in range(10):
173
+ obj.feed(mode, np.random.randint(0, 256, size=[minibatch_size]+image_shape, dtype=np.uint8))
174
+ obj.end(mode)
175
+ metric_objs.append(obj)
176
+
177
+ # Print table header.
178
+ print()
179
+ print('%-10s%-12s' % ('Snapshot', 'Time_eval'), end='')
180
+ for obj in metric_objs:
181
+ for name, fmt in zip(obj.get_metric_names(), obj.get_metric_formatting()):
182
+ print('%-*s' % (len(fmt % 0), name), end='')
183
+ print()
184
+ print('%-10s%-12s' % ('---', '---'), end='')
185
+ for obj in metric_objs:
186
+ for fmt in obj.get_metric_formatting():
187
+ print('%-*s' % (len(fmt % 0), '---'), end='')
188
+ print()
189
+
190
+ # Feed in reals.
191
+ for title, mode in [('Reals', 'reals'), ('Reals2', 'fakes')][:real_passes]:
192
+ print('%-10s' % title, end='')
193
+ time_begin = time.time()
194
+ labels = np.zeros([num_images, dataset_obj.label_size], dtype=np.float32)
195
+ [obj.begin(mode) for obj in metric_objs]
196
+ for begin in range(0, num_images, minibatch_size):
197
+ end = min(begin + minibatch_size, num_images)
198
+ images, labels[begin:end] = dataset_obj.get_minibatch_np(end - begin)
199
+ if mirror_augment:
200
+ images = misc.apply_mirror_augment(images)
201
+ if images.shape[1] == 1:
202
+ images = np.tile(images, [1, 3, 1, 1]) # grayscale => RGB
203
+ [obj.feed(mode, images) for obj in metric_objs]
204
+ results = [obj.end(mode) for obj in metric_objs]
205
+ print('%-12s' % misc.format_time(time.time() - time_begin), end='')
206
+ for obj, vals in zip(metric_objs, results):
207
+ for val, fmt in zip(vals, obj.get_metric_formatting()):
208
+ print(fmt % val, end='')
209
+ print()
210
+
211
+ # Evaluate each network snapshot.
212
+ for snapshot_idx, snapshot_pkl in enumerate(reversed(snapshot_pkls)):
213
+ prefix = 'network-snapshot-'; postfix = '.pkl'
214
+ snapshot_name = os.path.basename(snapshot_pkl)
215
+ assert snapshot_name.startswith(prefix) and snapshot_name.endswith(postfix)
216
+ snapshot_kimg = int(snapshot_name[len(prefix) : -len(postfix)])
217
+
218
+ print('%-10d' % snapshot_kimg, end='')
219
+ mode ='fakes'
220
+ [obj.begin(mode) for obj in metric_objs]
221
+ time_begin = time.time()
222
+ with tf.Graph().as_default(), tfutil.create_session(config.tf_config).as_default():
223
+ G, D, Gs = misc.load_pkl(snapshot_pkl)
224
+ for begin in range(0, num_images, minibatch_size):
225
+ end = min(begin + minibatch_size, num_images)
226
+ latents = misc.random_latents(end - begin, Gs)
227
+ images = Gs.run(latents, labels[begin:end], num_gpus=config.num_gpus, out_mul=127.5, out_add=127.5, out_dtype=np.uint8)
228
+ if images.shape[1] == 1:
229
+ images = np.tile(images, [1, 3, 1, 1]) # grayscale => RGB
230
+ [obj.feed(mode, images) for obj in metric_objs]
231
+ results = [obj.end(mode) for obj in metric_objs]
232
+ print('%-12s' % misc.format_time(time.time() - time_begin), end='')
233
+ for obj, vals in zip(metric_objs, results):
234
+ for val, fmt in zip(vals, obj.get_metric_formatting()):
235
+ print(fmt % val, end='')
236
+ print()
237
+ print()
238
+
239
+ #----------------------------------------------------------------------------
EEGFaceSem/preprocess.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import mne
2
+ from os import path, listdir
3
+ import numpy as np
4
+ import pandas as pd
5
+ import pickle
6
+ import os
7
+ import re
8
+ print('mne version', mne.__version__)
9
+ mne.set_log_level('WARNING')
10
+
11
+ indir = './data/raw/'
12
+ outdir = './data/processed/'
13
+ os.makedirs(outdir, exist_ok=True)
14
+ flist = [f for f in sorted(os.listdir(indir)) if f.endswith('.vhdr')]
15
+ for idx in range(len(flist)):
16
+ fname = flist[idx]
17
+ filename = os.path.join(indir, fname)
18
+
19
+ stem = '.'.join(fname.split('.')[:-1])
20
+ print(f"BEGIN {stem}.vhdr")
21
+
22
+ raw = mne.io.read_raw_brainvision(filename, eog=('HEOG','VEOG'), preload=True)
23
+ raw.set_montage('standard_1020')
24
+ def s2i(s):
25
+ m = re.search(r"[0-9]+$", s)
26
+ return int(0 if not m else m[0])
27
+ events, _ = mne.events_from_annotations(raw, event_id=s2i)
28
+ (raw, events) = raw.resample(500, events=events, n_jobs=3)
29
+ raw.filter(0.2, 35., fir_design='firwin', n_jobs=3)
30
+
31
+ # 2
32
+ stim_on_evs = events[(events[:, 2] > 200) & (events[:, 2] < 205)]
33
+ ev2img = pd.DataFrame(stim_on_evs[:,2], columns=['event'], index=stim_on_evs[:,0])
34
+ ev2img['img'] = 'NONE'
35
+ ev2img['rel'] = 0
36
+ curimg = ''
37
+ we = events.copy()
38
+ for i, e in enumerate(events):
39
+ if i < 3:
40
+ continue
41
+ cur = e[2]
42
+ l1 = events[i-1, 2]
43
+ l2 = events[i-2, 2]
44
+ if cur < 200 and l1 < 200 and l2 < 200:
45
+ curimg = str(l2)[1:] + str(l1)[1:] + str(cur)[2:]
46
+ elif cur > 200 and cur < 205 and l1 != 231 and l1 != 232: # stim on, skip neighbor
47
+ ev2img.loc[e[0], 'img'] = curimg
48
+ if cur == 201: # facecat rel
49
+ ev2img.loc[e[0], 'rel'] = 1
50
+ we[i, 1] = 1
51
+ if l1 > 220 and l1 < 242: # replace stim marker with group marker, forget rel
52
+ events[i, 2] = 1000 + l1
53
+ we[i, 2] = 1000 + l1
54
+
55
+ events = np.delete(events, np.where(events[:, 2] < 1000), axis=0)
56
+
57
+ # 3
58
+ ev = {
59
+ 'facecat/male': 1223,
60
+ 'facecat/female': 1224,
61
+ 'facecat/old': 1225,
62
+ 'facecat/young': 1226,
63
+ 'facecat/smiles': 1227,
64
+ 'facecat/nosmile': 1228,
65
+ 'facecat/blond': 1229,
66
+ 'facecat/darkhaired': 1230,
67
+ }
68
+
69
+ epochs = mne.Epochs(raw, events=events, event_id=ev,tmin=-.2,tmax=0.9,on_missing='warn',preload=True)
70
+ ev2img = ev2img.loc[epochs.events[:,0]]
71
+ epochs.metadata = ev2img
72
+ epochs.apply_baseline((-.2,0))
73
+ (mini, maxi) = epochs.time_as_index([0, 0.5], use_rounding=True)
74
+
75
+ # 4
76
+ bad_chs = "FT9,FT10,T7,T8,Iz,HEOG,VEOG,STI 014".split(',')
77
+ good_ch_indices = mne.pick_channels(epochs.info['ch_names'], [], exclude=bad_chs)
78
+ epochs2 = epochs.get_data()[:, good_ch_indices, mini:maxi] * 1e6
79
+ cutoff = np.sort(np.max(np.absolute(epochs2[:2000]), axis=(1,2)))[-200]
80
+ cutoff = np.max((10, np.min((cutoff, 80))))
81
+ bad_epo = []
82
+ for i in range(0, len(epochs2)):
83
+ if (np.max(np.absolute(epochs2[i])) > cutoff
84
+ or np.var(epochs2[i]) < 0.5):
85
+ bad_epo.append(i)
86
+ epochs.drop(bad_epo)
87
+ # print stats of each type of epochs
88
+ for k in ev.keys():
89
+ print(stem, k.split('/')[-1], len(epochs[k]))
90
+
91
+ # 5
92
+ epochs.save(f'{outdir}/{stem}-epo.fif', overwrite=True)
93
+ pickle.dump(ev2img, open(f'{outdir}/{stem}-ev2img.pkl', 'wb'))
EEGFaceSem/utils.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import pickle
3
+ import mne
4
+ import os
5
+ import numpy as np
6
+
7
+ def load_latent(latent_dir=None):
8
+ """
9
+ Load latent vectors for stimulus images.
10
+
11
+ Returns:
12
+ image_ids: list of image IDs
13
+ latents: numpy array of shape (n_images, 512)
14
+ id_to_idx: dict mapping image_id -> index in latents array
15
+ """
16
+ if latent_dir is None:
17
+ # Try to find from package cache
18
+ from .download import get_data_dir
19
+ data_dir = get_data_dir()
20
+ latent_dir = data_dir / "data" / "latents"
21
+
22
+ fpath = os.path.join(latent_dir, 'latent.pkl')
23
+ if not os.path.exists(fpath):
24
+ raise FileNotFoundError(f"Latent file not found: {fpath}. Run EEGFaceSem.download_latents() first.")
25
+
26
+ image_ids, latents = pickle.load(open(fpath, 'rb'))
27
+ image_ids = list(image_ids)
28
+ id_to_idx = {image_ids[i]: i for i in range(len(image_ids))}
29
+ return image_ids, latents, id_to_idx
30
+
31
+ def load_epochs(indir='./data/processed/', cache=True):
32
+ flist = [f for f in sorted(os.listdir(indir)) if f.endswith('-epo.fif')]
33
+ epochs = []
34
+ ev2img = []
35
+ for f in flist:
36
+ filename = f'{indir}/{f}'
37
+ epochs.append(mne.read_epochs(filename))
38
+ ff = f.replace('-epo.fif', '-ev2img.pkl')
39
+ ev2img.append(pickle.load(open(f'{indir}/{ff}', 'rb')))
40
+ return epochs, ev2img
41
+
42
+ def load_from_processed(indir='./data/processed/', cache=True, task=None):
43
+ cache_name = f'{indir}/cache_{task.split("/")[-1]}.pkl' if task is not None else f'{indir}/cache.pkl'
44
+ if cache and os.path.exists(cache_name):
45
+ return pickle.load(open(cache_name, 'rb'))
46
+ all_tasks = ['facecat/female', 'facecat/male', 'facecat/blond', 'facecat/darkhaired', 'facecat/smiles', 'facecat/nosmile', 'facecat/old', 'facecat/young']
47
+ flist = [f for f in sorted(os.listdir(indir)) if f.endswith('-epo.fif')]
48
+ Z, Y, D = [], [], []
49
+ for fidx, f in enumerate(flist):
50
+ filename = f'{indir}/{f}'
51
+ epochs = mne.read_epochs(filename, verbose=0)
52
+ ff = f.replace('-epo.fif', '-ev2img.pkl')
53
+ # ev2img = pickle.load(open(f'{indir}/{ff}', 'rb'))
54
+
55
+ for tid, t in enumerate(all_tasks):
56
+ if task is not None and t != task:
57
+ continue
58
+ ev = epochs[t].metadata
59
+ data = epochs[t].get_data(copy=False)
60
+ for i in range(ev.shape[0]):
61
+ img = int(ev['img'].iloc[i])
62
+ rel = int(ev['rel'].iloc[i])
63
+ z = data[i:i+1].flatten()*1000.0
64
+ Z.append(z)
65
+ Y.append(rel)
66
+ D.append((fidx, tid, i, rel, img))
67
+ Z = np.array(Z)
68
+ Y = np.array(Y)
69
+ D = np.array(D)
70
+ if cache:
71
+ pickle.dump((Z, Y, D), open(cache_name, 'wb'))
72
+ return Z, Y, D
73
+
74
+
75
+ import scipy
76
+ import scipy.ndimage
77
+ class Dataset:
78
+ def __init__(self, indir = "", cache = None, chs = 32, samples = 1101, task=None):
79
+ self.indir = indir
80
+ self.cache = cache
81
+ self.chs = chs
82
+ self.samples = samples
83
+ self.task = task
84
+ if len(indir) > 0:
85
+ self.load(indir, cache, task)
86
+
87
+ def load(self, indir='./data/processed/', cache=True, task=None):
88
+ self.X, self.Y, self.ids = load_from_processed(indir, cache, task)
89
+ self.X = self.X.reshape([self.X.shape[0], 34, self.samples])[:, :self.chs, :].reshape([self.X.shape[0], -1])
90
+ # lx, ly, lxd = load_latent(self.indir)
91
+ # self.imgs = list(lx)
92
+ # self.vecs = np.array(ly)
93
+ # self.img2idx = { img:idx for idx, img in enumerate(self.imgs)}
94
+ # ys[i] = self.vecs[self.img2idx[img]]
95
+
96
+ def normalize(self):
97
+ self.X = self.X.reshape([self.X.shape[0], 32, self.samples])
98
+ self.X = self.X[:, :self.chs, :].transpose([0, 2, 1])
99
+ self.X_m = np.mean(self.X, axis=(0, 1))
100
+ self.X_s = np.std(self.X, axis=(0, 1))
101
+ eps = 10**-10
102
+ self.X = (self.X - self.X_m) / (self.X_s + eps)
103
+ self.X = self.X.transpose([0, 2, 1]).reshape([self.X.shape[0], self.chs, self.samples])
104
+
105
+ # # Y = Y
106
+
107
+ # self.Y_m = np.mean(self.Y, axis=(0,))
108
+ # self.Y_s = np.std(self.Y, axis=(0,))
109
+ # eps = 10**-10
110
+ # self.Y = (self.Y - self.Y_m) / (self.Y_s + eps)
111
+
112
+
113
+ def normalize_by(self, other):
114
+ self.X = self.X.reshape([self.X.shape[0], 32, self.samples])
115
+ self.X = self.X[:, :self.chs, :].transpose([0, 2, 1])
116
+ # self.X_m = np.mean(self.X, axis=(0, 1))
117
+ # self.X_s = np.std(self.X, axis=(0, 1))
118
+ self.X_m, self.X_s = other.X_m, other.X_s
119
+ eps = 10**-10
120
+ self.X = (self.X - self.X_m) / (self.X_s + eps)
121
+ self.X = self.X.transpose([0, 2, 1]).reshape([self.X.shape[0], self.chs, self.samples])
122
+
123
+ # Y = Y
124
+ # self.Y_m = np.mean(self.Y, axis=(0,))
125
+ # self.Y_s = np.std(self.Y, axis=(0,))
126
+ # self.Y_m, self.Y_s = other.Y_m, other.Y_s
127
+ # eps = 10**-10
128
+ # self.Y = (self.Y - self.Y_m) / (self.Y_s + eps)
129
+
130
+ def subset(self, ids):
131
+ ret = Dataset(self.indir, self.cache, self.chs, self.samples)
132
+ ret.X = self.X[ids]
133
+ ret.Y = self.Y[ids]
134
+ ret.ids = self.ids[ids]
135
+ return ret
136
+
137
+ def split(self, valid_n):
138
+ ids = np.arange(self.X.shape[0])
139
+ np.random.shuffle(ids)
140
+ tmpids = []
141
+ ccnt = {}
142
+ for i in list(ids):
143
+ idx = (self.ids[i, 1], self.ids[i, 2])
144
+ if idx not in ccnt:
145
+ ccnt[idx] = 0
146
+ ccnt[idx] += 1
147
+ tmpids.append((ccnt[idx], i))
148
+ ids = np.array([i for _, i in sorted(tmpids)])
149
+
150
+ valid = self.subset(ids[:valid_n])
151
+ train = self.subset(ids[valid_n:])
152
+ return valid, train
153
+
154
+ def kfold(self, k = 10, mixed = False):
155
+ # by default, split with subject separation
156
+ if mixed:
157
+ ids = np.arange(self.X.shape[0])
158
+ np.random.shuffle(ids)
159
+ ii = np.arange(self.X.shape[0])
160
+ for i in range(k):
161
+ selected = (ids % k == i)
162
+ unselected = (ids % k != i)
163
+ valid = self.subset(selected)
164
+ train = self.subset(unselected)
165
+ yield valid, train
166
+ else:
167
+ # shuffle by unique (fidx)
168
+ fids = np.unique(self.ids[:, 0])
169
+ np.random.shuffle(fids)
170
+ for i in range(k):
171
+ selected = np.isin(self.ids[:, 0], fids[i::k])
172
+ unselected = ~selected
173
+ valid = self.subset(selected)
174
+ train = self.subset(unselected)
175
+ yield valid, train
176
+
177
+
178
+
179
+ def apply_random_transform(self, btx, bty):
180
+ retx, rety = [], []
181
+ m = btx.shape[0]
182
+ for i in range(m):
183
+ e = btx[i].reshape((self.chs, self.samples))
184
+ v = bty[i]
185
+
186
+ # only first self.chs channels
187
+ cs = np.random.normal(size = [self.chs, 1]) * 0.05 + 1
188
+ e = cs * e[:self.chs]
189
+ es =[]
190
+ for c in range(self.chs):
191
+ # [-0.2, 0.9] -> [0, 550] len(self.samples)
192
+ # [0.0, 0.6] -> [100, 400]
193
+ d = 25
194
+ l, r = np.random.randint(25-d, 25+d+1), np.random.randint(525-d, 525+d+1)
195
+ t = e[c][l:r]
196
+ t = scipy.ndimage.zoom(t, 500/len(t), order=1)
197
+ es.append(t)
198
+ e = np.stack(es)
199
+ retx.append(e)
200
+ rety.append(v)
201
+
202
+ retx = np.array(np.stack(retx))
203
+ rety = np.array(np.stack(rety))
204
+ return retx, rety
205
+ def apply_clean_transform(self, btx, bty):
206
+ retx, rety = [], []
207
+ m = btx.shape[0]
208
+ for i in range(m):
209
+ e = btx[i].reshape((self.chs, self.samples))
210
+ v = bty[i]
211
+
212
+ # only first self.chs channels
213
+ e = e[:self.chs]
214
+ es =[]
215
+ for c in range(self.chs):
216
+ l, r = 25, 525
217
+ t = e[c][l:r]
218
+ t = scipy.ndimage.zoom(t, 500/len(t), order=1)
219
+ es.append(t)
220
+ e = np.stack(es)
221
+ retx.append(e)
222
+ rety.append(v)
223
+
224
+ retx = np.array(np.stack(retx))
225
+ rety = np.array(np.stack(rety))
226
+ return retx, rety
227
+
228
+ def for_each_batch(self, batch_size = 256, shuffle = False):
229
+ ids = np.arange(self.X.shape[0])
230
+ if shuffle:
231
+ np.random.shuffle(ids)
232
+ for i in range(0, len(ids), batch_size):
233
+ bt_ids = ids[i : i + batch_size]
234
+ bt_x = self.X[bt_ids]
235
+ bt_y = self.Y[bt_ids]
236
+ bt_info = self.ids[bt_ids]
237
+ yield bt_ids, bt_x, bt_y, bt_info
238
+
239
+ def compute_cluster_accuracy(self, c_target, c_non):
240
+ tp, total = 0, 0
241
+ for i, j in [(c_target, 1), (c_non, 0)]:
242
+ tp += (self.ids[i, 2]==j).sum()
243
+ total += i.shape[0]
244
+ assert(total == self.X.shape[0])
245
+ return tp / total
README.md CHANGED
@@ -1,3 +1,110 @@
1
- ---
2
- license: apache-2.0
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # EEGFaceSem
2
+
3
+ EEG Dataset for Semantic Visual Response - CVPR 2024
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ pip install -e .
9
+ ```
10
+
11
+ For deep learning models:
12
+ ```bash
13
+ pip install -e ".[full]" # TensorFlow + PyTorch + Pillow
14
+ ```
15
+
16
+ ## Quick Start
17
+
18
+ ```python
19
+ import EEGFaceSem
20
+
21
+ # Download data (auto-downloads to ~/.cache/EEGFaceSem)
22
+ EEGFaceSem.download()
23
+
24
+ # Load data for a specific task
25
+ X, Y, ids = EEGFaceSem.load_data(task='female')
26
+ print(f"X: {X.shape}, Y: {Y.shape}") # X: (n_trials, 32, 1101), Y: (n_trials,)
27
+
28
+ # Split data
29
+ (X_train, Y_train), (X_test, Y_test) = EEGFaceSem.split_random(X, Y)
30
+
31
+ # Run benchmark
32
+ EEGFaceSem.benchmark(model='LDA')
33
+ ```
34
+
35
+ ## Dataset Info
36
+
37
+ | Metric | Value |
38
+ |--------|-------|
39
+ | Subjects | 30 |
40
+ | Total epochs | 64,124 |
41
+ | EEG channels | 32 |
42
+ | Sampling rate | 500 Hz |
43
+ | Epoch window | [-0.2, 0.9]s |
44
+
45
+ ### 8 Tasks
46
+
47
+ | Task ID | Task Name |
48
+ |---------|-----------|
49
+ | 0 | female |
50
+ | 1 | male |
51
+ | 2 | blond |
52
+ | 3 | darkhaired |
53
+ | 4 | smiles |
54
+ | 5 | nosmile |
55
+ | 6 | old |
56
+ | 7 | young |
57
+
58
+ ## API Reference
59
+
60
+ ### Data Loading
61
+
62
+ ```python
63
+ # Download data
64
+ EEGFaceSem.download(data_dir="./data", data_type="processed") # or "raw", "both"
65
+
66
+ # Load data
67
+ X, Y, ids = EEGFaceSem.load_data(task='female') # or task_id=0
68
+ ```
69
+
70
+ ### Splitting
71
+
72
+ ```python
73
+ # Random split
74
+ (X_train, Y_train), (X_test, Y_test) = EEGFaceSem.split_random(X, Y, test_size=0.2)
75
+
76
+ # Leave-one-subject-out
77
+ (X_train, Y_train), (X_test, Y_test) = EEGFaceSem.split_by_subject(X, Y, ids, test_subject=1)
78
+ ```
79
+
80
+ ### Benchmarking
81
+
82
+ ```python
83
+ EEGFaceSem.benchmark(
84
+ model='LDA', # LDA, LR, MLP, EEGNet, EEGPT
85
+ task_id=0, # 0-7 or -1 for all
86
+ strategy='single_subject', # single_subject, cross_subject, subject_adapted
87
+ epochs=100,
88
+ batch_size=32,
89
+ lr=0.001
90
+ )
91
+ ```
92
+
93
+ ### Image Generation
94
+
95
+ ```python
96
+ import numpy as np
97
+ images = EEGFaceSem.generate(np.random.randn(1, 512))
98
+ images[0].save("generated_face.png")
99
+ ```
100
+
101
+ ## Citation
102
+
103
+ ```bibtex
104
+ @inproceedings{eegfacesem2024,
105
+ title={EEGFaceSem: ...},
106
+ author={...},
107
+ booktitle={CVPR},
108
+ year={2024}
109
+ }
110
+ ```
README_code.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Supplementary Material: EEGFaceSem
2
+
3
+ This repository contains the official implementation for the paper "EEGFaceSem". It provides the necessary code to reproduce the benchmarking results, generate images from latent vectors, and preprocess the dataset from raw files.
4
+
5
+ ## Introduction
6
+
7
+ This package, `EEGFaceSem`, provides tools to:
8
+ 1. Benchmark EEG classification models, including LDA, EEGNet, and our proposed EEGPT model.
9
+ 2. Generate facial images from EEG signals using a pretrained Progressive GAN model.
10
+ 3. Prepare the dataset from raw files.
11
+
12
+ ## Installation
13
+
14
+ To get started, clone this repository and install the package using pip. We recommend using a virtual environment.
15
+
16
+ ```bash
17
+ pip install -r requirements.txt
18
+ pip install .
19
+ ```
20
+
21
+ ## Dataset
22
+
23
+ This project uses the EEGFaceSem dataset. Due to its size, the data is not included in this repository.
24
+
25
+ **Option 1: Download Processed Data (Recommended)**
26
+
27
+ You can download the preprocessed data files directly from OSF at [Link removed for review purposes] or Hugging Face at [Link removed for review purposes].
28
+
29
+ Download the files and place them in the `data/processed/` directory.
30
+
31
+ **Option 2: Process Raw Data**
32
+
33
+ 1. Download the raw data from OSF at [Link removed for review purposes].
34
+ 2. Place the downloaded files into the `data/raw/` directory.
35
+ 3. Run the preparation script:
36
+ ```python
37
+ import EEGFaceSem
38
+
39
+ EEGFaceSem.prepare_data()
40
+ ```
41
+ This will process the raw files and save the results in `data/processed/`, which will be used by the benchmark scripts.
42
+
43
+ ## Usage
44
+
45
+ The core functionalities are exposed through the `EEGFaceSem` package.
46
+
47
+ ### Benchmarking
48
+
49
+ You can run the benchmarks for different models directly from Python. The results will be saved to a `logs/` directory.
50
+
51
+ ```python
52
+ import EEGFaceSem
53
+
54
+ # Run the benchmark for the LDA model
55
+ EEGFaceSem.benchmark(models="LDA")
56
+
57
+ # Run the benchmark for the EEGPT model
58
+ EEGFaceSem.benchmark_eegpt()
59
+ ```
60
+
61
+ ### Image Generation from Latent Vectors
62
+
63
+ To generate an image from a latent vector using the pretrained Progressive GAN model, use the following function.
64
+
65
+ ```python
66
+ import EEGFaceSem
67
+ import numpy as np
68
+ images = EEGFaceSem.generate(np.random.randn(1, 512))
69
+ images[0].save("generated_face.png")
70
+ ```
71
+
72
+ ## Repository Structure
73
+
74
+ ```
75
+ EEGFaceSem/
76
+ ├── EEGFaceSem/ # The installable Python package
77
+ │ ├── __init__.py
78
+ │ ├── benchmark.py # Code for LDA, EEGNet benchmarks
79
+ │ ├── generation.py # Image generation logic
80
+ │ ├── preprocess.py # Data preparation script
81
+ │ ├── models.py # Model definitions
82
+ │ ├── utils.py # Data loading and utility functions
83
+ │ ├── EEGModels.py # EEGNet definitions
84
+ │ └── EEGPT/ # Submodule for EEGPT dependencies
85
+ │ └── ...
86
+ │ └── pgan/ # Submodule for Progressive GAN dependencies
87
+ │ └── ...
88
+ ├── data/
89
+ │ ├── raw/ # (Empty) For raw data
90
+ │ └── processed/ # (Empty) For processed data
91
+ ├── models/
92
+ │ ├── eegpt_mcae_58chs_4s_large4E.ckpt # (Empty) Pretrained EEGPT model to be downloaded
93
+ │ └── karras2018iclr-celebahq-1024x1024.pkl # (Empty) Pretrained Progressive GAN model to be downloaded
94
+ ├── scripts/
95
+ │ └── summarize_results.py # Script to evaluate benchmark outputs
96
+ ├── README.md
97
+ ├── setup.py
98
+ └── requirements.txt
99
+ ```
data/latents/latent.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b14482ddfcc261e55c7266665ccd2a30a2cb015b073fe4a1faa092e5da862272
3
+ size 9931913
data/processed/01-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3ac2a7958d9661acbae4ed99931a7f68ad50504956187d11362f5b6930e9e7b
3
+ size 301527920
data/processed/01-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:13bc4cf1f2bfc12e409de480e80e0e4a3ab9a1386a19982d5e870a97f6d5b03e
3
+ size 54561
data/processed/02-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:448b991cdfc94997f2e269429457db88ca8a8c4ff59b89fd2d0ef288042537ac
3
+ size 303625036
data/processed/02-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8ae51dc0ced8b51714c5fb6a66c00dae1e8cfbde43c556ffa2463db205c159c1
3
+ size 54538
data/processed/03-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8d0168c0ade1b638e328e2b80157a1838fac496765304350560a5333140cbd46
3
+ size 299580584
data/processed/03-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:29ed405946102e1c6dc9bf4bff218da9a665091eb53460e801f836d7dba53eef
3
+ size 54561
data/processed/04-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3da6e84ec56fa3fb7a62b9edd19df13845b433b2d900d82a2c4c68ca86f4fb50
3
+ size 303455983
data/processed/04-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:57d0b21603a2e2e316ed3019903fef3f0d3accc6882f8475dc218ec247a0024d
3
+ size 54563
data/processed/05-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa9b560781df8fad1b557aeb1a8a8ec1efd4c01d131d94a47bbd8fe9d1ce9bd6
3
+ size 301944877
data/processed/05-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2274bfb62a3b0ba7378a1d0e1407a2e9fe0d08fee3f2accb553043bada081168
3
+ size 54558
data/processed/06-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0dd028681e6f77b799e37a209a05704dd8843ff6e222b56af3214b15bbc1f78b
3
+ size 304205063
data/processed/06-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0efd3dd357dc8c332c86a76f4587a3e87706d4a0cb4049ddf7aa9fa2abd20e4f
3
+ size 54582
data/processed/07-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:8cc168b50d1cf24c0612a4cd24fced6f743945d573a6374bd9ee7975a59270ad
3
+ size 271419171
data/processed/07-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5889b43e88acbeaaec82332b3ab72ccd2cf8d065473ce0e0b4fbf858fb71f029
3
+ size 54515
data/processed/08-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:5b8a4074b30a79d9a1385f54a3db8dcc8cff171571b291adacd3775eb4f2e9a3
3
+ size 305852813
data/processed/08-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:22d527c375f05a461b0ffb9268a3cc1ec2e098773386b48cf19db0a1fbfaa771
3
+ size 54536
data/processed/09-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b6aaa5977f510f3b2202241a9923d59875b359491b0f304be966c7cc8e81798b
3
+ size 231274236
data/processed/09-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4671ab0941e5d10ca906ed6f81e6be3aa8c181be90b4ae0c1e0b762636ee19ba
3
+ size 54560
data/processed/10-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c479f664a972609892a82d993f176a2f80a733566f322e75d42b96db9d7cefe0
3
+ size 304360016
data/processed/10-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c8111a4a91b8ffccdbccd8a58ea0b6c0d2ade0a5a82284532dd9274d0e28cc2a
3
+ size 54561
data/processed/11-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fb4251ddc106fd5bddb7fe1279b74d15acdfb36961c8129e413e626e7a4038b5
3
+ size 300759608
data/processed/11-ev2img.pkl ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a1a6af2beb741636fc99813a25d27357be3d1906c8afae628f062e7c2c380041
3
+ size 54514
data/processed/12-epo.fif ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3dd9dcafacce72d9974b76c62704afe834e39762da693ee407f0e4fb38cb822b
3
+ size 256142968