-
Notifications
You must be signed in to change notification settings - Fork 8
/
classifier_sample.py
339 lines (292 loc) · 13.7 KB
/
classifier_sample.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
"""
Like image_sample.py, but use a noisy image classifier to guide the sampling
process towards more realistic images.
"""
import argparse
import numpy as np
import torch as th
import torch.distributed as dist
import torch.nn.functional as F
from guided_diffusion import dist_util, logger
from guided_diffusion.script_util import (
NUM_CLASSES,
model_and_diffusion_defaults,
classifier_and_diffusion_defaults,
create_model_and_diffusion,
create_classifier,
add_dict_to_argparser,
args_to_dict,
)
import scanpy as sc
import torch
from VAE.VAE_model import VAE
def load_VAE(ae_dir, num_gene):
autoencoder = VAE(
num_genes=num_gene,
device='cuda',
seed=0,
hidden_dim=128,
decoder_activation='ReLU',
)
autoencoder.load_state_dict(torch.load(ae_dir))
return autoencoder
def save_data(all_cells, traj, data_dir):
cell_gen = all_cells
np.savez(data_dir, cell_gen=cell_gen)
return
def main(cell_type=[0], multi=False, inter=False, weight=[10,10]):
args = create_argparser(cell_type, weight).parse_args()
dist_util.setup_dist()
logger.configure()
logger.log("creating model and diffusion...")
model, diffusion = create_model_and_diffusion(
**args_to_dict(args, model_and_diffusion_defaults().keys())
)
model.load_state_dict(
dist_util.load_state_dict(args.model_path, map_location="cpu")
)
model.to(dist_util.dev())
model.eval()
logger.log("loading classifier...")
if multi:
args.num_class = args.num_class1 # how many classes in this condition
classifier1 = create_classifier(**args_to_dict(args, (['num_class']+list(classifier_and_diffusion_defaults().keys()))[:3]))
classifier1.load_state_dict(
dist_util.load_state_dict(args.classifier_path1, map_location="cpu")
)
classifier1.to(dist_util.dev())
classifier1.eval()
args.num_class = args.num_class2 # how many classes in this condition
classifier2 = create_classifier(**args_to_dict(args, (['num_class']+list(classifier_and_diffusion_defaults().keys()))[:3]))
classifier2.load_state_dict(
dist_util.load_state_dict(args.classifier_path2, map_location="cpu")
)
classifier2.to(dist_util.dev())
classifier2.eval()
else:
classifier = create_classifier(**args_to_dict(args, (['num_class']+list(classifier_and_diffusion_defaults().keys()))[:3]))
classifier.load_state_dict(
dist_util.load_state_dict(args.classifier_path, map_location="cpu")
)
classifier.to(dist_util.dev())
classifier.eval()
'''
control function for Gradient Interpolation Strategy
'''
def cond_fn_inter(x, t, y=None, init=None, diffusion=None):
assert y is not None
y1 = y[:,0]
y2 = y[:,1]
# xt = diffusion.q_sample(th.tensor(init,device=dist_util.dev()),t*th.ones(init.shape[0],device=dist_util.dev(),dtype=torch.long),)
with th.enable_grad():
x_in = x.detach().requires_grad_(True)
logits = classifier(x_in, t)
log_probs = F.log_softmax(logits, dim=-1)
selected1 = log_probs[range(len(logits)), y1.view(-1)]
selected2 = log_probs[range(len(logits)), y2.view(-1)]
grad1 = th.autograd.grad(selected1.sum(), x_in, retain_graph=True)[0] * args.classifier_scale1
grad2 = th.autograd.grad(selected2.sum(), x_in, retain_graph=True)[0] * args.classifier_scale2
# l2_loss = ((x_in-xt)**2).mean()
# grad3 = th.autograd.grad(-l2_loss, x_in, retain_graph=True)[0] * 100
return grad1+grad2#+grad3
'''
control function for multi-conditional generation
Two conditional generation here
'''
def cond_fn_multi(x, t, y=None):
assert y is not None
y1 = y[:,0]
y2 = y[:,1]
with th.enable_grad():
x_in = x.detach().requires_grad_(True)
logits1 = classifier1(x_in, t)
log_probs1 = F.log_softmax(logits1, dim=-1)
selected1 = log_probs1[range(len(logits1)), y1.view(-1)]
logits2 = classifier2(x_in, t)
log_probs2 = F.log_softmax(logits2, dim=-1)
selected2 = log_probs2[range(len(logits2)), y2.view(-1)]
grad1 = th.autograd.grad(selected1.sum(), x_in, retain_graph=True)[0] * args.classifier_scale1
grad2 = th.autograd.grad(selected2.sum(), x_in, retain_graph=True)[0] * args.classifier_scale2
return grad1+grad2
'''
control function for one conditional generation
'''
def cond_fn_ori(x, t, y=None):
assert y is not None
with th.enable_grad():
x_in = x.detach().requires_grad_(True)
logits = classifier(x_in, t)
log_probs = F.log_softmax(logits, dim=-1)
selected = log_probs[range(len(logits)), y.view(-1)]
grad = th.autograd.grad(selected.sum(), x_in, retain_graph=True)[0] * args.classifier_scale
return grad
def model_fn(x, t, y=None, init=None, diffusion=None):
assert y is not None
if args.class_cond:
return model(x, t, y if args.class_cond else None)
else:
return model(x, t)
if inter:
# input real cell expression data as initial noise
ori_adata = sc.read_h5ad(args.init_cell_path)
sc.pp.normalize_total(ori_adata, target_sum=1e4)
sc.pp.log1p(ori_adata)
logger.log("sampling...")
all_cell = []
sample_num = 0
while sample_num < args.num_samples:
model_kwargs = {}
if not multi and not inter:
classes = (cell_type[0])*th.ones((args.batch_size,), device=dist_util.dev(), dtype=th.long)
if multi:
classes1 = (cell_type[0])*th.ones((args.batch_size,), device=dist_util.dev(), dtype=th.long)
classes2 = (cell_type[1])*th.ones((args.batch_size,), device=dist_util.dev(), dtype=th.long)
# classes3 = ... if more conditions
classes = th.stack((classes1,classes2), dim=1)
if inter:
classes1 = (cell_type[0])*th.ones((args.batch_size,), device=dist_util.dev(), dtype=th.long)
classes2 = (cell_type[1])*th.ones((args.batch_size,), device=dist_util.dev(), dtype=th.long)
classes = th.stack((classes1,classes2), dim=1)
model_kwargs["y"] = classes
sample_fn = (
diffusion.p_sample_loop if not args.use_ddim else diffusion.ddim_sample_loop
)
if inter:
celltype = ori_adata.obs['period'].cat.categories.tolist()[cell_type[0]]
adata = ori_adata[ori_adata.obs['period']==celltype].copy()
start_x = adata.X
autoencoder = load_VAE(args.ae_dir, args.num_gene)
start_x = autoencoder(torch.tensor(start_x,device=dist_util.dev()),return_latent=True).detach().cpu().numpy()
n, m = start_x.shape
if n >= args.batch_size:
start_x = start_x[:args.batch_size, :]
else:
repeat_times = args.batch_size // n
remainder = args.batch_size % n
start_x = np.concatenate([start_x] * repeat_times + [start_x[:remainder, :]], axis=0)
noise = diffusion.q_sample(th.tensor(start_x,device=dist_util.dev()),args.init_time*th.ones(start_x.shape[0],device=dist_util.dev(),dtype=torch.long),)
model_kwargs["init"] = start_x
model_kwargs["diffusion"] = diffusion
if multi:
sample, traj = sample_fn(
model_fn,
(args.batch_size, args.input_dim),
clip_denoised=args.clip_denoised,
model_kwargs=model_kwargs,
cond_fn=cond_fn_multi,
device=dist_util.dev(),
noise = None,
start_time=diffusion.betas.shape[0],
start_guide_steps=args.start_guide_steps,
)
elif inter:
sample, traj = sample_fn(
model_fn,
(args.batch_size, args.input_dim),
clip_denoised=args.clip_denoised,
model_kwargs=model_kwargs,
cond_fn=cond_fn_inter,
device=dist_util.dev(),
noise = noise,
start_time=diffusion.betas.shape[0],
start_guide_steps=args.start_guide_steps,
)
else:
sample, traj = sample_fn(
model_fn,
(args.batch_size, args.input_dim),
clip_denoised=args.clip_denoised,
model_kwargs=model_kwargs,
cond_fn=cond_fn_ori,
device=dist_util.dev(),
noise = None,
)
gathered_samples = [th.zeros_like(sample) for _ in range(dist.get_world_size())]
dist.all_gather(gathered_samples, sample) # gather not supported with NCCL
if args.filter:
for sample in gathered_samples:
if multi:
logits1 = classifier1(sample, torch.zeros((sample.shape[0]), device=sample.device))
logits2 = classifier2(sample, torch.zeros((sample.shape[0]), device=sample.device))
prob1 = F.softmax(logits1, dim=-1)
prob2 = F.softmax(logits2, dim=-1)
type1 = torch.argmax(prob1, 1)
type2 = torch.argmax(prob2, 1)
select_index = ((type1 == cell_type[0]) & (type2 == cell_type[1]))
all_cell.extend([sample[select_index].cpu().numpy()])
sample_num += select_index.sum().item()
elif inter:
logits = classifier(sample, torch.zeros((sample.shape[0]), device=sample.device))
prob = F.softmax(logits, dim=-1)
left = (prob[:,cell_type[0]] > weight[0]/10-0.15) & (prob[:,cell_type[0]] < weight[0]/10+0.15)
right = (prob[:,cell_type[1]] > weight[1]/10-0.15) & (prob[:,cell_type[1]] < weight[1]/10+0.15)
select_index = left & right
all_cell.extend([sample[select_index].cpu().numpy()])
sample_num += select_index.sum().item()
else:
logits = classifier(sample, torch.zeros((sample.shape[0]), device=sample.device))
prob = F.softmax(logits, dim=-1)
type = torch.argmax(prob, 1)
select_index = (type == cell_type[0])
all_cell.extend([sample[select_index].cpu().numpy()])
sample_num += select_index.sum().item()
logger.log(f"created {sample_num} samples")
else:
all_cell.extend([sample.cpu().numpy() for sample in gathered_samples])
sample_num = len(all_cell) * args.batch_size
logger.log(f"created {len(all_cell) * args.batch_size} samples")
arr = np.concatenate(all_cell, axis=0)
save_data(arr, traj, args.sample_dir+str(cell_type[0]))
dist.barrier()
logger.log("sampling complete")
def create_argparser(celltype=[0], weight=[10,10]):
defaults = dict(
clip_denoised=True,
num_samples=9000,
batch_size=3000,
use_ddim=False,
class_cond=False,
model_path="output/diffusion_checkpoint/muris_diffusion/model000000.pt",
# ***if commen conditional generation & gradiante interpolation, use this path***
classifier_path="output/classifier_checkpoint/classifier_muris/model000100.pt",
# ***if multi-conditional, use this path. replace this to your own classifiers***
classifier_path1="output/classifier_checkpoint/classifier_muris_ood_type/model200000.pt",
classifier_path2="output/classifier_checkpoint/classifier_muris_ood_organ/model200000.pt",
num_class1 = 2, # set this to the number of classes in your own dataset. this is the first condition (for example cell organ).
num_class2 = 2, # this is the second condition (for example cell type).
# ***if commen conditional generation, use this scale***
classifier_scale=2,
# ***in multi-conditional, use this scale. scale1 and scale2 are the weights of two classifiers***
# ***in Gradient Interpolation, use this scale, too. scale1 and scale2 are the weights of two gradients***
classifier_scale1=weight[0]*2/10,
classifier_scale2=weight[1]*2/10,
# ***if gradient interpolation, replace these base on your own situation***
ae_dir='output/Autoencoder_checkpoint/WOT/model_seed=0_step=150000.pt',
num_gene=19423,
init_time = 600, # initial noised state if interpolation
init_cell_path = 'data/WOT/filted_data.h5ad', #input initial noised cell state
sample_dir=f"output/simulated_samples/muris",
start_guide_steps = 500, # the time to use classifier guidance
filter = False, # filter the simulated cells that are classified into other condition, might take long time
)
defaults.update(model_and_diffusion_defaults())
defaults.update(classifier_and_diffusion_defaults())
defaults['num_class']=12
parser = argparse.ArgumentParser()
add_dict_to_argparser(parser, defaults)
return parser
if __name__ == "__main__":
# for conditional generation
# main(cell_type=[2])
for type in range(12):
main(cell_type=[type])
# ***for multi-condition, run***
# muris ood
# for i in [0,1]:
# for j in [0,1]:
# main(cell_type=[i,j],multi=True)
# ***for Gradient Interpolation, run***
# for i in range(0,11):
# main(cell_type=[6,7], inter=True, weight=[10-i,i])
# for i in range(18):
# main(cell_type=[i,i+1], inter=True, weight=[5,5])