### Convert Keras Model to ONNX and Save Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Installs necessary dependencies, converts a Keras model to ONNX format with specific input signatures, and copies the resulting files to Google Drive. ```python !pip install tf2onnx !pip install onnx import tensorflow as tf import tf2onnx import onnx input_signature = [tf.TensorSpec([1, None, None, 1], tf.float32, name='input')] onnx_model, _ = tf2onnx.convert.from_keras(model=model, input_signature=input_signature, inputs_as_nchw=['input'], outputs_as_nchw=['depth_to_space']) onnx.save(onnx_model, "/content/c4f32_dft.onnx") model.save('/content/c4f32.keras') !cp /content/c4f32.keras /content/drive/MyDrive/tmp/c4f32.keras !cp /content/c4f32.onnx /content/drive/MyDrive/tmp/c4f32.onnx ``` -------------------------------- ### Load and preprocess image for ArtCNN training Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Loads a grayscale image, normalizes to [0,1], applies flip_and_rotate augmentation, and creates a reference image with an added channel dimension. The input image is downscaled by 0.5 using area interpolation and also gets a channel dimension. Returns (in_image, ref_image). ```python def load_and_process(file): image = cv2.imread(file, cv2.IMREAD_GRAYSCALE).astype(np.float32) / 255.0 image = flip_and_rotate(image) ref_image = image[..., None].copy() in_image = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation=cv2.INTER_AREA) in_image = in_image[..., None] return in_image, ref_image ``` -------------------------------- ### Save ArtCNN weights to zip with Orbax Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Saves the current model weights to a zip archive. Cleans up any existing directory or zip, splits the model to get the state, saves it with Orbax StandardCheckpointer, waits until finished, and creates a zip archive from the saved directory. The archive is named r{blocks}f{filters}.zip in /content. ```python def save_weights(): base_path = Path(f"/content/r{blocks}f{filters}") zip_path = Path(f"/content/r{blocks}f{filters}.zip") if base_path.exists() and base_path.is_dir(): shutil.rmtree(base_path) if zip_path.exists(): zip_path.unlink() _, state = nnx.split(model) checkpointer = ocp.StandardCheckpointer() checkpointer.save(str(base_path), state, force=True) checkpointer.wait_until_finished() shutil.make_archive(str(base_path), 'zip', root_dir=base_path) ``` -------------------------------- ### Mount Google Drive and Import Datasets Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Mounts Google Drive and copies necessary model weights and training datasets to the local environment. ```python from google.colab import drive drive.mount('/content/drive') !cp /content/drive/MyDrive/tmp/c4f32.keras /content/c4f32.keras !cp /content/drive/MyDrive/Datasets/Anime_Train_HR.zip /content/HR1.zip !cp /content/drive/MyDrive/Datasets/Digital_Art_Train_HR.zip /content/HR2.zip !unzip /content/HR1.zip !unzip /content/HR2.zip ``` -------------------------------- ### Configure optimizer, loss scale, and Grain data pipeline Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Sets up training hyperparameters, optimizer (AdamW with learning rate 0.000025), static loss scale (2^15), and a Grain data pipeline that shuffles, repeats, maps load_and_process, and batches the file list. The filelist is sorted glob of PNGs in /content/HR. ```python batch_size = 8 learning_rate = 0.000025 optimizer = nnx.Optimizer(model, optax.adamw(learning_rate), wrt=nnx.Param) loss_scale = jmp.StaticLossScale(2 ** 15) filelist = sorted(glob.glob('/content/HR/*.png')) steps_per_epoch = len(filelist) // batch_size train_generator = iter( grain.MapDataset.source(filelist) .shuffle(seed=10) .repeat() .map(load_and_process) .to_iter_dataset(grain.ReadOptions(num_threads=4, prefetch_buffer_size=64)) .batch(batch_size=batch_size) ) ``` -------------------------------- ### Initialize Shader License Header Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Sets the initial shader code string with the MIT license header. ```python filters = model.layers[1].filters shader_code = """// MIT License // Copyright (c) 2024 Joao Chrisostomo, Kacper Michajłow // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. """ ``` -------------------------------- ### Initialize Environment and Model Architecture Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Sets up the Keras environment and defines the ArtCNN model architecture, including a custom DepthToSpace layer for upsampling. ```python #!pip install --upgrade keras #!pip install --upgrade tensorflow import os os.environ["KERAS_BACKEND"] = "tensorflow" import keras import numpy as np import cv2 import tensorflow as tf # For JAX backend # class DepthToSpace(keras.layers.Layer): # def __init__(self, block_size): # super().__init__() # self.block_size = block_size # def call(self, input): # batch, height, width, depth = keras.ops.shape(input) # depth = depth // (self.block_size**2) # x = keras.ops.reshape(input, [batch, height, width, self.block_size, self.block_size, depth]) # x = keras.ops.transpose(x, [0, 1, 3, 2, 4, 5]) # x = keras.ops.reshape(x, [batch, height * self.block_size, width * self.block_size, depth]) # x = keras.activations.relu(x, max_value=1.0) # return x class DepthToSpace(keras.layers.Layer): def __init__(self): super().__init__() def call(self, x): x = tf.nn.depth_to_space(x, 2) x = tf.clip_by_value(x, 0.0, 1.0) return x # Settings filters = 32 # Build the model: inputs = keras.layers.Input(shape=(None,None,1)) conv0 = keras.layers.Conv2D(filters=filters, kernel_size=3, padding='same')(inputs) # Internal convolutions conv1 = keras.layers.Conv2D(filters=filters, kernel_size=3, padding='same', activation='relu')(conv0) conv2 = keras.layers.Conv2D(filters=filters, kernel_size=3, padding='same', activation='relu')(conv1) conv3 = keras.layers.Conv2D(filters=filters, kernel_size=3, padding='same', activation='relu')(conv2) conv4 = keras.layers.Conv2D(filters=filters, kernel_size=3, padding='same', activation='relu')(conv3) # Feature Fusion mix_global = keras.layers.Conv2D(filters=filters, kernel_size=3, padding='same')(conv4) add_global = keras.layers.Add()([mix_global, conv0]) # Upsampler features = keras.layers.Conv2D(filters=4, kernel_size=3, padding='same')(add_global) outputs = DepthToSpace()(features) # Defining the model model = keras.Model(inputs=inputs, outputs=outputs) model.summary() keras.utils.plot_model(model, show_shapes=True) # model.load_weights("/content/c4f32.keras", skip_mismatch=True) ``` -------------------------------- ### RGB upscaling with inferencer.py Source: https://github.com/artoriuz/artcnn/blob/main/Inferencer/README.md Runs RGB upscaling with an RGB model. Assumes the ONNX models are in the inferencer's directory. ```shell python inferencer.py image.png --model ArtCNN_R8F64_RGB.onnx --task rgb ``` -------------------------------- ### Prepare Separate HR and LR Datasets Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Loads and processes separate directories for low-resolution (LR) and high-resolution (HR) images for training. ```python # Separate HR and LR import glob import cv2 filelist1 = sorted(glob.glob('/content/LR/*.png')) train_in = [] for myFile in filelist1: image = cv2.imread(myFile, cv2.IMREAD_COLOR) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY, 0) train_in.append(image) train_in = np.array(train_in).astype(np.float32) / 255.0 train_in = np.clip(train_in, 0.0, 1.0) train_in = np.expand_dims(train_in, axis=-1) print(train_in.shape) filelist2 = sorted(glob.glob('/content/HR/*.png')) train_ref = [] for myFile in filelist2: image = cv2.imread(myFile, cv2.IMREAD_COLOR) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY, 0) train_ref.append(image) train_ref = np.array(train_ref).astype(np.float32) / 255.0 train_ref = np.clip(train_ref, 0.0, 1.0) train_ref = np.expand_dims(train_ref, axis=-1) print(train_ref.shape) ``` -------------------------------- ### Luma upscaling with inferencer.py Source: https://github.com/artoriuz/artcnn/blob/main/Inferencer/README.md Runs luma upscaling with a luma model. Assumes the ONNX models are in the inferencer's directory. ```shell python inferencer.py image.png --model ArtCNN_R8F64.onnx --task luma ``` -------------------------------- ### Create ImagePairDataset and DataLoader Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Torch.ipynb Defines a PyTorch Dataset that loads grayscale images, normalizes to [0,1], creates a half-resolution input via cv2.resize, and returns tensors. Sets up a DataLoader with batch size 8, shuffle, and 8 workers. ```python import torch from torch.utils.data import Dataset, DataLoader import cv2 import glob import numpy as np import random class ImagePairDataset(Dataset): def __init__(self, filelist): self.filelist = filelist def __len__(self): return len(self.filelist) def __getitem__(self, idx): file = self.filelist[idx] image = cv2.imread(file, cv2.IMREAD_GRAYSCALE) image = image.astype(np.float32) / 255.0 image = np.clip(image, 0.0, 1.0) ref_image = np.expand_dims(image.copy(), axis=0) # shape: (1, H, W) in_image = cv2.resize(image.copy(), None, fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR_EXACT) in_image = np.clip(in_image, 0.0, 1.0) in_image = np.expand_dims(in_image, axis=0) # shape: (1, H/2, W/2) return torch.tensor(in_image, dtype=torch.float32), torch.tensor(ref_image, dtype=torch.float32) # Create DataLoader for training data filelist = sorted(glob.glob('/content/HR/*.png')) train_dataset = ImagePairDataset(filelist) train_loader = DataLoader( train_dataset, batch_size=8, shuffle=True, num_workers=8, pin_memory=True ) ``` -------------------------------- ### Training Loop with tqdm Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Executes the training loop for a specified number of epochs, updating a progress bar and saving weights after each epoch. ```python epochs = 500 for epoch in range(epochs): epoch_loss = 0.0 with tqdm(total=steps_per_epoch, desc=f"Epoch {epoch + 1}/{epochs}", unit="step") as pbar: for step in range(steps_per_epoch): batch_in, batch_ref = next(train_generator) loss = train_step(model, optimizer, batch_in, batch_ref, loss_scale) epoch_loss += float(loss) running_avg = epoch_loss / (step + 1) pbar.set_postfix(avg_loss=f"{running_avg:.8f}") pbar.update(1) save_weights() ``` -------------------------------- ### inferencer.py CLI usage and options Source: https://github.com/artoriuz/artcnn/blob/main/Inferencer/README.md Shows the CLI usage and all options for inferencer.py, including the positional input argument, the -m/--model and -cm/--chroma-model flags, the -t/--task choices, and the --self-ensemble flag. ```shell usage: inferencer.py [-h] [-m MODEL] [-cm CHROMA_MODEL] [-t {luma,rgb,ycbcr,chroma,luma-chroma,luma-luma-luma}] [--self-ensemble] input ONNX Inferencer positional arguments: input Input image or directory options: -h, --help show this help message and exit -m MODEL, --model MODEL ArtCNN Model -cm CHROMA_MODEL, --chroma-model CHROMA_MODEL ArtCNN Chroma Model -t {luma,rgb,ycbcr,chroma,luma-chroma,luma-luma-luma}, --task {luma,rgb,ycbcr,chroma,luma-chroma,luma-luma-luma} Task to perform --self-ensemble Enable self-ensemble inference ``` -------------------------------- ### Prepare Single Dataset for Training Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Processes a single directory of images by converting them to grayscale, normalizing, and generating low-resolution inputs via resizing. ```python # Single Dataset Gray import glob import cv2 filelist = sorted(glob.glob('/content/HR/*.png')) train_ref = [] train_in = [] for myFile in filelist: image = cv2.imread(myFile, cv2.IMREAD_COLOR) image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY, 0) image = np.array(image).astype(np.float32) / 255.0 image = np.clip(image, 0.0, 1.0) train_ref.append(image.copy()) train_in = cv2.resize(image.copy(), None, fx=0.5, fy=0.5, interpolation=cv2.INTER_LINEAR_EXACT) train_in = np.clip(train_in, 0.0, 1.0) train_in.append(image) train_ref = np.array(train_ref) train_ref = np.expand_dims(train_ref, axis=-1) print(train_ref.shape) train_in = np.array(train_in) train_in = np.expand_dims(train_in, axis=-1) print(train_in.shape) ``` -------------------------------- ### Train the Model Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Compiles the model with AdamW optimizer and Mean Absolute Error loss, then fits it to the training data. ```python # Train the model model.compile(optimizer=keras.optimizers.AdamW(learning_rate=0.00005), loss=keras.losses.MeanAbsoluteError()) history = model.fit(train_in, train_ref, epochs=500, batch_size=8, verbose=1) ``` -------------------------------- ### JIT train_step with value_and_grad and loss scaling Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb JIT-compiled training step that computes gradients via nnx.value_and_grad, unscales loss and gradients, and updates the optimizer. Returns the unscaled loss. Requires the optimizer to be an nnx.Optimizer and loss_scale to be a jmp loss scale. ```python @nnx.jit def train_step(model, optimizer, input, target, loss_scale): loss, grads = nnx.value_and_grad(forward)(model, input, target, loss_scale) loss = loss_scale.unscale(loss) grads = loss_scale.unscale(grads) optimizer.update(model, grads) return loss ``` -------------------------------- ### Augment HR images with rotations and flips Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Torch.ipynb Reads all PNG images from '/content/HR/', applies rotations (0, 90, 180, 270) and horizontal flips, saves augmented versions, and removes the original file. Uses OpenCV and tqdm for progress. ```python import cv2 import numpy as np import glob import os from pathlib import Path from tqdm import tqdm rotations = [0, 90, 180, 270] filelist = sorted(glob.glob('/content/HR/*.png')) for myFile in tqdm(filelist): img = cv2.imread(myFile, cv2.IMREAD_UNCHANGED) # Preserve grayscale if img is None: # Check if image was read correctly print(f"Error reading image: {myFile}") continue for rotation in rotations: rotated_img = np.rot90(img, rotation // 90) # More efficient rotation cv2.imwrite("/content/HR/" + str(Path(myFile).stem) + str(rotation) + ".png", rotated_img) flipped_img = cv2.flip(img, 1) # Horizontal flip (flop) for rotation in rotations: rotated_flipped_img = np.rot90(flipped_img, rotation // 90) cv2.imwrite("/content/HR/" + str(Path(myFile).stem) + str(rotation) + "f.png", rotated_flipped_img) os.remove(myFile) ``` -------------------------------- ### JPEG denoising with inferencer.py Source: https://github.com/artoriuz/artcnn/blob/main/Inferencer/README.md Runs JPEG denoising with a JPEG model. Assumes the ONNX models are in the inferencer's directory. ```shell python inferencer.py image.jpg --model ArtCNN_R8F64_JPEG420.onnx --task rgb ``` -------------------------------- ### Make a single RGB prediction with cv2 and model.predict Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Loads an RGB image, normalizes it to [0,1], splits into B/G/R channels, predicts each channel with the model, then stacks, clips, scales, and saves the result as '/content/prediction.png'. ```python # Make a single RGB prediction input = cv2.imread('/content/aoko.png', cv2.IMREAD_COLOR) input = np.array(input).astype(np.float32) / 255.0 input = np.clip(input, 0.0, 1.0) (input_b, input_g, input_r) = cv2.split(input) input_b = np.expand_dims(input_b, axis=0) input_g = np.expand_dims(input_g, axis=0) input_r = np.expand_dims(input_r, axis=0) input_b = np.expand_dims(input_b, axis=-1) input_g = np.expand_dims(input_g, axis=-1) input_r = np.expand_dims(input_r, axis=-1) pred_b = model.predict(input_b) pred_g = model.predict(input_g) pred_r = model.predict(input_r) pred = np.stack((pred_b, pred_g, pred_r), axis=-1) pred = np.clip(pred, 0.0, 1.0) pred = np.squeeze(pred) pred = pred * 255.0 pred = np.squeeze((np.around(pred)).astype(np.uint8)) cv2.imwrite('/content/prediction.png', pred) ``` -------------------------------- ### Define ArtCNN model with Flax NNX and print tabulate Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Defines the ArtCNN model using Flax NNX with DepthToSpace and ResBlock modules, then instantiates it and prints a tabulated summary. Uses jnp.float16 for convolutions and he_normal/zeros_init initializers. The model expects a single-channel 256x256 input and outputs a clipped 0..1 image. ```python import jax import flax import optax import cv2 import glob import treescope import dm_pix as pix import numpy as np import jax.numpy as jnp import orbax.checkpoint as ocp import random import jmp import grain import shutil from pathlib import Path from flax import nnx from tqdm import tqdm from jax2onnx import to_onnx # Settings filters = 64 blocks = 8 class DepthToSpace(nnx.Module): def __init__(self, *, rngs: nnx.Rngs): self.block_size = 2 def __call__(self, input): x = pix.depth_to_space(input, self.block_size) return x class ResBlock(nnx.Module): def __init__(self, *, rngs: nnx.Rngs): self.conv0 = nnx.Conv(filters, filters, kernel_size=(3, 3), rngs=rngs, dtype=jnp.float16, kernel_init=nnx.initializers.he_normal()) self.conv1 = nnx.Conv(filters, filters, kernel_size=(3, 3), rngs=rngs, dtype=jnp.float16, kernel_init=nnx.initializers.he_normal()) self.conv2 = nnx.Conv(filters, filters, kernel_size=(3, 3), rngs=rngs, dtype=jnp.float16, kernel_init=nnx.initializers.zeros_init()) def __call__(self, input): x = nnx.silu(self.conv0(input)) x = nnx.silu(self.conv1(x)) x = self.conv2(x) x = x + input return x class ArtCNN(nnx.Module): def __init__(self, *, rngs: nnx.Rngs): self.conv0 = nnx.Conv(1, filters, kernel_size=(3, 3), rngs=rngs, dtype=jnp.float16) self.res_blocks = nnx.List(ResBlock(rngs=rngs) for _ in range(blocks)) self.conv1 = nnx.Conv(filters, filters, kernel_size=(3, 3), rngs=rngs, dtype=jnp.float16) self.feats_conv = nnx.Conv(filters, 4, kernel_size=(3, 3), rngs=rngs, dtype=jnp.float16) self.depth_to_space = DepthToSpace(rngs=rngs) def __call__(self, input): conv0 = self.conv0(input) x = conv0 for block in self.res_blocks: x = block(x) conv1 = self.conv1(x) x = conv1 + conv0 x = self.feats_conv(x) x = self.depth_to_space(x) x = jnp.clip(x, 0.0, 1.0) return x model = ArtCNN(rngs=nnx.Rngs(0)) treescope.basic_interactive_setup(autovisualize_arrays=True) print(nnx.tabulate(model, jnp.ones((1, 256, 256, 1)))) ``` -------------------------------- ### Train ArtCNN with PyTorch Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Torch.ipynb Configures the loss function, optimizer, and mixed-precision scaler before executing the training loop over a specified number of epochs. ```python import torch import torch.nn as nn import torch.optim as optim from tqdm import tqdm # Define loss function and optimizer loss_function = nn.L1Loss() optimizer = optim.AdamW(model.parameters(), lr=0.00005) scaler = torch.cuda.amp.GradScaler() # Move model to device if available device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) # Training loop num_epochs = 10 for epoch in range(num_epochs): model.train() running_loss = 0.0 progress_bar = tqdm(train_loader, desc=f"[Epoch {epoch + 1}/{num_epochs}]", unit="batch") for inputs, targets in progress_bar: inputs, targets = inputs.to(device), targets.to(device) optimizer.zero_grad(set_to_none=True) with torch.autocast(device_type="cuda"): outputs = model(inputs) loss = loss_function(outputs, targets) scaler.scale(loss).backward() scaler.step(optimizer) scaler.update() progress_bar.set_postfix({'loss': loss.item()}) running_loss += loss.item() * inputs.size(0) epoch_loss = running_loss / len(train_loader.dataset) print(f'Epoch [{epoch + 1}/{num_epochs}], Loss: {epoch_loss:.8f}') print('Finished Training') ``` -------------------------------- ### YCbCr upscaling with luma and chroma models Source: https://github.com/artoriuz/artcnn/blob/main/Inferencer/README.md Runs YCbCr upscaling using both a luma model and a chroma model together. Assumes the ONNX models are in the inferencer's directory. ```shell python inferencer.py image.png --model ArtCNN_R8F64.onnx --chroma-model ArtCNN_R8F64_Chroma.onnx --task luma-chroma ``` -------------------------------- ### mpv configuration for ArtCNN GLSL shader Source: https://github.com/artoriuz/artcnn/blob/main/README.md Add these lines to your mpv config to use the ArtCNN_C4F32 GLSL shader with the gpu-next video output. ```ini vo=gpu-next glsl-shader="path/to/shader/ArtCNN_C4F32.glsl" ``` -------------------------------- ### Compute Shader Generation Logic Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Contains helper functions to calculate tile dimensions and the main function to generate shader code strings with appropriate GLSL bindings and metadata. ```python #Generate compute shader import math import numpy as np def find_rect(area): s = int(math.sqrt(area)) for w in range(s, 0, -1): if area % w == 0: h = area // w return int(max(w, h)), int(min(w, h)) def get_tile_off(i, w): x = i % w y = i // w return x, y def generate_shader_code(current_layer, previous_layer, channels_in, channels_out): if previous_layer.name == "input_layer": previous_layer.name = "LUMA" threads_w, threads_h = 12, 16 tile_w, tile_h = find_rect(np.ceil(channels_out / 4.0)) tile_in_w, tile_in_h = find_rect(np.ceil(channels_in / 4.0)) shader_code = "" if any(layer_name in current_layer.name for layer_name in ["conv2d_1", "conv2d_2", "conv2d_3", "conv2d_4"]): shader_code += f"//!DESC ArtCNN C4F{filters} ({current_layer.name.title().replace('_', '-')}-ReLU)\n" else: shader_code += f"//!DESC ArtCNN C4F{filters} ({current_layer.name.title().replace('_', '-')})\n" shader_code += f"//!COMPUTE {threads_w * tile_w} {threads_h * tile_h} {threads_w} {threads_h}\n" shader_code += f"//!HOOK LUMA\n" if previous_layer.name == "LUMA": shader_code += f"//!BIND {previous_layer.name}\n" elif "add" in previous_layer.name: shader_code += f"//!BIND conv2d\n" shader_code += f"//!BIND conv2d_5\n" elif "conv2d" in current_layer.name: shader_code += f"//!BIND {previous_layer.name}\n" elif "depth" in current_layer.name: shader_code += f"//!BIND {previous_layer.name}\n" if "depth" in current_layer.name: shader_code += f"//!WIDTH LUMA.w 2.0 *\n" shader_code += f"//!HEIGHT LUMA.h 2.0 *\n" else: shader_code += f"//!SAVE {current_layer.name}\n" shader_code += f"//!WIDTH LUMA.w {float(tile_w)} *\n" shader_code += f"//!HEIGHT LUMA.h {float(tile_h)} *\n" shader_code += f"//!COMPONENTS 4\n" shader_code += f"//!WHEN OUTPUT.w LUMA.w / 1.3 > OUTPUT.h LUMA.h / 1.3 > *" shader_code += """ #extension GL_EXT_shader_explicit_arithmetic_types_float16 : enable #ifdef GL_EXT_shader_explicit_arithmetic_types_float16 # define V4 f16vec4 # define M4 f16mat4 # define F float16_t #else # define V4 vec4 # define M4 mat4 # define F float #endif """ if "conv2d" in current_layer.name: storage = "V4" weights_storage = "M4" load_suffix = "" if previous_layer.name == "LUMA": storage = "F" weights_storage = "V4" load_suffix = ".x" shader_code += "const ivec2 ksize = ivec2(3, 3);\n" shader_code += "const ivec2 offset = ksize / 2;\n" shader_code += "const ivec2 wg_size = ivec2(gl_WorkGroupSize);\n" shader_code += "const ivec2 isize = wg_size + ksize - 1;\n" shader_code += f"shared {storage} inp[{tile_in_w * tile_in_h}][isize.y][isize.x];\n" ``` -------------------------------- ### Perform Single Image Prediction Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Loads an image, preprocesses it, runs the model prediction, and saves the resulting upscaled image. ```python # Make a single prediction input = cv2.imread('/content/downscaled.png', cv2.IMREAD_COLOR) input = cv2.cvtColor(input, cv2.COLOR_BGR2GRAY, 0) input = np.array(input).astype(np.float32) / 255.0 input = np.clip(input, 0.0, 1.0) input = np.expand_dims(input, axis=0) input = np.expand_dims(input, axis=-1) pred = model.predict(input) pred = np.clip(pred, 0.0, 1.0) pred = np.squeeze(pred) pred = pred * 255.0 pred = np.squeeze((np.around(pred)).astype(np.uint8)) cv2.imwrite('/content/prediction.png', pred) ``` -------------------------------- ### Restore ArtCNN checkpoint with Orbax and nnx.merge Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Restores a previously saved model checkpoint from a zip archive. Unpacks the archive, splits the model into graphdef and state, restores the state with Orbax StandardCheckpointer, displays it, and merges it back into the model. Requires the zip file to exist at /content/r{blocks}f{filters}.zip. ```python shutil.unpack_archive(f'/content/r{blocks}f{filters}.zip', f'/content/r{blocks}f{filters}') graphdef, state = nnx.split(model) checkpointer = ocp.StandardCheckpointer() state_restored = checkpointer.restore(f'/content/r{blocks}f{filters}', state) nnx.display(state_restored) model = nnx.merge(graphdef, state_restored) ``` -------------------------------- ### Define ResBlock and Model with PixelShuffle Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Torch.ipynb Defines a residual block with SiLU activation and a super-resolution model using PixelShuffle. The model loads a pretrained state dict from '/content/r8f64_torch.pth' and clips outputs to [0,1] during inference. ```python import torch import torch.nn as nn import torch.nn.init as init from torchsummary import summary filters = 64 blocks = 8 class ResBlock(nn.Module): def __init__(self, filters=filters, kernel_size=3): super(ResBlock, self).__init__() self.act = nn.SiLU() self.conv0 = nn.Conv2d(filters, filters, kernel_size=kernel_size, padding='same') self.conv1 = nn.Conv2d(filters, filters, kernel_size=kernel_size, padding='same') self.conv2 = nn.Conv2d(filters, filters, kernel_size=kernel_size, padding='same') def forward(self, input): x = self.act(self.conv0(input)) x = self.act(self.conv1(x)) x = self.conv2(x) return x + input class Model(nn.Module): def __init__(self, filters=filters, kernel_size=3, upscale_factor=2): super(Model, self).__init__() self.conv0 = nn.Conv2d(1, filters, kernel_size=kernel_size, padding='same') self.res_blocks = nn.ModuleList([ResBlock() for _ in range(blocks)]) self.conv1 = nn.Conv2d(filters, filters, kernel_size=kernel_size, padding='same') self.feats_conv = nn.Conv2d(filters, 4, kernel_size=kernel_size, padding='same') self.pixel_shuffle = nn.PixelShuffle(upscale_factor) def forward(self, input): conv0 = self.conv0(input) x = conv0 for block in self.res_blocks: x = block(x) conv1 = self.conv1(x) x = self.feats_conv(conv1 + conv0) x = self.pixel_shuffle(x) if not self.training: x = torch.clip(x, 0.0, 1.0) return x model = Model() summary(model.cuda(), (1, 128, 128)) model.load_state_dict(torch.load("/content/r8f64_torch.pth")) ``` -------------------------------- ### Export Model to MLIR Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Exports the JAX model to an MLIR module and saves it to a file. ```python # Export MLIR input_spec = jax.ShapeDtypeStruct((1, 256, 256, 1), np.float32) exported = jax.export.export(jax.jit(model))(input_spec).mlir_module() print(exported) with open("ArtCNN_R8F64.mlir", "w") as file: file.write(exported) ``` -------------------------------- ### Export ArtCNN to ONNX and Save State Dict Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Torch.ipynb Exports the trained model to an ONNX file with dynamic axes and saves the model weights as a .pth file. ```python import onnx device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model.to(device) x = torch.ones((1, 1, 128, 128)) # N x C x W x H x = x.to(device) torch.onnx.export( model, x, '/content/r8f64_torch.onnx', opset_version=20, input_names = ['input'], output_names = ['output'], dynamic_axes={ 'input' : {0 : 'batch', 2: 'width', 3: 'height'}, 'output' : {0 : 'batch', 2: 'width', 3: 'height'}, } ) torch.save(model.state_dict(), "/content/r8f64_torch.pth") ``` -------------------------------- ### Forward pass with loss scaling Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Forward pass that computes the loss and scales it with the provided loss_scale. Used inside the jitted train_step to enable mixed-precision training. ```python def forward(model, input, target, loss_scale): pred = model(input) loss = loss_fn(pred, target) loss = loss_scale.scale(loss) return loss ``` -------------------------------- ### Generate Shader Hook for Depth Layers Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Constructs the GLSL hook function for depth processing layers. ```python elif "depth" in current_layer.name: shader_code += "void hook() {\n" shader_code += f" vec4 result = vec4(0.0, 0.0, 0.0, 1.0);\n" shader_code += f" vec2 f0 = fract({previous_layer.name}_pos * {previous_layer.name}_size);\n" shader_code += f" ivec2 i0 = ivec2(f0 * vec2(2.0));\n" shader_code += f" result.x = {previous_layer.name}_tex((vec2(0.5) - f0) * {previous_layer.name}_pt + {previous_layer.name}_pos)[i0.y * 2 + i0.x];\n" shader_code += f" imageStore(out_image, ivec2(gl_GlobalInvocationID), clamp(result, 0.0, 1.0));\n" shader_code += "}\n\n" return shader_code ``` -------------------------------- ### Export Model to ONNX Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Exports the trained ArtCNN model to the ONNX format with specified input/output shapes and opset version. ```python # Export ONNX to_onnx(model, [(1, "H", "W", 1)], return_mode="file", output_path=f"ArtCNN_R{blocks}F{filters}.onnx", inputs_as_nchw=[0], outputs_as_nchw=[0], input_names=["input"], output_names=["output"], opset=19, model_name=f"ArtCNN_R{blocks}F{filters}") ``` -------------------------------- ### Generate and Save GLSL Shader Code Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Iterates through model layers to generate shader code based on layer names and saves the result to a compute.glsl file. ```python for i in range(1, len(model.layers)): if model.layers[i].name == "conv2d": shader_code += generate_shader_code(model.layers[i], model.layers[i - 1], 1, filters) elif model.layers[i].name == "conv2d_6": shader_code += generate_shader_code(model.layers[i], model.layers[i - 1], filters, 4) elif "conv2d_" in model.layers[i].name: shader_code += generate_shader_code(model.layers[i], model.layers[i - 1], filters, filters) elif model.layers[i].name == "depth_to_space": shader_code += generate_shader_code(model.layers[i], model.layers[i - 1], 4, 1) print(shader_code) with open("compute.glsl", mode="w", encoding="utf-8") as f: f.write(shader_code) ``` -------------------------------- ### Generate Shader Hook for Convolution Layers Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Constructs the GLSL hook function for convolution operations, handling input loading, weight application, and output storage. ```python shader_code += "void hook() {\n" shader_code += " const uvec2 local_xy = gl_LocalInvocationID.xy;\n" shader_code += " ivec2 base = ivec2(gl_WorkGroupID) * wg_size;\n" shader_code += " for (uint y = local_xy.y; y < isize.y; y += wg_size.y) {\n" shader_code += " for (uint x = local_xy.x; x < isize.x; x += wg_size.x) {\n" shader_code += f" const ivec2 input_base = (base + ivec2(x,y) - offset) * ivec2({tile_in_w}, {tile_in_h});\n" for z in range(tile_in_w * tile_in_h): x, y = get_tile_off(z, tile_in_w) if "add" in previous_layer.name: shader_code += f" inp[{z}][y][x] = {storage}(conv2d_5_mul * texelFetch(conv2d_5_raw, input_base + ivec2({x}, {y}), 0) + conv2d_mul * texelFetch(conv2d_raw, input_base + ivec2({x}, {y}), 0){load_suffix});\n" else: shader_code += f" inp[{z}][y][x] = {storage}({previous_layer.name}_mul * texelFetch({previous_layer.name}_raw, input_base + ivec2({x}, {y}), 0){load_suffix});\n" shader_code += " }\n" shader_code += " }\n" shader_code += "\n barrier();\n" for pass_idx in range(tile_w * tile_h): biases = current_layer.get_weights()[1][pass_idx*4:(pass_idx+1)*4] biases_str = ", ".join(str(w) for w in biases.flatten()) shader_code += f" V4 result{pass_idx} = V4({biases_str});\n" for z in range(tile_in_w * tile_in_h): for y in range(0, 3): for x in range(0, 3): shader_code += f" const {storage} inp_{z}_{x}_{y} = inp[{z}][local_xy.y + {y}][local_xy.x + {x}];\n" for pass_idx in range(tile_w * tile_h): for y in range(0, 3): for x in range(0, 3): weights = current_layer.get_weights()[0][y, x, z*4:(z+1)*4, pass_idx*4:(pass_idx+1)*4] weights_str = ", ".join(str(w) for w in weights.flatten()) if weights_str: shader_code += f" result{pass_idx} += {weights_storage}({weights_str}) * inp_{z}_{x}_{y};\n" shader_code += f" const ivec2 output_base = ivec2(gl_GlobalInvocationID) * ivec2({tile_w}, {tile_h});\n" for pass_idx in range(tile_w * tile_h): x, y = get_tile_off(pass_idx, tile_w) if any(layer_name in current_layer.name for layer_name in ["conv2d_1", "conv2d_2", "conv2d_3", "conv2d_4"]): shader_code += f" imageStore(out_image, output_base + ivec2({x}, {y}), max(result{pass_idx}, {storage}(0.0)));\n" else: shader_code += f" imageStore(out_image, output_base + ivec2({x}, {y}), result{pass_idx});\n" ``` -------------------------------- ### Random flip and rotate augmentation with cv2 and numpy Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Applies random data augmentation: randomly flips horizontally and rotates by 0, 90, 180, or 270 degrees. Used for training augmentation. The rotation is applied after the flip. ```python def flip_and_rotate(image): rotation = random.choice([0, 90, 180, 270]) flip = random.choice([True, False]) if flip: image = cv2.flip(image, 1) image = np.rot90(image, rotation // 90) return image ``` -------------------------------- ### Generate Shader Code from Keras Layers Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_C_Keras.ipynb Iterates through model layers to generate GLSL shader code based on layer names and types. It writes the final shader code to a file named fragment.glsl. ```python filters = model.layers[1].filters shader_code = """// MIT License // Copyright (c) 2024 Joao Chrisostomo // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. """ for i in range(1, len(model.layers)): if model.layers[i].name == "conv2d": shader_code += generate_shader_code(model.layers[i], model.layers[i - 1], 1, filters) elif "conv2d_6" in model.layers[i].name: shader_code += generate_shader_code(model.layers[i], model.layers[i - 1], filters, 4) elif "conv2d" in model.layers[i].name: shader_code += generate_shader_code(model.layers[i], model.layers[i - 1], filters, filters) elif "depth_to_space" in model.layers[i].name: shader_code += generate_shader_code(model.layers[i], model.layers[i - 1], 4, 1) print(shader_code) with open("fragment.glsl", mode="w") as f: f.write(shader_code) ``` -------------------------------- ### L1 loss function for ArtCNN Source: https://github.com/artoriuz/artcnn/blob/main/Notebooks/ArtCNN_R_Flax.ipynb Computes the mean absolute error (L1) loss between prediction and target, casting both to float32 first. Used as the training loss for the ArtCNN model. ```python def loss_fn(pred, target): pred = pred.astype(jnp.float32) target = target.astype(jnp.float32) loss = jnp.mean(jnp.absolute(target - pred)) return loss ```