|
| 1 | +namespace tensorflow.keras { |
| 2 | + using System; |
| 3 | + using System.Collections.Generic; |
| 4 | + using System.Diagnostics; |
| 5 | + using System.Drawing; |
| 6 | + using System.Drawing.Imaging; |
| 7 | + using System.Linq; |
| 8 | + |
| 9 | + using LostTech.Gradient; |
| 10 | + using LostTech.TensorFlow; |
| 11 | + |
| 12 | + using numpy; |
| 13 | + |
| 14 | + using tensorflow.keras.callbacks; |
| 15 | + using tensorflow.keras.layers; |
| 16 | + using tensorflow.keras.losses; |
| 17 | + using tensorflow.keras.optimizers; |
| 18 | + |
| 19 | + class UpscaleProgram { |
| 20 | + static void Main(string[] args) { |
| 21 | + GradientEngine.UseEnvironmentFromVariable(); |
| 22 | + TensorFlowSetup.Instance.EnsureInitialized(); |
| 23 | + |
| 24 | + // this allows SIREN to oversaturate channels without adding to the loss |
| 25 | + var clampToValidChannelRange = PythonFunctionContainer.Of<Tensor, Tensor>(ClampToValidChannelValueRange); |
| 26 | + var siren = new Sequential(new object[] { |
| 27 | + new GaussianNoise(stddev: 1f/(128*1024)), |
| 28 | + new Siren(2, Enumerable.Repeat(256, 5).ToArray()), |
| 29 | + new Dense(units: 4, activation: clampToValidChannelRange), |
| 30 | + new GaussianNoise(stddev: 1f/128), |
| 31 | + }); |
| 32 | + |
| 33 | + siren.compile( |
| 34 | + // too slow to converge |
| 35 | + //optimizer: new SGD(momentum: 0.5), |
| 36 | + // lowered learning rate to avoid destabilization |
| 37 | + optimizer: new Adam(learning_rate: 0.00032), |
| 38 | + loss: new MeanSquaredError()); |
| 39 | + |
| 40 | + foreach (string imagePath in args) { |
| 41 | + using var original = new Bitmap(imagePath); |
| 42 | + byte[,,] image = ToBytesHWC(original); |
| 43 | + int height = image.GetLength(0); |
| 44 | + int width = image.GetLength(1); |
| 45 | + int channels = image.GetLength(2); |
| 46 | + Debug.Assert(channels == 4); |
| 47 | + |
| 48 | + var imageSamples = PrepareImage(image); |
| 49 | + |
| 50 | + var coords = SirenTests.Coord(height, width).ToNumPyArray() |
| 51 | + .reshape(new[] { width * height, 2 }); |
| 52 | + |
| 53 | + var upscaleCoords = SirenTests.Coord(height * 2, width * 2).ToNumPyArray(); |
| 54 | + |
| 55 | + var improved = new ImprovedCallback(); |
| 56 | + improved.OnLossImproved += (sender, eventArgs) => { |
| 57 | + if (eventArgs.Epoch < 10) return; |
| 58 | + ndarray<float> upscaled = siren.predict( |
| 59 | + upscaleCoords.reshape(new[] { height * width * 4, 2 }), |
| 60 | + batch_size: 1024); |
| 61 | + upscaled = (ndarray<float>)upscaled.reshape(new[] { height * 2, width * 2, channels }); |
| 62 | + using var bitmap = ToImage(RestoreImage(upscaled)); |
| 63 | + bitmap.Save("sample4X.png", ImageFormat.Png); |
| 64 | + |
| 65 | + siren.save_weights("sample.weights"); |
| 66 | + |
| 67 | + Console.WriteLine(); |
| 68 | + Console.WriteLine("saved!"); |
| 69 | + }; |
| 70 | + |
| 71 | + siren.fit(coords, imageSamples, epochs: 100, batchSize: 64, stepsPerEpoch: 200, |
| 72 | + shuffleMode: TrainingShuffleMode.Batch, |
| 73 | + callbacks: new ICallback[] { improved }); |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + class ImprovedCallback : Callback { |
| 78 | + double bestLoss = double.PositiveInfinity; |
| 79 | + public override void on_epoch_end(int epoch, IDictionary<string, dynamic> logs) { |
| 80 | + base.on_epoch_end(epoch, logs); |
| 81 | + if (logs["loss"] < this.bestLoss) { |
| 82 | + this.bestLoss = logs["loss"]; |
| 83 | + this.OnLossImproved?.Invoke(this, new EpochEndEventArgs { |
| 84 | + Epoch = epoch, |
| 85 | + Logs = logs, |
| 86 | + }); |
| 87 | + } |
| 88 | + } |
| 89 | + |
| 90 | + public event EventHandler<EpochEndEventArgs> OnLossImproved; |
| 91 | + } |
| 92 | + |
| 93 | + class EpochEndEventArgs : EventArgs { |
| 94 | + public int Epoch { get; set; } |
| 95 | + public IDictionary<string, dynamic> Logs { get; set; } |
| 96 | + } |
| 97 | + |
| 98 | + static ndarray<float> PrepareImage(byte[,,] image) { |
| 99 | + int height = image.GetLength(0); |
| 100 | + int width = image.GetLength(1); |
| 101 | + int channels = image.GetLength(2); |
| 102 | + |
| 103 | + var normalized = SirenTests.NormalizeChannelValue(image.ToNumPyArray()); |
| 104 | + var flattened = normalized.reshape(new[] { height * width, channels }).astype(np.float32_fn); |
| 105 | + return (ndarray<float>)flattened; |
| 106 | + } |
| 107 | + |
| 108 | + static Tensor ClampToValidChannelValueRange(Tensor input) |
| 109 | + => tf.clip_by_value(input, |
| 110 | + clip_value_min: SirenTests.NormalizeChannelValue(-0.01f), |
| 111 | + clip_value_max: SirenTests.NormalizeChannelValue(255.01f)); |
| 112 | + |
| 113 | + static unsafe byte[,,] RestoreImage(ndarray<float> learnedImage) { |
| 114 | + (int height, int width, int channels) = (ValueTuple<int, int, int>)learnedImage.shape; |
| 115 | + var bytes = (learnedImage * 128f + 128f).clip(0, 255).astype(np.uint8_fn).tobytes(); |
| 116 | + Debug.Assert(bytes.Length == height * width * channels); |
| 117 | + byte[,,] result = new byte[height, width, channels]; |
| 118 | + fixed (byte* dest = result) |
| 119 | + fixed (byte* source = bytes) |
| 120 | + Buffer.MemoryCopy(source: source, destination: dest, bytes.Length, bytes.Length); |
| 121 | + return result; |
| 122 | + } |
| 123 | + |
| 124 | + static unsafe Bitmap ToImage(byte[,,] bytesHWC) { |
| 125 | + if (bytesHWC.GetLength(2) != 4) |
| 126 | + throw new NotSupportedException(); |
| 127 | + var bitmap = new Bitmap(bytesHWC.GetLength(1), bytesHWC.GetLength(0)); |
| 128 | + int rowBytes = bitmap.Width * 4; |
| 129 | + var rect = new Rectangle(default, new Size(bitmap.Width, bitmap.Height)); |
| 130 | + var data = bitmap.LockBits(rect, ImageLockMode.WriteOnly, PixelFormat.Format32bppArgb); |
| 131 | + try { |
| 132 | + fixed (byte* source = bytesHWC) { |
| 133 | + for (int y = 0; y < bitmap.Height; y++) { |
| 134 | + var dest = data.Scan0 + data.Stride * y; |
| 135 | + Buffer.MemoryCopy(&source[rowBytes * y], destination: (byte*)dest, rowBytes, rowBytes); |
| 136 | + } |
| 137 | + } |
| 138 | + } finally { |
| 139 | + bitmap.UnlockBits(data); |
| 140 | + } |
| 141 | + |
| 142 | + return bitmap; |
| 143 | + } |
| 144 | + |
| 145 | + static unsafe byte[,,] ToBytesHWC(Bitmap bitmap) { |
| 146 | + byte[,,] result = new byte[bitmap.Height, bitmap.Width, 4]; |
| 147 | + int rowBytes = bitmap.Width * 4; |
| 148 | + var rect = new Rectangle(default, new Size(bitmap.Width, bitmap.Height)); |
| 149 | + var data = bitmap.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb); |
| 150 | + try { |
| 151 | + fixed (byte* dest = result) { |
| 152 | + for (int y = 0; y < bitmap.Height; y++) { |
| 153 | + var source = data.Scan0 + data.Stride * y; |
| 154 | + Buffer.MemoryCopy((byte*)source, destination: &dest[rowBytes * y], rowBytes, rowBytes); |
| 155 | + } |
| 156 | + } |
| 157 | + } finally { |
| 158 | + bitmap.UnlockBits(data); |
| 159 | + } |
| 160 | + |
| 161 | + return result; |
| 162 | + } |
| 163 | + } |
| 164 | +} |
0 commit comments