sdcpp-model-load.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. // The credential this node wants, named so it can be found. It is stored as a
  10. // plain basic credential - that is what decides how it is encrypted - and this
  11. // only says which basic credential is the SD.cpp one. Anything that accepts a
  12. // basic credential still accepts this, and this node still accepts a plain
  13. // basic credential, because the shape is identical.
  14. const credentialTypes = [
  15. {
  16. id: 'sdcpp',
  17. label: 'SD.cpp Server',
  18. baseType: 'basic',
  19. description: 'The username and password you sign in to sdcpp-restapi with. The node exchanges them for a token before every call',
  20. usernameLabel: 'Username',
  21. passwordLabel: 'Password'
  22. }
  23. ];
  24. const configSchema = {
  25. type: 'object',
  26. properties: {
  27. serverUrl: {
  28. type: 'string', title: 'Server URL',
  29. description: 'Base address of the sdcpp-restapi server',
  30. default: 'http://localhost:8077'
  31. },
  32. credentialId: {
  33. type: 'string', title: 'Credential',
  34. description: 'A basic credential holding the sdcpp-restapi username and password',
  35. dynamicOptions: { source: 'credentials', filter: { type: ['sdcpp', 'basic'] } }
  36. },
  37. modelName: {
  38. type: 'string', title: 'Model',
  39. description: 'File name of the model, relative to its type directory. Browse lists what the server has of the Model Type chosen below',
  40. dynamicOptions: {
  41. source: 'node',
  42. node: 'sdcpp-model',
  43. config: { listOnly: true },
  44. itemsPath: 'models',
  45. valueKey: 'name',
  46. labelKey: 'name',
  47. needs: ['serverUrl', 'credentialId']
  48. }
  49. },
  50. modelType: {
  51. type: 'string', title: 'Model Type',
  52. enum: ['', 'checkpoint', 'diffusion'],
  53. default: '',
  54. 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'
  55. },
  56. vae: {
  57. type: 'string', title: 'VAE',
  58. description: 'Component file name',
  59. dynamicOptions: {
  60. source: 'node',
  61. node: 'sdcpp-model',
  62. config: { listOnly: true, modelType: 'vae' },
  63. itemsPath: 'models',
  64. valueKey: 'name',
  65. labelKey: 'name',
  66. needs: ['serverUrl', 'credentialId']
  67. }
  68. },
  69. clipL: {
  70. type: 'string', title: 'CLIP-L',
  71. description: 'Component file name',
  72. dynamicOptions: {
  73. source: 'node',
  74. node: 'sdcpp-model',
  75. config: { listOnly: true, modelType: 'clip' },
  76. itemsPath: 'models',
  77. valueKey: 'name',
  78. labelKey: 'name',
  79. needs: ['serverUrl', 'credentialId']
  80. }
  81. },
  82. clipG: {
  83. type: 'string', title: 'CLIP-G',
  84. description: 'Component file name',
  85. dynamicOptions: {
  86. source: 'node',
  87. node: 'sdcpp-model',
  88. config: { listOnly: true, modelType: 'clip' },
  89. itemsPath: 'models',
  90. valueKey: 'name',
  91. labelKey: 'name',
  92. needs: ['serverUrl', 'credentialId']
  93. }
  94. },
  95. t5xxl: {
  96. type: 'string', title: 'T5-XXL',
  97. description: 'Component file name',
  98. dynamicOptions: {
  99. source: 'node',
  100. node: 'sdcpp-model',
  101. config: { listOnly: true, modelType: 't5' },
  102. itemsPath: 'models',
  103. valueKey: 'name',
  104. labelKey: 'name',
  105. needs: ['serverUrl', 'credentialId']
  106. }
  107. },
  108. llm: {
  109. type: 'string', title: 'LLM',
  110. description: 'Component file name, used by Z-Image, Qwen, Anima and Flux2',
  111. dynamicOptions: {
  112. source: 'node',
  113. node: 'sdcpp-model',
  114. config: { listOnly: true, modelType: 'llm' },
  115. itemsPath: 'models',
  116. valueKey: 'name',
  117. labelKey: 'name',
  118. needs: ['serverUrl', 'credentialId']
  119. }
  120. },
  121. taesd: {
  122. type: 'string', title: 'TAESD',
  123. description: 'Tiny autoencoder for progress previews',
  124. dynamicOptions: {
  125. source: 'node',
  126. node: 'sdcpp-model',
  127. config: { listOnly: true, modelType: 'taesd' },
  128. itemsPath: 'models',
  129. valueKey: 'name',
  130. labelKey: 'name',
  131. needs: ['serverUrl', 'credentialId']
  132. }
  133. },
  134. controlnet: {
  135. type: 'string', title: 'ControlNet',
  136. description: 'Component file name',
  137. dynamicOptions: {
  138. source: 'node',
  139. node: 'sdcpp-model',
  140. config: { listOnly: true, modelType: 'controlnet' },
  141. itemsPath: 'models',
  142. valueKey: 'name',
  143. labelKey: 'name',
  144. needs: ['serverUrl', 'credentialId']
  145. }
  146. },
  147. options: {
  148. type: 'object', title: 'Load Options',
  149. description: 'Extra load options passed through, such as flash_attn, enable_mmap, weight_type, stream_layers or max_vram'
  150. },
  151. whenDifferent: {
  152. type: 'string', title: 'When A Different Model Is Loaded',
  153. enum: ['load', 'fail'],
  154. default: 'load',
  155. 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'
  156. },
  157. force: {
  158. type: 'boolean', title: 'Force Reload',
  159. default: false,
  160. 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',
  161. showWhen: { field: 'whenDifferent', value: 'load' }
  162. },
  163. timeout: {
  164. type: 'number', title: 'Timeout (ms)',
  165. description: 'Loading reads gigabytes from disk and can take minutes',
  166. default: 300000
  167. }
  168. },
  169. required: []
  170. };
  171. const inputSchema = { type: 'object', properties: { data: { type: 'any' } } };
  172. const outputSchema = {
  173. type: 'object',
  174. properties: {
  175. modelName: { type: 'string', description: 'The model that is loaded now' },
  176. modelType: { type: 'string' },
  177. architecture: { type: 'string', description: 'Architecture the server detected, which decides generation defaults' },
  178. loaded: { type: 'boolean', description: 'True when this node performed a load' },
  179. alreadyLoaded: { type: 'boolean', description: 'True when the right model was already in place and nothing was done' },
  180. previousModel: { type: 'string', description: 'What was loaded before, when this node swapped it' },
  181. loadedComponents: { type: 'object' },
  182. elapsedMs: { type: 'number' }
  183. }
  184. };
  185. function normalizeServer(url) {
  186. const value = String(url || '').trim();
  187. if (!value) {
  188. throw new Error('SD.cpp: a server URL is required, such as http://localhost:8077');
  189. }
  190. return value.replace(/\/+$/, '');
  191. }
  192. function readCredential(credentialId) {
  193. const auth = smartbotic.credentials.get(credentialId);
  194. if (!auth || auth.success !== true) {
  195. throw new Error('SD.cpp: could not read the credential: ' +
  196. ((auth && auth.error) || 'unknown error'));
  197. }
  198. const value = auth.headerValue || '';
  199. if (value.indexOf('Basic ') !== 0) {
  200. throw new Error('SD.cpp: the credential must be a basic one, holding the sdcpp-restapi ' +
  201. 'username and password');
  202. }
  203. const decoded = smartbotic.utils.base64Decode(value.substring(6));
  204. const separator = decoded.indexOf(':');
  205. if (separator < 1) {
  206. throw new Error('SD.cpp: the credential is malformed, expected a username and a password');
  207. }
  208. return {
  209. username: decoded.substring(0, separator),
  210. password: decoded.substring(separator + 1)
  211. };
  212. }
  213. function call(options) {
  214. const response = smartbotic.http.request(options);
  215. let body = response.data;
  216. if (typeof body === 'string' && body.length > 0) {
  217. try {
  218. body = JSON.parse(body);
  219. } catch (e) {
  220. const snippet = body.substring(0, 200).replace(/\s+/g, ' ');
  221. throw new Error('SD.cpp: ' + options.what + ' returned HTTP ' + response.status +
  222. ' with a body that is not JSON: ' + snippet);
  223. }
  224. }
  225. if (response.status < 200 || response.status >= 300) {
  226. const detail = (body && (body.message || body.error)) || ('HTTP ' + response.status);
  227. throw new Error('SD.cpp: ' + options.what + ' failed: ' + detail);
  228. }
  229. return body || {};
  230. }
  231. function login(server, credential, timeout) {
  232. const session = call({
  233. method: 'POST',
  234. url: server + '/auth/login',
  235. headers: { 'Content-Type': 'application/json' },
  236. body: JSON.stringify({
  237. username: credential.username,
  238. password: credential.password
  239. }),
  240. timeout: timeout,
  241. what: 'signing in'
  242. });
  243. if (!session.token) {
  244. throw new Error('SD.cpp: the server accepted the login but returned no token');
  245. }
  246. return session.token;
  247. }
  248. // /health is unauthenticated, and it is the only way to find out what is
  249. // already loaded without asking for a token first.
  250. function readHealth(server, timeout) {
  251. return call({
  252. method: 'GET',
  253. url: server + '/health',
  254. timeout: timeout,
  255. what: 'reading server health'
  256. });
  257. }
  258. function putIfSet(target, key, value) {
  259. if (value === undefined || value === null || value === '') {
  260. return;
  261. }
  262. target[key] = value;
  263. }
  264. async function execute(config, input, context) {
  265. const server = normalizeServer(config.serverUrl);
  266. const timeout = config.timeout > 0 ? config.timeout : 300000;
  267. const modelName = String(config.modelName || '').trim();
  268. if (!modelName) {
  269. throw new Error('SD.cpp: a model name is required. Connect an SD.cpp Model node, ' +
  270. 'or type the file name');
  271. }
  272. // Ask what is loaded before loading anything. A load takes minutes and
  273. // unloads whatever was there, so doing it when the right model is already
  274. // resident is pure cost - and on a shared server it disrupts other work.
  275. const startedAt = Date.now();
  276. const health = readHealth(server, Math.min(timeout, 15000));
  277. const current = health.model_name || '';
  278. const sameModel = current === modelName;
  279. if (sameModel && config.force !== true) {
  280. smartbotic.log.info('SD.cpp: ' + modelName + ' is already loaded, nothing to do');
  281. return {
  282. modelName: current,
  283. modelType: health.model_type || '',
  284. architecture: health.model_architecture || '',
  285. loaded: false,
  286. alreadyLoaded: true,
  287. previousModel: '',
  288. loadedComponents: health.loaded_components || {},
  289. elapsedMs: Date.now() - startedAt
  290. };
  291. }
  292. if (!sameModel && (config.whenDifferent || 'load') === 'fail') {
  293. throw new Error('SD.cpp: this workflow expects "' + modelName + '" to be loaded, but ' +
  294. (current ? 'the server has "' + current + '"' : 'no model is loaded') +
  295. '. Set When A Different Model Is Loaded to "load" to swap it automatically');
  296. }
  297. const credential = readCredential(config.credentialId);
  298. const token = login(server, credential, Math.min(timeout, 30000));
  299. const body = { model_name: modelName };
  300. putIfSet(body, 'model_type', config.modelType);
  301. putIfSet(body, 'vae', config.vae);
  302. putIfSet(body, 'clip_l', config.clipL);
  303. putIfSet(body, 'clip_g', config.clipG);
  304. putIfSet(body, 't5xxl', config.t5xxl);
  305. putIfSet(body, 'llm', config.llm);
  306. putIfSet(body, 'taesd', config.taesd);
  307. putIfSet(body, 'controlnet', config.controlnet);
  308. if (config.options && typeof config.options === 'object') {
  309. body.options = config.options;
  310. }
  311. smartbotic.log.info('SD.cpp: loading ' + modelName +
  312. (current ? ' (replacing ' + current + ')' : ''));
  313. // Loading unloads whatever was in the slot first, and the server holds a
  314. // mutex for the duration, so this blocks until the weights are resident.
  315. const loaded = call({
  316. method: 'POST',
  317. url: server + '/models/load',
  318. headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + token },
  319. body: JSON.stringify(body),
  320. timeout: timeout,
  321. what: 'loading model ' + modelName
  322. });
  323. const after = readHealth(server, Math.min(timeout, 15000));
  324. return {
  325. modelName: loaded.model_name || modelName,
  326. modelType: loaded.model_type || config.modelType || '',
  327. architecture: after.model_architecture || '',
  328. loaded: true,
  329. alreadyLoaded: false,
  330. previousModel: sameModel ? '' : current,
  331. loadedComponents: loaded.loaded_components || after.loaded_components || {},
  332. elapsedMs: Date.now() - startedAt
  333. };
  334. }
  335. module.exports = { configSchema, inputSchema, outputSchema, execute };