* @brief Learning rate schedule * * The learning rate schedule class is used for compatibility of string schedule and custom schedule function. * Generally, you don't need to construct this class explictly. */
| 40 | * Generally, you don't need to construct this class explictly. |
| 41 | */ |
| 42 | class LRSchedule { |
| 43 | public: |
| 44 | typedef std::function<float(int, int)> ScheduleFunction; |
| 45 | |
| 46 | std::string type; |
| 47 | ScheduleFunction schedule_function; |
| 48 | |
| 49 | /** Construct a learning rate schedule */ |
| 50 | LRSchedule(const std::string &_type = "constant") : type(_type) { |
| 51 | CHECK(type == "linear" || type == "constant") << "Invalid schedule `" << type << "`"; |
| 52 | if (type == "linear") |
| 53 | schedule_function = linear_schedule; |
| 54 | if (type == "constant") |
| 55 | schedule_function = constant_schedule; |
| 56 | } |
| 57 | |
| 58 | /** Construct a learning rate from custom function */ |
| 59 | LRSchedule(const ScheduleFunction &_schedule_function) : |
| 60 | type("custom"), schedule_function(_schedule_function) {} |
| 61 | |
| 62 | LRSchedule(const char *_schedule) : LRSchedule(std::string(_schedule)) {} |
| 63 | |
| 64 | /** Call the schedule function */ |
| 65 | float operator ()(int batch_id, int num_batch) { |
| 66 | return schedule_function(batch_id, num_batch); |
| 67 | } |
| 68 | |
| 69 | /** Return information about the schedule */ |
| 70 | std::string info() const { |
| 71 | std::stringstream ss; |
| 72 | ss << "lr schedule: " << type; |
| 73 | return ss.str(); |
| 74 | } |
| 75 | |
| 76 | /** Linear decay schedule */ |
| 77 | static float linear_schedule(int batch_id, int num_batch) { |
| 78 | return std::max(1 - float(batch_id) / num_batch, 1e-4f); |
| 79 | } |
| 80 | |
| 81 | /** Constant schedule */ |
| 82 | static float constant_schedule(int batch_id, int num_batch) { |
| 83 | return 1; |
| 84 | } |
| 85 | }; |
| 86 | |
| 87 | /** |
| 88 | * @brief General interface of first-order optimizers |
nothing calls this directly
no outgoing calls
no test coverage detected