API Reference
Structure:
Config
DataConfig
dataclass
Data configuration class.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train_params |
DataParams
|
training data parameters. Check DataParams for more details. |
required |
test_params |
DataParams
|
testing data parameters. Check DataParams for more details. |
required |
dataset_name |
str
|
name of the dataset to use. Currently only supports "voc". |
''
|
dataset_root |
str
|
root directory of the dataset. |
''
|
transform |
optional, dict
|
transform to apply to the dataset. Default None for no transf. Transform dict comes from albumentations library. Check albumentations for more details. Loading transform should proceed with albumentations.from_dict method. |
None
|
size |
int
|
size of image width and height. |
224
|
Source code in modules/config.py
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 |
|
DataParams
dataclass
Train and test data parameters.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch_size |
int
|
batch size for training. |
required |
shuffle |
bool
|
whether to shuffle the dataset. |
required |
Source code in modules/config.py
215 216 217 218 219 220 221 222 223 224 |
|
DiscConfig
Bases: PretrainedConfig
Configuration class to store the configuration of a Discriminator model.
Dataclass for storing is based on PretrainedConfig
from transformers
package.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_last_dim |
int
|
last dimension of the input sample in Discriminator. |
3
|
output_last_dim |
int
|
last dimension of the output sample in Discriminator. |
1
|
resolution |
int
|
resolution of the input image (256x256). |
256
|
ndf |
int
|
number of filters in the first layer of Discriminator. |
64
|
n_layers |
int
|
number of layers in Discriminator. |
3
|
Source code in modules/config.py
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 |
|
LoadConfig
dataclass
Load configuration class to store the configuration of a train model and data. Main configuration class to be used for training.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
DataConfig
|
data configuration. |
required |
data |
TrainConfig
|
training configuration. |
required |
Source code in modules/config.py
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 |
|
TrainConfig
dataclass
Configuration class to store the configuration of a train model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_name |
str
|
name of the model to train. Used for saving and logging. |
required |
model_hparams |
VQGANConfig
|
model hyperparameters. Check VQGANConfig for more details. |
required |
disc_hparams |
DiscConfig
|
discriminator hyperparameters. Check DiscConfig for more details. |
required |
save_dir |
str
|
directory to save the model. |
required |
log_dir |
str
|
directory to save the logs for tensorboard. |
required |
check_val_every_n_epoch |
int
|
number of epochs to run validation. |
required |
log_img_every_n_epoch |
int
|
number of epochs to log images. |
required |
input_shape |
Tuple[int, int, int]
|
shape of the input image (H, W, C). |
required |
codebook_weight |
float
|
weight for the codebook loss (Quantizer part). |
required |
monitor |
str
|
metric to monitor for saving best model. |
required |
recon_loss |
str
|
reconstruction loss to use. Can be one of |
required |
disc_loss |
str
|
discriminator loss to use. Can be |
required |
disc_weight |
float
|
weight for the discriminator loss. |
required |
num_epochs |
int
|
number of epochs to train. |
required |
dtype |
str
|
dtype to use for training.
Supported: |
required |
distributed |
bool
|
whether to use distributed training. |
required |
seed |
int
|
seed for random number generation. |
required |
optimizer |
str
|
optimizer to use for training. Structure needs to be optax Optimizer (Check optax for more details) with 'target' parameter, for specifing optax optimizer, and 'kwargs' parameter for passing to optimizer. check config_test.yaml for example. |
required |
optimizer_disc |
str
|
optimizer to use for discriminator training. Similar to optimizer. |
required |
disc_start |
int
|
number of epochs to past to start using the discriminator. |
required |
temp_scheduler |
optional
|
temperature scheduler to use for training. Similar to optimizer but uses optax scheduler with 'target' parameter, for specifing optax scheduler. if None, then no scheduler is used. Check config_test.yaml for example. |
required |
Source code in modules/config.py
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 |
|
VQGANConfig
Bases: PretrainedConfig
Configuration class to store the configuration of a VQGAN model.
Dataclass for storing is based on PretrainedConfig
from transformers
package.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
ch |
int
|
number of channels. |
128
|
out_ch |
int
|
number of output channels (RGB). |
3
|
in_channels |
int
|
number of input channels (RGB). |
3
|
num_res_blocks |
int
|
number of residual blocks. |
2
|
resolution |
int
|
resolution of the input image (256x256). |
256
|
z_channels |
int
|
number of channels in the latent space. |
256
|
ch_mult |
Tuple[int]
|
channel multiplier for each layer. |
tuple([1, 1, 2, 2, 4])
|
attn_resolutions |
Tuple[int]
|
resolutions at which to apply attention. |
(16)
|
n_embed |
int
|
number of embeddings, unique codes in the latent space. |
1024
|
embed_dim |
int
|
dimension of embedding from Encoder. |
256
|
dropout |
float
|
dropout rate. |
0.0
|
double_z |
bool
|
whether to double the latent space for. |
False
|
resamp_with_conv |
bool
|
whether to use convolutions for upsampling. |
True
|
use_gumbel |
bool
|
whether to use gumbel softmax for quantization. |
False
|
gumb_temp |
float
|
temperature for gumbel softmax. |
1.0
|
act_name |
str
|
activation function name to use. |
'swish'
|
give_pre_end |
bool
|
whether to give the pre-end layer for the decoder. |
False
|
kwargs |
Any
|
keyword arguments passed along to the super class. |
{}
|
Source code in modules/config.py
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 |
|
Losses
combo_loss(predictions, targets)
Compute combined l1 and l2 loss : l1 if l2 < 0.5 else l2.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predictions |
jnp.ndarray
|
Predictions from the model. |
required |
targets |
jnp.ndarray
|
Targets for the model. |
required |
Returns:
Type | Description |
---|---|
jnp.ndarray
|
Reconstruction loss. |
Source code in modules/losses.py
27 28 29 30 31 32 33 34 35 36 37 |
|
disc_loss_hinge(real, fake)
Compute discriminator loss for hinge GAN. Real and fake logits influence the loss the same.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
real |
jnp.ndarray
|
Real images, received from dataset. |
required |
fake |
jnp.ndarray
|
Fake images, produced by generator. |
required |
Returns:
Type | Description |
---|---|
jnp.ndarray
|
Discriminator loss. |
Source code in modules/losses.py
65 66 67 68 69 70 71 72 73 74 75 76 |
|
disc_loss_vanilla(real, fake)
Compute discriminator loss for vanilla GAN. Wrong fake logits impact more the loss than the bad real logits.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
real |
jnp.ndarray
|
Real images, received from dataset. |
required |
fake |
jnp.ndarray
|
Fake images, produced by generator. |
required |
Returns:
Type | Description |
---|---|
jnp.ndarray
|
Discriminator loss. |
Source code in modules/losses.py
51 52 53 54 55 56 57 58 59 60 61 62 |
|
l1_loss(predictions, targets)
Compute L1 loss.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predictions |
jnp.ndarray
|
Predictions from the model. |
required |
targets |
jnp.ndarray
|
Targets for the model. |
required |
Returns:
Type | Description |
---|---|
jnp.ndarray
|
Reconstruction loss. |
Source code in modules/losses.py
16 17 18 19 20 21 22 23 24 |
|
l2_loss(predictions, targets)
Compute L2 loss.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predictions |
jnp.ndarray
|
Predictions from the model. |
required |
targets |
jnp.ndarray
|
Targets for the model. |
required |
Returns:
Type | Description |
---|---|
jnp.ndarray
|
Reconstruction loss. |
Source code in modules/losses.py
5 6 7 8 9 10 11 12 13 |
|
mape_loss(predictions, targets)
Compute mean absolute percentage error loss.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
predictions |
jnp.ndarray
|
Predictions from the model. |
required |
targets |
jnp.ndarray
|
Targets for the model. |
required |
Returns:
Type | Description |
---|---|
jnp.ndarray
|
Reconstruction loss. |
Source code in modules/losses.py
40 41 42 43 44 45 46 47 48 |
|
Models
AttnBlock
Bases: nn.Module
Attention block.
Attributes:
Name | Type | Description |
---|---|---|
in_channels |
int
|
number of input channels. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Source code in modules/models.py
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 |
|
__call__(x)
Forward pass of the block.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
jnp.ndarray
|
input tensor. |
required |
Returns:
Type | Description |
---|---|
jnp.ndarray
|
output tensor with the same shape as the input. |
Source code in modules/models.py
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 |
|
Decoder
Bases: nn.Module
Decoder of VQ-GAN to map input batch of latent space to images. Dimension Transformations originally: 32x32x256 --Conv2d--> 32x32x512 --MidBlock--> 32x32x512
for loop
--UpsamplingBlock--> 64x64x256 --UpsamplingBlock--> 128x128x128 --UpsamplingBlock--> 256x256x64 --UpsamplingBlock--> 256x256x32
--GroupNorm--> --nonlinear--> --Conv2d-> 256x256x3
Attributes:
Name | Type | Description |
---|---|---|
config |
VQGANConfig
|
the config of the model. |
act_fn |
str
|
activation function. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Source code in modules/models.py
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 |
|
Downsample
Bases: nn.Module
Downsample the input by a factor of 2.
Attributes:
Name | Type | Description |
---|---|---|
in_channels |
int
|
Number of input channels. |
use_conv |
bool
|
Whether to use a identity convolution. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Source code in modules/models.py
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 |
|
DownsamplingBlock
Bases: nn.Module
Downsampling block for Encoder.
Attributes:
Name | Type | Description |
---|---|---|
config |
VQGANConfig
|
the config of the model. |
curr_res |
int
|
current resolution. |
blck_idx |
int
|
current block index. |
act_fn |
Callable
|
activation function. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Source code in modules/models.py
334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
|
__call__(x, temb=None, deterministic=True)
Forward pass of the block.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
jnp.ndarray
|
input tensor. |
required |
temb |
Optional[jnp.ndarray]
|
temporal embedding. Defaults to None. |
None
|
deterministic |
bool
|
deterministic flag. Defaults to True. |
True
|
Source code in modules/models.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
|
Encoder
Bases: nn.Module
Encoder of VQ-GAN to map input batch of images to latent space. Dimension Transformations originally: 256x256x3 --Conv2d--> 256x256x32
for loop
--DownsamplingBlock--> 128x128x64 --DownsamplingBlock--> 64x64x128 --DownsamplingBlock--> 32x32x256 --DownsamplingBlock--> 32x32x512
--MidBlock--> 32x32x512 --GroupNorm--> --nonlinear--> --Conv2d-> 32x32x256
Attributes:
Name | Type | Description |
---|---|---|
config |
VQGANConfig
|
the config of the model. |
act_fn |
str
|
activation function. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Source code in modules/models.py
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 |
|
MidBlock
Bases: nn.Module
Mid block for Encoder and Decoder.
Attributes:
Name | Type | Description |
---|---|---|
in_channels |
int
|
number of input channels. |
act_fn |
str
|
activation function. |
temb_channels |
int
|
number of channels for temporal embedding. |
dropout_prob |
float
|
dropout probability. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Source code in modules/models.py
412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 |
|
__call__(x, temb=None, deterministic=True)
BxWxHxC --ResNet--> BxWxHxC --Attn--> BxWxHxC --ResNet--> BxWxHxC
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
jnp.ndarray
|
input tensor. |
required |
temb |
Optional[jnp.ndarray]
|
temporal embedding. Defaults to None. |
None
|
deterministic |
bool
|
deterministic flag. Defaults to True. |
True
|
Source code in modules/models.py
429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 |
|
ResNetBlock
Bases: nn.Module
ResNet block with optional bottleneck.
Attributes:
Name | Type | Description |
---|---|---|
in_channels |
int
|
number of input channels. |
out_channels |
Optional[int]
|
number of output channels. If None, the output channels will be the same as the input channels. |
act_fn |
Callable
|
activation function. |
use_conv_shortcut |
bool
|
whether to use a convolutional shortcut. |
temb_channels |
jnp.ndarray
|
number of channels in the temporal embedding. |
dropout_prob |
float
|
dropout probability. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Source code in modules/models.py
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 |
|
__call__(x, temb=None, deterministic=True)
Forward pass of the block.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
jnp.ndarray
|
input tensor. |
required |
temb |
Optional[int]
|
temporal embedding. Defaults to None. |
None
|
deterministic |
bool
|
deterministic flag. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
jnp.ndarray
|
output tensor with the out_channels dimension as the last dimension (C). |
Source code in modules/models.py
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 |
|
Upsample
Bases: nn.Module
Upsample the input by a factor of 2.
Attributes:
Name | Type | Description |
---|---|---|
in_channels |
int
|
Number of input channels. |
use_conv |
bool
|
Whether to use a identity convolution. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Source code in modules/models.py
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 |
|
UpsamplingBlock
Bases: nn.Module
Upsampling block for Decoder.
Attributes:
Name | Type | Description |
---|---|---|
config |
VQGANConfig
|
the config of the model. |
curr_res |
int
|
current resolution. |
blck_idx |
int
|
current block index. |
act_fn |
Callable
|
activation function. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Source code in modules/models.py
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 |
|
__call__(x, temb=None, deterministic=True)
Forward pass of the block.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
jnp.ndarray
|
input tensor. |
required |
temb |
Optional[jnp.ndarray]
|
temporal embedding. Defaults to None. |
None
|
deterministic |
bool
|
deterministic flag. Defaults to True. |
True
|
Source code in modules/models.py
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 |
|
Training
GenerateCallback
Callback that generates and logs images during training.
Source code in modules/training.py
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 |
|
__init__(input_imgs, rng, every_n_epochs=1)
Initialize the callback.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input_imgs |
Any
|
Images to reconstruct during training |
required |
every_n_epochs |
int
|
Only save those images every N epochs (otherwise tensorboard gets quite large). Defaults to 1. |
1
|
Source code in modules/training.py
25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
TrainStateDisc
Bases: train_state.TrainState
Train state for discriminator.
Attributes:
Name | Type | Description |
---|---|---|
apply_fn |
Callable
|
The function that applies the model. |
step |
int
|
The current step. |
params |
FrozenDict
|
The model parameters. |
batch_stats |
FrozenDict
|
The batch statistics. Defaults to None. |
tx |
optax.GradientTransformation
|
The optimizer. Defaults to None. |
opt_state |
optax.OptState
|
The optimizer state. Defaults to None. |
Source code in modules/training.py
323 324 325 326 327 328 329 330 331 332 333 334 |
|
TrainerModule
Helper functions for training.
Source code in modules/training.py
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 |
|
__init__(module_config, model_class)
Module for summarizing all common training functionalities.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
module_config |
TrainConfig
|
Configuration for training with all hyperparameters and train module parameters. |
required |
model_class |
FlaxPreTrainedModel
|
Model class to be trained. |
required |
Source code in modules/training.py
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 |
|
checkpoint_exists()
Check whether a pretrained model exist.
Returns:
Type | Description |
---|---|
bool
|
True if model exists, False otherwise. |
Source code in modules/training.py
315 316 317 318 319 320 |
|
create_functions()
To be implemented in sub-classes.
Source code in modules/training.py
113 114 115 |
|
create_train_state(optimizer)
Initialize training state.
Source code in modules/training.py
124 125 126 127 128 |
|
eval_model(data_loader)
Test model on all images of a data loader and return avg metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_loader |
utils.DataLoader
|
Data loader to evaluate on. |
required |
Returns:
Type | Description |
---|---|
Dict[str, float]
|
Dictionary with all metrics. |
Source code in modules/training.py
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 |
|
eval_step(state, batch, rng, *args, **kwargs)
staticmethod
Evaluate model on a single batch.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state |
TrainState
|
Current training state. |
required |
batch |
Any
|
Batch of data. |
required |
rng |
Union[Any, jnp.ndarray]
|
Random number generator. |
required |
Returns:
Type | Description |
---|---|
Tuple[Union[Any, jnp.ndarray], Dict[str, float]]
|
New rng and metrics. |
Source code in modules/training.py
228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 |
|
init_optimizer()
Initialize optimizer and scheduler. By default, we decrease the learning rate with cosine annealing.
Source code in modules/training.py
117 118 119 120 121 122 |
|
load_model()
Load model.
Source code in modules/training.py
296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 |
|
push_model_to_hub(repo_id, commit_message='Saving weights and logs')
Push model to huggingface hub.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
repo_id |
str
|
Repository id to push to Hugging Face. |
required |
commit_message |
str
|
Commit message. Defaults to "Saving weights and logs". |
'Saving weights and logs'
|
Source code in modules/training.py
282 283 284 285 286 287 288 289 290 291 292 293 294 |
|
save_model(step=None)
Save current model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
step |
int
|
Current step. Defaults to None. |
None
|
Source code in modules/training.py
268 269 270 271 272 273 274 275 276 277 278 279 280 |
|
train_epoch(data_loader, epoch)
Train model for one epoch, and log avg metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_loader |
utils.DataLoader
|
Data loader to train on. |
required |
epoch |
int
|
Current epoch. |
required |
Returns:
Type | Description |
---|---|
Dict[str, float]
|
Dictionary with all metrics. |
Source code in modules/training.py
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 |
|
train_model(train_loader, val_loader)
Train model for defined number of epochs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train_loader |
utils.DataLoader
|
Training data loader. |
required |
val_loader |
utils.DataLoader
|
Validation data loader. |
required |
Source code in modules/training.py
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 |
|
train_step(state, batch, rng, distributed=False, *args, **kwargs)
staticmethod
Train model on a single batch.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
state |
TrainState
|
Current training state. |
required |
batch |
Any
|
Batch of data. |
required |
rng |
Union[Any, jnp.ndarray]
|
Random number generator. |
required |
distributed |
bool
|
Whether to use distributed training. Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
Any
|
Updated training states, rng and metrics. |
Source code in modules/training.py
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 |
|
TrainerVQGan
Bases: TrainerModule
Helper functions for training VQGAN.
Source code in modules/training.py
337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 |
|
checkpoint_exists()
Check whether a pretrained model exist.
Returns:
Type | Description |
---|---|
bool
|
True if model and discriminator exists, False otherwise. |
Source code in modules/training.py
454 455 456 457 458 459 460 461 |
|
create_functions()
Create training and eval functions.
Source code in modules/training.py
526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 |
|
create_train_stat_full(optimizer, optimizer_disc)
Initialize training state.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
optimizer |
optax.GradientTransformation
|
Optimizer for generator. |
required |
optimizer_disc |
optax.GradientTransformation
|
Optimizer for discriminator. |
required |
Source code in modules/training.py
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 |
|
init_optimizer()
Initialize optimizer and scheduler also for discriminator. By default, we decrease the learning rate with cosine annealing.
Source code in modules/training.py
400 401 402 403 404 405 406 |
|
load_model()
Load model.
Source code in modules/training.py
439 440 441 442 443 444 445 446 447 448 449 450 451 452 |
|
save_model(step=None)
Save current model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
step |
int
|
Current step. Defaults to None. |
None
|
Source code in modules/training.py
428 429 430 431 432 433 434 435 436 437 |
|
temperature_scheduling(epoch)
Temperature scheduling.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
epoch |
int
|
Current epoch. |
required |
Returns:
Type | Description |
---|---|
float
|
Temperature. |
Source code in modules/training.py
388 389 390 391 392 393 394 395 396 397 398 |
|
train_epoch(data_loader, epoch)
Train model for one epoch, and log avg metrics.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
data_loader |
utils.DataLoader
|
Data loader to train on. |
required |
Returns:
Type | Description |
---|---|
Dict[str, float]
|
Dictionary with all metrics. |
Source code in modules/training.py
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 |
|
Utils
BaseDataset
Bases: ABC
Load the dataset. Abstract method.
Source code in modules/utils.py
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 |
|
__init__(train, dtype, config)
Set the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
bool
|
If the dataset is for training. |
required |
config |
DataConfig
|
The config for the dataset. |
required |
Source code in modules/utils.py
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
|
__len__()
Return the length of the dataset.
Source code in modules/utils.py
103 104 105 |
|
get_dataset()
Return the dataset.
Returns:
Type | Description |
---|---|
tf.data.Dataset
|
The dataset. |
Source code in modules/utils.py
132 133 134 135 136 137 138 139 |
|
load_dataset(train)
abstractmethod
Load the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
bool
|
If the dataset is for training. |
required |
Returns:
Type | Description |
---|---|
tf.data.Dataset
|
The dataset. |
Source code in modules/utils.py
93 94 95 96 97 98 99 100 101 |
|
DataLoader
Dataloader similar as in pytorch.
Source code in modules/utils.py
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 |
|
__call__(*args, **kwds)
Return the dataset in dataloader style.
Source code in modules/utils.py
212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 |
|
__init__(dataset, distributed)
Create a data loader.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
dataset |
BaseDataset
|
The dataset to load. |
required |
distributed |
bool
|
If the data is distributed. |
required |
Source code in modules/utils.py
199 200 201 202 203 204 205 206 |
|
__len__()
Return the length of the dataset.
Source code in modules/utils.py
208 209 210 |
|
DummyDataset
Bases: BaseDataset
Create dummy dataset.
Source code in modules/utils.py
142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
|
load_dataset(train)
Load the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
bool
|
If the dataset is for training. |
required |
Returns:
Type | Description |
---|---|
tf.data.Dataset
|
The dataset. |
Source code in modules/utils.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
|
TensorflowDataset
Bases: BaseDataset
Tensorflow dataset.
Source code in modules/utils.py
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 |
|
load_dataset(train)
Load the dataset.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
train |
bool
|
If the dataset is for training. |
required |
Returns:
Type | Description |
---|---|
tf.data.Dataset
|
The dataset. |
Source code in modules/utils.py
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 |
|
VQGanFeatureExtractor
Bases: VQGanImageProcessor
Extract features for VQGan from images. Extends VQGanImageProcessor only with call function to run preprocessing.
Source code in modules/utils.py
501 502 503 504 505 506 507 |
|
VQGanImageProcessor
Constructs a VQGan image processor.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
do_resize |
`bool`, *optional*, defaults to `True`
|
Whether to resize the image's (height, width) dimensions to the specified
|
True
|
size |
`dict`, *optional*, defaults to `{"height"
|
256, "width": 256} |
None
|
resample |
`Image.Resampling`, *optional*, defaults to `Image.Resampling.BILINEAR`
|
Resampling filter to use if resizing the image. Can be overridden by the |
Image.Resampling.BILINEAR
|
do_rescale |
`bool`, *optional*, defaults to `True`
|
Whether to rescale the image by the specified scale |
True
|
rescale_factor |
`int` or `float`, *optional*, defaults to `1/255`
|
Scale factor to use if rescaling the image. Can be overridden by the |
1 / 255
|
do_normalize |
bool
|
Whether to normalize the image. Can be overridden by the |
True
|
image_mean |
`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_MEAN`
|
Mean to use if normalizing the image. This is a float or list of floats the length of
the number of channels in the image. Can be overridden by the |
None
|
image_std |
`float` or `List[float]`, *optional*, defaults to `IMAGENET_STANDARD_STD`
|
Standard deviation to use if normalizing the image. This is a float or list of floats
the length of the number of channels in the image. Can be overridden by the |
None
|
dtype |
`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`
|
jnp.float32
|
Source code in modules/utils.py
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 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
|
normalize(image, mean, std, data_format=None, **kwargs)
Normalize an image. image = (image - image_mean) / image_std.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image |
`np.ndarray`
|
Image to normalize. |
required |
mean |
`float` or `List[float]`
|
Image mean to use for normalization. |
required |
std |
`float` or `List[float]`
|
Image standard deviation to use for normalization. |
required |
data_format |
`str`, *optional*
|
The channel dimension format for the output image. If unset, the channel dimension
format of the input image is used. Can be one of:
- |
None
|
Returns:
Type | Description |
---|---|
np.ndarray
|
The normalized image. |
Source code in modules/utils.py
366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
|
preprocess(images, do_resize=None, size=None, resample=None, do_rescale=None, rescale_factor=None, do_normalize=None, image_mean=None, image_std=None, data_format='channels_last', **kwargs)
Preprocess an image or batch of images.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images |
`Image.Image`, `np.ndarray`, `List[Image.Image]`, `List[np.ndarray]`
|
Image to preprocess. |
required |
do_resize |
`bool`, *optional*, defaults to `self.do_resize`
|
Whether to resize the image. |
None
|
size |
`Dict[str, int]`, *optional*, defaults to `self.size`
|
Dictionary in the format |
None
|
resample |
`Image.Resampling` filter, *optional*, defaults to `self.resample`
|
|
None
|
do_rescale |
`bool`, *optional*, defaults to `self.do_rescale`
|
Whether to rescale the image values between [0 - 1]. |
None
|
rescale_factor |
`float`, *optional*, defaults to `self.rescale_factor`
|
Rescale factor to rescale the image by if |
None
|
do_normalize |
`bool`, *optional*, defaults to `self.do_normalize`
|
Whether to normalize the image. |
None
|
image_mean |
`float` or `List[float]`, *optional*, defaults to `self.image_mean`
|
Image mean to use if |
None
|
image_std |
`float` or `List[float]`, *optional*, defaults to `self.image_std`
|
Image standard deviation to use if |
None
|
data_format |
`str`, *optional*, defaults to `channels_las`
|
):
The channel dimension format for the output image. Can be one of:
- |
'channels_last'
|
Returns:
Type | Description |
---|---|
BatchFeature
|
The preprocessed image(s). |
Source code in modules/utils.py
411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 |
|
rescale(image, scale, data_format=None, **kwargs)
Rescale an image by a scale factor. image = image * scale.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image |
`np.ndarray`
|
Image to resize. |
required |
scale |
`float`
|
The scaling factor to rescale pixel values by. |
required |
data_format |
`str`, *optional*
|
The channel dimension format for the output image. If unset, the channel dimension
format of the input image is used. Can be one of:
- |
None
|
Returns:
Type | Description |
---|---|
np.ndarray
|
The resized image. |
Source code in modules/utils.py
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 |
|
resize(image, size, resample=Image.Resampling.BILINEAR, data_format=None, **kwargs)
Resize an image to (size["height"], size["width"])
.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image |
`np.ndarray`
|
Image to resize. |
required |
size |
`Dict[str, int]`
|
Dictionary in the format |
required |
resample |
Image.Resampling
|
|
Image.Resampling.BILINEAR
|
data_format |
`str`, *optional*
|
The channel dimension format for the output image. If unset, the channel
dimension format of the input image is used. Can be one of:
- |
None
|
Returns:
Type | Description |
---|---|
np.ndarray
|
The resized image. |
Source code in modules/utils.py
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 340 |
|
make_img_grid(images, nrows=4)
Make image grid from images.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
images |
np.ndarray
|
image list to make grid. |
required |
nrows |
int
|
number of rows. Defaults to 4. |
4
|
Returns:
Type | Description |
---|---|
np.ndarray
|
image grid object. |
Source code in modules/utils.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
|
post_processing(image, resize=None)
Post processing for image. un standarize image and multiply by 255. Next clip values to [0, 255] and convert to uint8.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
image |
np.ndarray
|
image to post process. |
required |
Returns:
Type | Description |
---|---|
np.ndarray
|
post processed image. |
Source code in modules/utils.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
|
set_seed(seed)
Set seed for random operations.
Source code in modules/utils.py
21 22 23 24 25 |
|
VQGAN
GumbelQuantize
Bases: nn.Module
Gumbel Softmax trick quantizer Categorical Reparameterization with Gumbel-Softmax, Jang et al. 2016. z (continuous) -> z_q (discrete) z.shape = (batch, height, width, channel)
quantization pipeline
- get encoder input (B,H,W,C)
- get logits(prob) of input (B,H,W,n_embed)
See
https://arxiv.org/abs/1611.01144
Attributes:
Name | Type | Description |
---|---|---|
config |
VQGANConfig
|
the config of the model. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Config Attributes
n_embed (int) : number of embeddings. emb_dim (int): dimension of embedding. kl_weight (float): weight of kl loss.
Source code in modules/vqgan.py
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 |
|
get_codebook_entry(params, indices, shape=None)
staticmethod
Get the codebook entry for a given index. Input is expected to be of shape (batch, num_tokens)
Source code in modules/vqgan.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 |
|
NLayerDiscriminator
Bases: nn.Module
Defines a PatchGAN discriminator as in Pix2Pix
See
https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/networks.py
Attributes:
Name | Type | Description |
---|---|---|
ndf |
int
|
the number of filters in the last conv layer |
n_layers |
int
|
the number of conv layers in the discriminator |
output_dim |
bool
|
dim of output the last channel of the discriminator |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32) |
Source code in modules/vqgan.py
552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 |
|
VQGANPreTrainedModel
Bases: FlaxPreTrainedModel
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained models.
Attributes:
Name | Type | Description |
---|---|---|
module_class |
nn.Module
|
a class derived from nn.Module that defines the model's core computation. |
config_class |
PretrainedConfig
|
a class derived from PretrainedConfig |
Source code in modules/vqgan.py
321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
|
__call__(pixel_values, params=None, dropout_rng=None, gumble_rng=None, train=False)
Encode and decode the input.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pixel_values |
jnp.ndarray
|
the input to the encoder. |
required |
params |
Optional[FrozenDict]
|
the params of the model. Defaults to None. |
None
|
dropout_rng |
Optional[jnp.ndarray]
|
the dropout rng. Defaults to None. |
None
|
gumble_rng |
Optional[jnp.ndarray]
|
the gumbel rng. Defaults to None. If gumble_rng is None then the defult rng is used and produce deterministic results. |
None
|
train |
bool
|
Training or inference mode. Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
jnp.ndarray
|
the encoded latent vector, |
jnp.ndarray
|
the decoded image, |
float
|
the log prob of the latent vector, |
jnp.ndarray
|
the indices of the latent vector. |
Source code in modules/vqgan.py
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
|
__init__(config=VQGANConfig(), input_shape=(1, 256, 256, 3), seed=0, dtype=jnp.float32, _do_init=True, **kwargs)
Initialize the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
config |
PretrainedConfig
|
the config of the model. Defaults to VQGANConfig. |
VQGANConfig()
|
input_shape |
Tuple
|
the input shape of the model. Defaults to (1, 256, 256, 3). |
(1, 256, 256, 3)
|
seed |
int
|
the seed of the model. Defaults to 0. |
0
|
dtype |
jnp.dtype
|
the dtype of the computation. Defaults to jnp.float32. |
jnp.float32
|
_do_init |
bool
|
whether to initialize the model. Defaults to True. |
True
|
Source code in modules/vqgan.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 |
|
decode(z, params=None, dropout_rng=None, gumble_rng=None, train=False)
Decode the latent vector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
z |
jnp.ndarray
|
the latent vector. |
required |
params |
Optional[FrozenDict]
|
the params of the model. Defaults to None. |
None
|
dropout_rng |
Union[Any, jnp.ndarray]
|
the dropout rng. Defaults to None. |
None
|
gumble_rng |
Union[Any, jnp.ndarray]
|
the gumbel rng. Defaults to None. |
None
|
train |
bool
|
Training or inference mode. Defaults to False. |
False
|
Returns:
Type | Description |
---|---|
jnp.ndarray
|
the decoded image. |
Source code in modules/vqgan.py
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 |
|
decode_code(indices, z_shape, params=None)
Decode the indices.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
indices |
jnp.ndarray
|
the indices. |
required |
z_shape |
Tuple[int, ...]
|
the shape of the latent vector. |
required |
params |
Optional[FrozenDict]
|
the params of the model. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
jnp.ndarray
|
the decoded image from indices. |
Source code in modules/vqgan.py
471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
|
encode(pixel_values, params=None, dropout_rng=None, gumble_rng=None, train=False)
Encode the input.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
pixel_values |
jnp.ndarray
|
the input to the encoder. |
required |
params |
Optional[FrozenDict]
|
the params of the model. Defaults to None. |
None
|
dropout_rng |
Union[Any, jnp.ndarray]
|
the dropout rng. Defaults to None. |
None
|
gumble_rng |
Union[Any, jnp.ndarray]
|
the gumbel rng. Defaults to None. |
None
|
train |
bool
|
Training or inference mode. Defaults to False. |
False
|
Source code in modules/vqgan.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 |
|
init_weights(rng, input_shape, params=None)
Initialize the weights of the model. Get the params
Parameters:
Name | Type | Description | Default |
---|---|---|---|
rng |
Union[Any, jnp.ndarray]
|
the random number generator. |
required |
input_shape |
Tuple
|
the input shape of the model. |
required |
params |
FrozenDict
|
the params of the model. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
FrozenDict[str, Any]
|
initialized params of the model. |
Source code in modules/vqgan.py
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
|
update_temperature(temperature, params=None)
Update the temperature of the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
temperature |
float
|
the temperature to update to. |
required |
params |
Optional[FrozenDict]
|
the params of the model. Defaults to None. |
None
|
Returns:
Type | Description |
---|---|
float
|
the updated temperature. |
Source code in modules/vqgan.py
494 495 496 497 498 499 500 501 502 503 504 505 506 507 |
|
VQGanDiscriminator
Bases: FlaxPreTrainedModel
VQGAN discriminator model.
Attributes:
Name | Type | Description |
---|---|---|
module_class |
nn.Module
|
the discriminator module class (NLayerDiscriminator). |
Source code in modules/vqgan.py
618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 |
|
VQModel
Bases: VQGANPreTrainedModel
VQ-VAE model from pre-trained VQGAN.
Source code in modules/vqgan.py
545 546 547 548 549 |
|
VQModule
Bases: nn.Module
VQ-VAE module.
See
https://arxiv.org/abs/1711.00937v2
Attributes:
Name | Type | Description |
---|---|---|
config |
VQGANConfig
|
the config of the model. |
dtype |
jnp.dtype
|
the dtype of the computation (default: float32). |
Source code in modules/vqgan.py
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 |
|
decode(z_q, deterministic=True)
Decode the quantized latent vector.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
z_q |
jnp.ndarray
|
the quantized latent vector. |
required |
deterministic |
bool
|
for Dropout. Defaults to True. |
True
|
Returns:
Type | Description |
---|---|
jnp.ndarray
|
the reconstructed image. |
Source code in modules/vqgan.py
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 |
|
decode_code(code, z_shape)
Decode already created z_code
Source code in modules/vqgan.py
295 296 297 298 299 300 |
|
encode(x, deterministic=True)
Encode the input.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
jnp.ndarray
|
the input to the encoder. |
required |
Returns:
Type | Description |
---|---|
Tuple[jnp.ndarray, float, jnp.ndarray]
|
the encoded input, the loss and the indices. |
Source code in modules/vqgan.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 |
|
setup()
Setup the VQ-VAE module.
Source code in modules/vqgan.py
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 |
|
update_temperature(temperature)
Update the temperature of the Gumbel-Softmax distribution.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
temperature |
float
|
the new temperature of the Gumbel-Softmax distribution |
required |
Returns:
Type | Description |
---|---|
float
|
the new temperature of the Gumbel-Softmax distribution |
Source code in modules/vqgan.py
302 303 304 305 306 307 308 309 310 311 |
|
VectorQuantizer
Bases: nn.Module
Discretization bottleneck part of the VQ-VAE. Module get z lattent vector (Encoder output) and maps it to a discrete one-hot vector that is the index of the closest embedding vector e_j z (continuous) -> z_q (discrete) z.shape = (batch, height, width, channel)
quantization pipeline
- get encoder input (B,H,W,C)
- flatten input to (BHW,C)
See
https://github.com/MishaLaskin/vqvae/blob/d761a999e2267766400dc646d82d3ac3657771d4/models/quantizer.py
Attributes:
Name | Type | Description |
---|---|---|
config |
VQGANConfig
|
the config of the model. |
dtype |
jnp.dtype
|
the dtype of the computation for embeddings (default: float32). |
Config Attributes
n_embed (int) : number of embeddings. emb_dim (int): dimension of embedding. beta (float): weight of commitment loss.
Source code in modules/vqgan.py
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 |
|
get_codebook_entry(params, indices, shape=None)
staticmethod
Get the codebook entry for a given index. Input is expected to be of shape (batch, num_tokens)
Source code in modules/vqgan.py
99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
|