logankilpatrick
logankilpatrick

Reputation: 14521

What does @with_kw do in Julia?

I am reading some code which looks like:

 @with_kw struct HyperParams
     batch_size::Int = 128
     latent_dim::Int = 100
     epochs::Int = 25
     verbose_freq::Int = 1000
     output_dim::Int = 5
     disc_lr::Float64 = 0.0002
     gen_lr::Float64 = 0.0002
     device::Function = gpu
 end

but it is unclear to me what the @with_kw is doing in this context. Is this still a normal struct? It does not look like the macro is part of base Julia so I am unfamiliar with its usage here.

Upvotes: 4

Views: 3629

Answers (1)

logankilpatrick
logankilpatrick

Reputation: 14521

So it looks like the @with_kw is part of the Parameters package where it provides the ability to define default values for a struct fields and keyword arguments. Per the Julia docs here: https://docs.julialang.org/en/v1/manual/types/#Composite-Types it does not look like you can define default values so this is actually quite useful in that case. Here is an example of what is possible with the keyword arguments and default values:

julia> @with_kw struct HyperParams
            batch_size::Int = 128
            latent_dim::Int = 100
            epochs::Int = 25
            verbose_freq::Int = 1000
            output_dim::Int = 5
            disc_lr::Float64 = 0.0002
            gen_lr::Float64 = 0.0002
            device::Function
        end
HyperParams

julia> hyper = HyperParams(device=cpu)
HyperParams
  batch_size: Int64 128
  latent_dim: Int64 100
  epochs: Int64 25
  verbose_freq: Int64 1000
  output_dim: Int64 5
  disc_lr: Float64 0.0002
  gen_lr: Float64 0.0002
  device: cpu (function of type typeof(cpu))


julia> HyperParams()
ERROR: Field 'device' has no default, supply it with keyword.
Stacktrace:
 [1] error(s::String)
   @ Base ./error.jl:33
 [2] HyperParams()
   @ Main ~/.julia/packages/Parameters/MK0O4/src/Parameters.jl:493
 [3] top-level scope
   @ REPL[61]:1

julia> hyper = HyperParams(epochs=20, device=cpu)
HyperParams
  batch_size: Int64 128
  latent_dim: Int64 100
  epochs: Int64 20
  verbose_freq: Int64 1000
  output_dim: Int64 5
  disc_lr: Float64 0.0002
  gen_lr: Float64 0.0002
  device: cpu (function of type typeof(cpu))

Upvotes: 4

Related Questions