MCPcopy Create free account
hub / github.com/LargeWorldModel/LWM / __call__

Method __call__

lwm/vqgan.py:192–221  ·  view source on GitHub ↗
(self, z, encoding_indices=None)

Source from the content-addressed store, hash-verified

190
191 @nn.compact
192 def __call__(self, z, encoding_indices=None):
193 def quantize(encoding_indices):
194 w = jax.device_put(embeddings)
195 return w[(encoding_indices,)]
196 embeddings = self.param(
197 'embeddings',
198 lambda rng, shape, dtype: jax.random.uniform(
199 rng, shape, dtype, minval=-1.0 / self.n_e, maxval=1.0 / self.n_e
200 ),
201 [self.n_e, self.e_dim], jnp.float32
202 )
203
204 if encoding_indices is not None:
205 return quantize(encoding_indices)
206
207 z_flattened = z.reshape(-1, z.shape[-1])
208 d = jnp.sum(z_flattened ** 2, axis=1, keepdims=True) + \
209 jnp.sum(embeddings.T ** 2, axis=0, keepdims=True) - \
210 2 * jnp.einsum('bd,nd->bn', z_flattened, embeddings)
211
212 min_encoding_indices = jnp.argmin(d, axis=1)
213 z_q = quantize(min_encoding_indices)
214 z_q = jnp.reshape(z_q, z.shape)
215 z_q = z + jax.lax.stop_gradient(z_q - z)
216
217 encodings_one_hot = jax.nn.one_hot(min_encoding_indices, num_classes=self.n_e)
218 assert len(encodings_one_hot.shape) == 2
219 min_encoding_indices = jnp.reshape(min_encoding_indices, z.shape[:-1])
220
221 return z_q, min_encoding_indices
222
223
224class DownsamplingBlock(nn.Module):

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected