|
| 1 | +using Flux |
| 2 | +using FFTW |
| 3 | +using Tullio |
| 4 | + |
| 5 | +export |
| 6 | + SpectralConv1d, |
| 7 | + FourierOperator, |
| 8 | + FNO |
| 9 | + |
| 10 | +c_glorot_uniform(dims...) = Flux.glorot_uniform(dims...) + Flux.glorot_uniform(dims...) * im |
| 11 | + |
| 12 | +struct SpectralConv1d{T, S} |
| 13 | + weight::T |
| 14 | + in_channel::S |
| 15 | + out_channel::S |
| 16 | + modes::S |
| 17 | + σ |
| 18 | +end |
| 19 | + |
| 20 | +function SpectralConv1d( |
| 21 | + ch::Pair{<:Integer,<:Integer}, |
| 22 | + modes::Integer, |
| 23 | + σ=identity; |
| 24 | + init=c_glorot_uniform, |
| 25 | + T::DataType=ComplexF32 |
| 26 | +) |
| 27 | + in_chs, out_chs = ch |
| 28 | + scale = one(T) / (in_chs * out_chs) |
| 29 | + weights = scale * init(out_chs, in_chs, modes) |
| 30 | + |
| 31 | + return SpectralConv1d(weights, in_chs, out_chs, modes, σ) |
| 32 | +end |
| 33 | + |
| 34 | +Flux.@functor SpectralConv1d |
| 35 | + |
| 36 | +function (m::SpectralConv1d)(𝐱::AbstractArray) |
| 37 | + 𝐱_fft = fft(𝐱, 2) # [in_chs, x, batch] |
| 38 | + 𝐱_selected = 𝐱_fft[:, 1:m.modes, :] # [in_chs, modes, batch] |
| 39 | + |
| 40 | + # [out_chs, modes, batch] <- [in_chs, modes, batch] [out_chs, in_chs, modes] |
| 41 | + @tullio 𝐱_weighted[o, m, b] := 𝐱_selected[i, m, b] * m.weight[o, i, m] |
| 42 | + |
| 43 | + s = size(𝐱_weighted) |
| 44 | + d = size(𝐱, 2) - m.modes |
| 45 | + 𝐱_padded = cat(𝐱_weighted, zeros(ComplexF32, s[1], d, s[3:end]...), dims=2) |
| 46 | + |
| 47 | + 𝐱_out = ifft(𝐱_padded, 2) |
| 48 | + |
| 49 | + return m.σ.(𝐱_out) |
| 50 | +end |
| 51 | + |
| 52 | +function FourierOperator( |
| 53 | + ch::Pair{<:Integer,<:Integer}, |
| 54 | + modes::Integer, |
| 55 | + σ=identity |
| 56 | +) |
| 57 | + return Chain( |
| 58 | + Parallel(+, |
| 59 | + Dense(ch.first, ch.second, init=c_glorot_uniform), |
| 60 | + SpectralConv1d(ch, modes) |
| 61 | + ), |
| 62 | + x -> σ.(x) |
| 63 | + ) |
| 64 | +end |
| 65 | + |
| 66 | +function FNO() |
| 67 | + modes = 16 |
| 68 | + ch = 64 => 64 |
| 69 | + σ = x -> @. log(1 + exp(x)) |
| 70 | + |
| 71 | + return Chain( |
| 72 | + Dense(2, 64, init=c_glorot_uniform), |
| 73 | + FourierOperator(ch, modes, σ), |
| 74 | + FourierOperator(ch, modes, σ), |
| 75 | + FourierOperator(ch, modes, σ), |
| 76 | + FourierOperator(ch, modes), |
| 77 | + Dense(64, 128, σ, init=c_glorot_uniform), |
| 78 | + Dense(128, 1, init=c_glorot_uniform), |
| 79 | + flatten |
| 80 | + ) |
| 81 | +end |
0 commit comments