Class: Daimond::NN::Module

Inherits:
Object
  • Object
show all
Defined in:
lib/daimond/nn/module.rb

Direct Known Subclasses

Conv2d, Conv2dRust, Flatten, Linear, MaxPool2d, MaxPool2dRust

Instance Method Summary collapse

Constructor Details

#initialize ⇒ Module

Returns a new instance of Module.



6
7
8
# File 'lib/daimond/nn/module.rb', line 6

def initialize
  @parameters = []
end

Instance Method Details

#call(*args) ⇒ Object



24
25
26
# File 'lib/daimond/nn/module.rb', line 24

def call(*args)
  forward(*args)
end

#forward(*args) ⇒ Object

Raises:

  • (NotImplementedError)


20
21
22
# File 'lib/daimond/nn/module.rb', line 20

def forward(*args)
  raise NotImplementedError
end

#load(path) ⇒ Object

Загрузка модели



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/daimond/nn/module.rb', line 40

def load(path)
  unless File.exist?(path)
    raise "Model file not found: #{path}"
  end

  params_data = File.open(path, 'rb') { |f| Marshal.load(f) }

  if params_data.length != @parameters.length
    raise "Parameter count mismatch: saved #{params_data.length} vs current #{@parameters.length}"
  end

  @parameters.each_with_index do |param, i|
    param.data = params_data[i]
    param.grad = Numo::DFloat.zeros(*param.data.shape)
  end

  puts "Model loaded from #{path}"
end

#parameters ⇒ Object



10
11
12
# File 'lib/daimond/nn/module.rb', line 10

def parameters
  @parameters
end

#save(path) ⇒ Object

Сохранение модели



29
30
31
32
33
34
35
36
37
# File 'lib/daimond/nn/module.rb', line 29

def save(path)
  FileUtils.mkdir_p(File.dirname(path)) if File.dirname(path) != '.'

  # Сохраняем массив весов как массив Numo массивов
  params_data = @parameters.map { |p| p.data }
  File.open(path, 'wb') { |f| Marshal.dump(params_data, f) }

  puts "Model saved to #{path} (#{@parameters.length} parameters)"
end

#zero_grad ⇒ Object



14
15
16
17
18
# File 'lib/daimond/nn/module.rb', line 14

def zero_grad
  @parameters.each do |p|
    p.grad = Numo::DFloat.zeros(*p.shape)
  end
end