sdcpp-model-load.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. /**
  2. * @node sdcpp-model-load
  3. * @name SD.cpp Load Model
  4. * @category sdcpp
  5. * @version 1.0.0
  6. * @description Make sure a model is loaded, without reloading one that already is
  7. * @icon box
  8. */
  9. const configSchema = {
  10. type: 'object',
  11. properties: {
  12. serverUrl: {
  13. type: 'string', title: 'Server URL',
  14. description: 'Base address of the sdcpp-restapi server',
  15. default: 'http://localhost:8077'
  16. },
  17. credentialId: {
  18. type: 'string', title: 'Credential',
  19. description: 'A basic credential holding the sdcpp-restapi username and password',
  20. dynamicOptions: { source: 'credentials', filter: { type: ['basic'] } }
  21. },
  22. modelName: {
  23. type: 'string', title: 'Model',
  24. description: 'File name of the model, relative to its type directory. Usually supplied by an SD.cpp Model node rather than typed here'
  25. },
  26. modelType: {
  27. type: 'string', title: 'Model Type',
  28. enum: ['', 'checkpoint', 'diffusion'],
  29. default: '',
  30. description: 'checkpoint bundles U-Net, CLIP and VAE and suits SD1, SD2 and SDXL. diffusion holds only the U-Net or DiT and needs its components named separately, which is how Flux, SD3, Qwen, Wan and Z-Image load'
  31. },
  32. vae: { type: 'string', title: 'VAE', description: 'Component file name' },
  33. clipL: { type: 'string', title: 'CLIP-L', description: 'Component file name' },
  34. clipG: { type: 'string', title: 'CLIP-G', description: 'Component file name' },
  35. t5xxl: { type: 'string', title: 'T5-XXL', description: 'Component file name' },
  36. llm: { type: 'string', title: 'LLM', description: 'Component file name, used by Z-Image, Qwen, Anima and Flux2' },
  37. taesd: { type: 'string', title: 'TAESD', description: 'Tiny autoencoder for progress previews' },
  38. controlnet: { type: 'string', title: 'ControlNet', description: 'Component file name' },
  39. options: {
  40. type: 'object', title: 'Load Options',
  41. description: 'Extra load options passed through, such as flash_attn, enable_mmap, weight_type, stream_layers or max_vram'
  42. },
  43. whenDifferent: {
  44. type: 'string', title: 'When A Different Model Is Loaded',
  45. enum: ['load', 'fail'],
  46. default: 'load',
  47. description: 'load swaps it. fail stops the run instead - for a workflow that depends on a particular model already being in place and should not quietly spend minutes swapping it'
  48. },
  49. force: {
  50. type: 'boolean', title: 'Force Reload',
  51. default: false,
  52. description: 'Load again even when the right model is already loaded. Costs the full load time; useful after changing components or options, which this node cannot see from outside',
  53. showWhen: { field: 'whenDifferent', value: 'load' }
  54. },
  55. timeout: {
  56. type: 'number', title: 'Timeout (ms)',
  57. description: 'Loading reads gigabytes from disk and can take minutes',
  58. default: 300000
  59. }
  60. },
  61. required: []
  62. };
  63. const inputSchema = { type: 'object', properties: { data: { type: 'any' } } };
  64. const outputSchema = {
  65. type: 'object',
  66. properties: {
  67. modelName: { type: 'string', description: 'The model that is loaded now' },
  68. modelType: { type: 'string' },
  69. architecture: { type: 'string', description: 'Architecture the server detected, which decides generation defaults' },
  70. loaded: { type: 'boolean', description: 'True when this node performed a load' },
  71. alreadyLoaded: { type: 'boolean', description: 'True when the right model was already in place and nothing was done' },
  72. previousModel: { type: 'string', description: 'What was loaded before, when this node swapped it' },
  73. loadedComponents: { type: 'object' },
  74. elapsedMs: { type: 'number' }
  75. }
  76. };
  77. function normalizeServer(url) {
  78. const value = String(url || '').trim();
  79. if (!value) {
  80. throw new Error('SD.cpp: a server URL is required, such as http://localhost:8077');
  81. }
  82. return value.replace(/\/+$/, '');
  83. }
  84. function readCredential(credentialId) {
  85. const auth = smartbotic.credentials.get(credentialId);
  86. if (!auth || auth.success !== true) {
  87. throw new Error('SD.cpp: could not read the credential: ' +
  88. ((auth && auth.error) || 'unknown error'));
  89. }
  90. const value = auth.headerValue || '';
  91. if (value.indexOf('Basic ') !== 0) {
  92. throw new Error('SD.cpp: the credential must be a basic one, holding the sdcpp-restapi ' +
  93. 'username and password');
  94. }
  95. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  96. const separator = decoded.indexOf(':');
  97. if (separator < 1) {
  98. throw new Error('SD.cpp: the credential is malformed, expected a username and a password');
  99. }
  100. return {
  101. username: decoded.substring(0, separator),
  102. password: decoded.substring(separator + 1)
  103. };
  104. }
  105. function call(options) {
  106. const response = smartbotic.http.request(options);
  107. let body = response.data;
  108. if (typeof body === 'string' && body.length > 0) {
  109. try {
  110. body = JSON.parse(body);
  111. } catch (e) {
  112. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  113. throw new Error('SD.cpp: ' + options.what + ' returned HTTP ' + response.status +
  114. ' with a body that is not JSON: ' + snippet);
  115. }
  116. }
  117. if (response.status < 200 || response.status >= 300) {
  118. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  119. throw new Error('SD.cpp: ' + options.what + ' failed: ' + detail);
  120. }
  121. return body || {};
  122. }
  123. function login(server, credential, timeout) {
  124. const session = call({
  125. method: 'POST',
  126. url: server + '/auth/login',
  127. headers: { 'Content-Type': 'application/json' },
  128. body: JSON.stringify({
  129. username: credential.username,
  130. password: credential.password
  131. }),
  132. timeout: timeout,
  133. what: 'signing in'
  134. });
  135. if (!session.token) {
  136. throw new Error('SD.cpp: the server accepted the login but returned no token');
  137. }
  138. return session.token;
  139. }
  140. // /health is unauthenticated, and it is the only way to find out what is
  141. // already loaded without asking for a token first.
  142. function readHealth(server, timeout) {
  143. return call({
  144. method: 'GET',
  145. url: server + '/health',
  146. timeout: timeout,
  147. what: 'reading server health'
  148. });
  149. }
  150. function putIfSet(target, key, value) {
  151. if (value === undefined || value === null || value === '') {
  152. return;
  153. }
  154. target[key] = value;
  155. }
  156. async function execute(config, input, context) {
  157. const server = normalizeServer(config.serverUrl);
  158. const timeout = config.timeout > 0 ? config.timeout : 300000;
  159. const modelName = String(config.modelName || '').trim();
  160. if (!modelName) {
  161. throw new Error('SD.cpp: a model name is required. Connect an SD.cpp Model node, ' +
  162. 'or type the file name');
  163. }
  164. // Ask what is loaded before loading anything. A load takes minutes and
  165. // unloads whatever was there, so doing it when the right model is already
  166. // resident is pure cost - and on a shared server it disrupts other work.
  167. const startedAt = Date.now();
  168. const health = readHealth(server, Math.min(timeout, 15000));
  169. const current = health.model_name || '';
  170. const sameModel = current === modelName;
  171. if (sameModel && config.force !== true) {
  172. smartbotic.log.info('SD.cpp: ' + modelName + ' is already loaded, nothing to do');
  173. return {
  174. modelName: current,
  175. modelType: health.model_type || '',
  176. architecture: health.model_architecture || '',
  177. loaded: false,
  178. alreadyLoaded: true,
  179. previousModel: '',
  180. loadedComponents: health.loaded_components || {},
  181. elapsedMs: Date.now() - startedAt
  182. };
  183. }
  184. if (!sameModel && (config.whenDifferent || 'load') === 'fail') {
  185. throw new Error('SD.cpp: this workflow expects "' + modelName + '" to be loaded, but ' +
  186. (current ? 'the server has "' + current + '"' : 'no model is loaded') +
  187. '. Set When A Different Model Is Loaded to "load" to swap it automatically');
  188. }
  189. const credential = readCredential(config.credentialId);
  190. const token = login(server, credential, Math.min(timeout, 30000));
  191. const body = { model_name: modelName };
  192. putIfSet(body, 'model_type', config.modelType);
  193. putIfSet(body, 'vae', config.vae);
  194. putIfSet(body, 'clip_l', config.clipL);
  195. putIfSet(body, 'clip_g', config.clipG);
  196. putIfSet(body, 't5xxl', config.t5xxl);
  197. putIfSet(body, 'llm', config.llm);
  198. putIfSet(body, 'taesd', config.taesd);
  199. putIfSet(body, 'controlnet', config.controlnet);
  200. if (config.options && typeof config.options === 'object') {
  201. body.options = config.options;
  202. }
  203. smartbotic.log.info('SD.cpp: loading ' + modelName +
  204. (current ? ' (replacing ' + current + ')' : ''));
  205. // Loading unloads whatever was in the slot first, and the server holds a
  206. // mutex for the duration, so this blocks until the weights are resident.
  207. const loaded = call({
  208. method: 'POST',
  209. url: server + '/models/load',
  210. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
  211. body: JSON.stringify(body),
  212. timeout: timeout,
  213. what: 'loading model ' + modelName
  214. });
  215. const after = readHealth(server, Math.min(timeout, 15000));
  216. return {
  217. modelName: loaded.model_name || modelName,
  218. modelType: loaded.model_type || config.modelType || '',
  219. architecture: after.model_architecture || '',
  220. loaded: true,
  221. alreadyLoaded: false,
  222. previousModel: sameModel ? '' : current,
  223. loadedComponents: loaded.loaded_components || after.loaded_components || {},
  224. elapsedMs: Date.now() - startedAt
  225. };
  226. }
  227. module.exports = { configSchema, inputSchema, outputSchema, execute };