微信扫码
与创始人交个朋友
我要投稿
点击上方↗️「活水智能」,关注 + 星标?
作者:Ozgur Guler
编译:活水智能
GraphRAG 为大语言模型(LLMs)提供了“推理支架”,通过结构化的知识图谱(KG)支持其推理过程。试想一下,追踪“因果路径”——从发达经济体的财政紧缩到新兴市场的通货膨胀。借助 GraphRAG,可以减少生成幻觉内容(hallucination),并获得意想不到的洞见。但能否更进一步?通过将图注意网络(GATs)集成到 GraphRAG 中,我们可以动态地将上下文与每个查询对齐,从而释放前所未有的推理能力。
(本文将使用 IMF 2024 年 10 月的《世界经济展望》报告作为因果推理的示例。)
基线 RAG 在推理任务中表现不佳,因为它主要依赖语义相似性。推断因果关系(通常未明确编码在非结构化文档中)尤其具有挑战性。对于缺乏高级模型精度的小型语言模型,这一问题尤为突出。
GraphRAG 通过利用知识图谱(KG)中的结构化关系克服了这些局限性。关键实体(如“发达经济体”、“财政紧缩”和“新兴市场”)被表示为节点,节点之间通过边连接,映射出因果链。例如:
• 路径 A:“财政紧缩” → “资本流入减少” → “货币贬值” → “新兴市场通胀”
• 路径 B:“财政紧缩” → “商品价格调整” → “能源价格” → “贸易失衡” → “新兴市场通胀影响”
通过 Leiden 等算法,GraphRAG 根据关系强度将节点聚类为社区,分组相关概念(如财政政策和通胀)。这种聚类通过减少噪声和增强上下文相关性来改善检索,从而使 LLM 能生成准确、扎实的响应。
然而,基线 GraphRAG 的静态聚类存在局限性。固定的社区可能无法很好地适应跨多个主题的查询,例如财政紧缩和全球贸易中断对通胀的综合影响。这种刚性可能导致:
• 相关上下文检索效率低下;
• 难以捕获远程关系;
• 遗漏关键连接或信息过载。
将 GATs 集成到 GraphRAG 中,增强了其对节点和边相关性的权重计算能力,从而实现上下文敏感的推理。与传统 GraphRAG 的静态聚类不同,GAT 能根据查询动态调整,通过为节点和边分配注意力分数来反映其与查询的相关性。这使 GraphRAG 能够实时优化上下文,使检索更精准,洞见更贴合查询意图。
在 GAT 中:
1. 节点嵌入:每个节点以其特征向量开始。
2. 注意力分数:在每一层,节点从其邻居处聚合信息,权重由注意力分数决定(通过相似度计算,例如点积)。
3. 多跳扩展:该过程在每一层重复,扩展节点的上下文以包含越来越远的邻居(例如,1 跳、2 跳、3 跳连接)。
4. 最终嵌入:在最后一层,每个节点的嵌入捕获了其自身特征和相关邻居的聚合影响,形成了图知识的整体表示。
为什么这很重要?
GAT 增强的嵌入充当 LLM 的“精炼镜头”,将推理聚焦于图中最相关的部分。这些嵌入作为结构化输入提供给 LLM,将图的知识与查询对齐。这种动态协同使 GraphRAG 能够:
• 处理复杂的多跳查询;
• 提升准确性和上下文深度;
• 提供更丰富、更贴合查询的洞见。
PyG 是一个开源的几何深度学习和基于图神经网络(GNN)的库,在其 2.6 版本中引入了 G-Retriever。G-Retriever 仅需几行代码即可将 PyG GNN 与 HuggingFace 的 LLM 无缝整合。基于论文 “G-Retriever: Retrieval-Augmented Generation for Textual Graph Understanding and Question Answering”,该工具可实现复杂文本推理任务的高级图检索。
gnn = GAT(
in_channels=768,
hidden_channels=1024,
out_channels=768,
num_layers=4,
heads=8
).to(device)
llm = LLM(model_name='meta-llama/Llama-2-7b-chat-hf', num_params=7).to(device)
g_retriever = GRetriever(llm=llm, gnn=gnn, mlp_out_channels=4096)
G-Retriever 通过结合 GNN 和 LLM 的优势来实现 RAG。在推理时,它通过以下四步处理查询:
1. LLM 编码:将自然语言查询分词并使用 LLM 编码器编码为嵌入。
2. 子图检索:检索 KG 的相关子图,并使用 GNN 编码器对其节点和边进行编码。
3. 嵌入融合:将 GNN 嵌入(表示 KG 上下文)与 LLM 嵌入(表示查询)连接以形成联合表示。
4. LLM 解码:将联合嵌入传递给 LLM 解码器,根据丰富的上下文生成自然语言响应。
此工作流确保 G-Retriever 能通过动态整合基于图的推理与 LLM 的上下文理解来处理复杂查询,从而生成更准确、更扎实的响应。
我已分别在三个笔记本中实现了基线 GraphRAG 的全局查询、使用 GAT 的 G-Retriever 和不使用 GAT 的 G-Retriever,并在附录中引用了这些笔记本。然后我们将使用 gpt-4o 来评估响应。示例简化知识图谱来自 IMF 2024 年 10 月的《世界经济展望》报告。(G-Retriever 已在 llama2–7b-chat-hf 和 gemma-7b 上测试,因此在此示例中使用 llama2–7b-chat-hf。)
以下是结果……
EVALUATION
We will evaluate the answers using gpt-4o.
Example1:
Query: "Evaluate the potential long-term economic and environmental impacts of shifting from fossil fuel consumption to renewable energy adoption, considering factors such as job creation, technological innovation, energy policy, and public health. Additionally, discuss how this transition affects international agreements and climate change policies, and identify potential challenges in infrastructure investment and sustainable agriculture."
Answer with vanilla GraphRAG: "['Shifting from fossil fuel consumption to renewable energy adoption has the potential to bring about significant long-term economic and environmental benefits, while also addressing climate change. Here are some of the key factors to consider: Addressing the impacts of climate change, such as increased frequency and severity of natural disasters, can help to reduce the risk of disasters and improve disaster risk management. In conclusion, shifting from fossil fuel consumption to renewable energy adoption has the potential to bring about significant long-term economic and environmental benefits, while also addressing climate change. However, there are also challenges to be addressed, including infrastructure investment and sustainable agriculture. By prioritizing renewable energy adoption and addressing these challenges, we can create a more sustainable and resilient future for all.']
Answer with G-Retriever GNN: "[' Shifting from fossil fuel consumption to renewable energy adoption has the potential to bring about significant long-term economic and environmental benefits. Here are some of the key factors to consider:\n\n1. Job Creation: The transition to renewable energy can create new job opportunities in industries such as solar panel installation, wind turbine maintenance, and energy efficiency consulting. According to the International Renewable Energy Agency (IRENA), the renewable energy sector could support up to 46 million jobs worldwide by 2050, up from around 11 million today.\n2. Technological Innovation: The shift to renewable energy can drive innovation in areas such as energy storage, grid management, and smart grids. This can lead to new technologies and products that can be exported globally, creating new economic opportunities.\n3. Energy Policy: The transition to renewable energy can lead to more flexible and decentralized energy systems, with greater emphasis on local generation and distribution. This can lead to more efficient and resilient energy systems, with reduced transmission losses and increased energy security.\n4. Public Health: The transition to renewable energy can lead to significant improvements in public health, particularly in urban areas. Air pollution from fossil fuels is a major contributor to respiratory diseases and other health problems, and the use of renewable energy can help to reduce these impacts.\n\nIn terms of international agreements and climate change policies, the transition to renewable energy is critical for meeting global climate targets. The Paris Agreement, signed by nearly 200 countries in 2015, sets a goal of limiting global warming to well below 2 degrees Celsius (and pursuing efforts to limit it to 1.5 degrees) above pre-industrial levels. Renewable energy is a key component of this effort, as it can help to reduce greenhouse gas emissions while providing energy security and economic benefits.\n\nHowever, there are also potential challenges to consider in the transition to renewable energy, including:\n\n1. Infrastructure Investment: The transition to renewable energy will require significant investment in new infrastructure, including wind farms, solar panels, and energy storage facilities. This can be a challenge, particularly in developing countries where there may be limited financial resources and existing infrastructure.\n2. Sustainable Agriculture: The transition to renewable energy may also have impacts on sustainable agriculture, particularly in areas where land is used for biofuel production. This can lead to competition for land and water resources, and may impact food security and rural livelihoods.\n3. Energy Storage: The transition to renewable energy will also require the development of energy storage technologies, such as batteries and hydrogen fuel cells, to ensure a reliable and stable energy supply. This can be a challenge, particularly in areas where there may be limited infrastructure and resources.\n4. Grid Integration: The integration of renewable energy into the grid can also be a challenge, particularly in areas where there may be limited grid capacity and infrastructure. This can lead to issues with energy transmission and distribution, and may impact the reliability and stability of the energy supply.\n\nOverall, the transition to renewable energy has the potential to bring about significant long-term economic and environmental benefits, but it will require careful planning, investment, and coordination to ensure a successful transition.']
Answer with G-Retriever without GNN: "[' Shifting from fossil fuel consumption to renewable energy adoption has the potential to have significant long-term economic and environmental impacts. Here are some of the factors to consider:\n\n1. Job Creation: The transition to renewable energy can create new job opportunities in industries such as solar panel installation, wind turbine maintenance, and energy efficiency. According to the International Renewable Energy Agency (IRENA), the renewable energy sector could support up to 24 million jobs worldwide by 2050.\n2. Technological Innovation: The shift to renewable energy can drive technological innovation, particularly in areas such as energy storage, grid management, and smart grids. This can lead to new products and services, and improved energy efficiency.\n3. Energy Policy: The transition to renewable energy can lead to changes in energy policy, such as incentives for renewable energy production, carbon pricing, and energy efficiency standards. These policies can help to level the playing field for renewable energy and create a more sustainable energy system.\n4. Public Health: The transition to renewable energy can lead to improved air quality and reduced greenhouse gas emissions, which can have significant public health benefits. For example, the World Health Organization (WHO) estimates that air pollution from fossil fuels causes around 7 million premature deaths worldwide each year.\n5. International Agreements and Climate Change Policies: The transition to renewable energy can help countries meet their commitments under international agreements such as the Paris Agreement, which aims to limit global warming to well below 2°C above pre-industrial levels. The transition can also help to reduce greenhouse gas emissions and mitigate the impacts of climate change.\n\nHowever, there are also potential challenges to consider:\n\n1. Infrastructure Investment: The transition to renewable energy may require significant investment in infrastructure, such as new power transmission lines, energy storage facilities, and distributed energy systems. This can be a challenge in areas with limited resources or in countries with less developed energy infrastructure.\n2. Sustainable Agriculture: The transition to renewable energy may also have implications for sustainable agriculture, particularly in areas where land is used for biofuel production. This can lead to competition for land use and potential impacts on food security.\n3. Energy Security: The transition to renewable energy may also raise concerns about energy security, particularly in countries with limited renewable energy resources. This can lead to dependence on imported energy sources and potential vulnerability to price volatility.\n4. Economic Disruption: The transition to renewable energy can also lead to economic disruption in industries such as fossil fuel production and transportation. This can lead to job losses and economic instability in communities reliant on these industries.\n5. Social Acceptance: Finally, the transition to renewable energy may also be influenced by social acceptance, particularly in areas with limited public support for renewable energy. This can lead to delays or challenges in implementing renewable energy projects.\n\nIn conclusion, the transition to renewable energy has the potential to have significant long-term economic and environmental impacts. While there are challenges to consider, the benefits of this transition far outweigh the costs, particularly in terms of improved public health, job creation, and reduced greenhouse gas emissions. With careful planning and policy support, the transition to renewable energy can be a successful and sustainable path forward.']"
| Metric |GraphRAG GlobalQuery | G-ret with GNN | G-ret wo GNN |
|-------------------|-----------------------------------------------------------------|
| Groundedness | 4 | 8 | 7 |
| Correctness | 6 | 9 | 8 |
| Coherence | 5 | 9 | 8 |
| Novelty | 3 | 8 | 7 |
| Relevance | 6 | 9 | 8 |
| Overall Score. | 4.8 | 8.6 | 7.6. |
Example2:
Query: "What are the economic and environmental implications of renewable energy adoption, considering the roles of job creation, technological innovation, and deforestation mitigation?"
Answer with vanilla GraphRAG:["Renewable energy adoption has significant economic and environmental implications, including job creation, technological innovation, and deforestation mitigation. Economic Implications: Job Creation: Renewable energy adoption can create new job opportunities in industries such as solar panel installation, wind turbine maintenance, and biofuels production. According to the International Renewable Energy Agency (IRENA), the renewable energy sector could support up to 46 million jobs globally by 2050, up from 11 million in 2020. Technological Innovation: The transition to renewable energy sources requires significant technological advancements, leading to innovations in fields such as energy storage, grid management, and smart grids. This can drive economic growth by creating new industries and opportunities for investment. Infrastructure Investment: The deployment of renewable energy infrastructure, such as wind farms and solar parks, requires significant investment in infrastructure. This can lead to job creation, economic growth, and improved energy security. Environmental Implications: Deforestation Mitigation: Renewable energy adoption can help mitigate deforestation by reducing the demand for fossil fuels, which are often linked to deforestation in developing countries. According to the World Wildlife Fund, the use of renewable energy can help reduce deforestation by up to 70 Carbon Emissions Reduction: The transition to renewable energy sources can significantly reduce carbon emissions, which contribute to climate change. According to the Intergovernmental Panel on Climate Change (IPCC), the use of renewable energy can reduce carbon emissions by up to 70% by 2050. Air Pollution Reduction: Renewable energy adoption can also reduce air pollution, as renewable energy sources emit significantly less air pollutants than fossil fuels. Public Health Improvement: The reduction of air pollution and carbon emissions through renewable energy adoption can lead to improved public health outcomes, as reduced air pollution can reduce the incidence of respiratory diseases and other health problems. Energy Security: The adoption of renewable energy sources can improve energy security by reducing dependence on imported fossil fuels, which can be subject to price volatility and geopolitical risks. In conclusion, renewable energy adoption has significant economic and environmental implications, including job creation, technological innovation, deforestation mitigation, carbon emissions reduction, air pollution reduction, public health improvement, and energy security. The transition to renewable energy sources is essential to mitigate the impacts of climate change and ensure a sustainable future for generations to come."]
Answer with GNN: [" Renewable energy adoption has significant economic and environmental implications, including job creation, technological innovation, and deforestation mitigation. Here are some of the key implications:\n\nEconomic Implications:\n\n1. Job Creation: The renewable energy sector is creating new job opportunities in areas such as solar panel installation, wind turbine maintenance, and energy efficiency consulting. According to the International Renewable Energy Agency (IRENA), the renewable energy sector could support up to 46 million jobs globally by 2050, up from 11 million in 2019.\n2. Investment Opportunities: Investing in renewable energy can provide attractive financial returns, as well as contribute to sustainable economic growth. According to Bloomberg New Energy Finance, the global investment in renewable energy reached $2.6 trillion in 2020, up from $1.1 trillion in 2010.\n3. Economic Efficiency: Renewable energy can reduce energy costs for consumers and businesses, as the fuel costs for renewable energy sources are generally lower than for fossil fuels. According to the National Renewable Energy Laboratory (NREL), the cost of wind energy has decreased by 69% since 2009, making it more competitive with fossil fuels.\n\nEnvironmental Implications:\n\n1. Reduced Greenhouse Gas Emissions: Renewable energy sources such as solar, wind, and hydroelectric power produce little to no greenhouse gas emissions, which contribute to climate change. According to the Intergovernmental Panel on Climate Change (IPCC), renewable energy can help reduce greenhouse gas emissions by up to 70% by 2050, compared to 2010 levels.\n2. Deforestation Mitigation: Renewable energy can help mitigate deforestation by reducing the demand for land for energy production. According to the World Wildlife Fund (WWF), the use of renewable energy can help reduce the global demand for land by up to 30%, which can help protect forests and biodiversity.\n3. Resource Conservation: Renewable energy can help conserve non-renewable resources, such as fossil fuels, by reducing the demand for these resources. According to the U.S. Department of Energy, the use of renewable energy can help reduce the United States' dependence on fossil fuels by up to 50% by 2050.\n\nTechnological Innovation:\n\n1. Increased Efficiency: The development of new technologies, such as advanced solar panels and wind turbines, has increased the efficiency of renewable energy production. According to the NREL, the efficiency of solar panels has increased by 40% since 2000, while the efficiency of wind turbines has increased by 10% since 2000.\n2. Decentralization: The development of decentralized renewable energy systems, such as rooftop solar and community wind, can increase the resilience of energy systems and reduce the risk of power outages. According to the International Energy Agency (IEA), decentralized renewable energy systems can provide up to 20% of global electricity demand by 2050.\n3. Energy Storage: The development of energy storage technologies, such as batteries and hydrogen fuel cells, can improve the reliability of renewable energy systems and reduce the need for fossil fuels. According to the IEA, energy storage can provide up to 10% of global electricity demand by 2050.\n\nIn conclusion, the adoption of renewable energy has significant economic and environmental implications, including job creation, technological innovation, and deforestation mitigation. As the world transitions to a low-carbon economy, the adoption of renewable energy sources will play a critical role in reducing greenhouse gas emissions, conserving non-renewable resources, and promoting sustainable economic growth."]
Answer without GNN: [" Renewable energy adoption has significant economic and environmental implications, both positive and negative, across various sectors. Here are some key considerations:\n\n1. Job creation:\n\t* Renewable energy can create new job opportunities in industries such as solar panel installation, wind turbine maintenance, and energy efficiency consulting. According to the International Renewable Energy Agency (IRENA), the renewable energy sector could support up to 46 million jobs globally by 2050, compared to 11 million jobs in the fossil fuel sector.\n\t* However, the transition to renewable energy may also lead to job losses in traditional fossil fuel industries, such as coal mining and oil drilling.\n2. Technological innovation:\n\t* The development and deployment of renewable energy technologies, such as advanced solar panels and wind turbines, can drive innovation and economic growth.\n\t* Investing in renewable energy can also foster research and development in other sectors, such as energy storage and grid management.\n3. Deforestation mitigation:\n\t* Renewable energy can help reduce deforestation by reducing the demand for fossil fuels, which are often linked to deforestation in tropical regions.\n\t* Large-scale renewable energy projects, such as hydroelectric dams and bioenergy plantations, can also contribute to deforestation, so it's essential to ensure that these projects are designed and implemented sustainably.\n4. Environmental impact:\n\t* Renewable energy sources, such as solar and wind, have a significantly lower environmental impact than fossil fuels, as they produce little to no greenhouse gas emissions during operation.\n\t* However, the production of renewable energy technologies, such as solar panels and wind turbines, can have environmental impacts, such as land use changes and material depletion.\n5. Economic benefits:\n\t* Renewable energy can provide economic benefits by reducing energy costs, improving energy security, and creating new job opportunities.\n\t* According to the National Renewable Energy Laboratory (NREL), the cost of wind and solar energy has decreased significantly over the past decade, making them more competitive with fossil fuels.\n6. Economic challenges:\n\t* The transition to renewable energy can be costly, particularly for developing countries or regions with limited financial resources.\n\t* The intermittency of renewable energy sources, such as solar and wind, can create challenges for grid management and energy storage, which can be expensive to address.\n7. Policy and regulation:\n\t* Effective policy and regulation can help drive the transition to renewable energy by providing incentives for investment, promoting research and development, and ensuring a level playing field for renewable energy technologies.\n\t* Governments can also play a role in addressing the economic challenges associated with renewable energy adoption by providing financial support, such as tax credits or feed-in tariffs, to encourage investment.\n8. Grid integration:\n\t* The integration of renewable energy sources into the grid can be challenging, particularly when these sources are intermittent.\n\t* Advanced grid management systems and energy storage technologies can help address these challenges, but their deployment can be expensive.\n9. Energy storage:\n\t* Energy storage technologies, such as batteries and hydrogen fuel cells, can help address the intermittency of renewable energy sources by storing excess energy for use when it's needed.\n\t* The cost of energy storage technologies is expected to decrease over time, making them more competitive with traditional energy storage solutions.\n10. International cooperation:\n\t* Renewable energy adoption can have significant implications for international trade and cooperation, particularly in the context of global climate change.\n\t* Collaboration between countries can help share knowledge, technologies, and best practices, accelerating the transition to renewable energy.\n\nIn conclusion, the economic and environmental implications of renewable energy adoption are complex and multifaceted. While there are significant challenges to be addressed, the transition to renewable energy can provide numerous benefits, including job creation, technological innovation, and deforestation mitigation. Effective policy and regulation, along with international cooperation, can help drive this transition and ensure a sustainable energy future."]
| Metric |GraphRAG GlobalQuery | G-ret with GNN | G-ret wo GNN |
|-------------------|-----------------------------------------------------------------|
| Groundedness | 7 | 9 | 8 |
| Correctness | 8 | 9 | 8 |
| Coherence | 7 | 9 | 8 |
| Novelty | 6 | 9 | 8 |
| Relevance | 7 | 9 | 8 |
| Overall Score. | 7 | 9 | 8 |
Example3:
Query: ["How does infrastructure investment in renewable energy correlate with disaster risk management, water scarcity solutions, and public health improvements?"
Answer with vanilla GraphRAG: ["Answer: Investment in renewable energy can positively correlate with disaster risk management, water scarcity solutions, and public health improvements in several ways:1. Reduced Carbon Emissions: Transitioning to renewable energy sources reduces the amount of carbon dioxide emitted into the atmosphere, which is a major contributor to climate change. Climate change exacerbates the frequency and severity of natural disasters, such as hurricanes, wildfires, and floods. By reducing carbon emissions, investment in renewable energy can help mitigate the impact of disasters 2. Improved Energy Efficiency: Renewable energy sources are generally more energy-efficient than fossil fuels. By investing in renewable energy, energy consumption can be reduced, leading to cost savings and a reduction in energy waste. This can also contribute to disaster risk management by reducing the strain on energy infrastructure during natural disasters. 3. Enhanced Resilience: Investing in renewable energy can enhance the resilience of energy systems, making them better equipped to withstand the impacts of natural disasters. For example, solar and wind power can continue to operate even during power outages caused by storms or floods. 4. Water Conservation: Renewable energy sources often require less water than traditional fossil fuel-based power plants. This can help conserve water resources, which are essential for addressing water scarcity issues. 5. Job Creation: The transition to renewable energy can create new job opportunities in industries such as solar panel installation, wind turbine maintenance, and energy efficiency consulting. This can help reduce unemployment and improve economic growth. 6. Public Health Improvements: Investing in renewable energy can lead to improved air quality, as renewable energy sources produce little to no air pollution. This can improve public health outcomes by reducing the number of respiratory illnesses and other health problems associated with air pollution. 7. Reduced Water Pollution: Renewable energy sources can help reduce water pollution by minimizing the amount of wastewater generated during energy production. 8. Climate Change Mitigation: Investing in renewable energy can help mitigate the impacts of climate change by reducing greenhouse gas emissions. This can help reduce the risk of climate-related disasters, such as sea level rise, droughts, and heatwaves. 9. International Cooperation: Investing in renewable energy can promote international cooperation on climate change issues. This can help facilitate the sharing of knowledge, technologies, and best practices for addressing climate change and its associated impacts. 10. Economic Growth: Investing in renewable energy can promote economic growth by creating new job opportunities and attracting investment in the renewable energy sector. This can help stimulate local economies and promote sustainable development. In conclusion, investing in renewable energy can positively correlate with disaster risk management, water scarcity solutions, and public health improvements by reducing carbon emissions, improving energy efficiency, enhancing resilience, conserving water resources, creating job opportunities, improving air quality, reducing water pollution, promoting international cooperation, and stimulating economic growth."]
Answer with GNN: ["Renewable energy adoption has several economic and environmental implications, including job creation, technological innovation, and deforestation mitigation. Here are some of the key implications:\n\nEconomic Implications:\n\n1. Job Creation: Renewable energy adoption can create new job opportunities in industries such as solar panel installation, wind turbine maintenance, and biofuel production. According to the International Renewable Energy Agency (IRENA), the renewable energy sector could support up to 46 million jobs globally by 2050.\n2. Investment Opportunities: Investing in renewable energy can create new investment opportunities, particularly in emerging markets. As renewable energy technologies become more cost-competitive with fossil fuels, there is potential for increased investment in renewable energy infrastructure.\n3. Economic Growth: Renewable energy can contribute to economic growth by reducing the dependence on fossil fuels and promoting energy security. According to the United Nations, renewable energy can generate up to 11% of global GDP by 2050.\n\nEnvironmental Implications:\n\n1. Reduced Greenhouse Gas Emissions: Renewable energy sources such as solar and wind power produce little to no greenhouse gas emissions during operation, which can help mitigate climate change. According to the Intergovernmental Panel on Climate Change (IPCC), renewable energy can reduce greenhouse gas emissions by up to 70% by 2050.\n2. Deforestation Mitigation: The use of renewable energy can help mitigate deforestation by reducing the demand for fossil fuels, which are often linked to deforestation practices. According to the World Wildlife Fund, the adoption of renewable energy can help reduce deforestation by up to 50% by 2050.\n3. Resource Conservation: Renewable energy sources can help conserve natural resources such as water and land, as they require less land and water than traditional energy sources.\n\nTechnological Innovation:\n\n1. Research and Development: The transition to renewable energy requires significant research and development to improve the efficiency and affordability of renewable energy technologies. This can lead to new technological innovations and advancements in fields such as energy storage, grid management, and materials science.\n2. Increased Efficiency: As renewable energy technologies become more widespread, their efficiency is likely to increase, leading to greater energy output from the same amount of resources.\n3. Decentralization of Energy Production: Renewable energy can decentralize energy production, allowing for greater control over energy production and distribution, and reducing the need for centralized power plants.\n\nIn conclusion, the adoption of renewable energy can have significant economic and environmental implications, including job creation, technological innovation, and deforestation mitigation. As the world transitions to a more renewable energy-based economy, it is important to consider these implications and work towards a sustainable and equitable future.']
Answer without GNN:["Investing in renewable energy infrastructure can have a positive correlation with disaster risk management, water scarcity solutions, and public health improvements in several ways:\n\n1. Reduced reliance on fossil fuels: Renewable energy sources, such as solar and wind power, can reduce the reliance on fossil fuels, which are a major contributor to greenhouse gas emissions. This can help mitigate the impact of natural disasters, such as hurricanes and wildfires, which are becoming more frequent and severe due to climate change.\n2. Resilience and adaptation: Renewable energy infrastructure can provide a more resilient and adaptable energy system, particularly in areas prone to natural disasters. For example, solar panels and wind turbines can continue to operate during power outages caused by hurricanes or wildfires, providing critical energy to emergency responders and affected communities.\n3. Water conservation: Renewable energy can also contribute to water conservation by reducing the amount of water used in traditional fossil fuel-based power generation. For example, solar panels and wind turbines require very little water for operation, compared to traditional power plants that use significant amounts of water for cooling.\n4. Improved air quality: Renewable energy can also improve air quality by reducing the amount of air pollutants emitted by fossil fuel-based power generation. This can have positive impacts on public health, particularly in areas with high levels of air pollution.\n5. Job creation and economic growth: Investing in renewable energy infrastructure can create jobs and stimulate economic growth, particularly in rural areas where wind and solar farms are often located. This can help to reduce poverty and improve economic opportunities in disaster-prone areas.\n6. Disaster risk reduction: Renewable energy infrastructure can also help to reduce the risk of disasters by providing reliable and sustainable energy sources. For example, renewable energy can help to power critical infrastructure, such as hospitals and emergency shelters, during natural disasters.\n7. Climate change mitigation: Investing in renewable energy can help to mitigate the impacts of climate change by reducing the amount of greenhouse gas emissions from fossil fuel-based power generation. This can help to reduce the risk of more frequent and severe natural disasters, such as hurricanes, floods, and wildfires.\n8. Water scarcity solutions: Renewable energy can also help to address water scarcity issues by reducing the amount of water used in traditional power generation. For example, solar panels and wind turbines can provide energy for water treatment and desalination plants, helping to make water more accessible and sustainable in areas with limited water resources.\n9. Public health improvements: Investing in renewable energy can also improve public health by reducing the amount of air pollutants emitted by fossil fuel-based power generation. This can have positive impacts on respiratory health, cardiovascular health, and overall well-being.\n10. Energy independence: Renewable energy can also provide energy independence by reducing reliance on imported fossil fuels. This can help to improve energy security and reduce the risk of disruptions to energy supply during natural disasters.\n\nIn summary, investing in renewable energy infrastructure can have numerous benefits for disaster risk management, water scarcity solutions, and public health improvements. By reducing greenhouse gas emissions, improving air quality, and providing reliable and sustainable energy sources, renewable energy can help to mitigate the impacts of natural disasters and improve the resilience of communities.']
| Metric |GraphRAG GlobalQuery | G-ret with GNN | G-ret wo GNN |
|-------------------|-----------------------------------------------------------------|
| Groundedness | 7 | 9 | 8 |
| Correctness | 8 | 9 | 8 |
| Coherence | 7 | 9 | 8 |
| Novelty | 6 | 9 | 8 |
| Relevance | 7 | 9 | 8 |
| Overall Score. | 7 | 9. | 8 |
评估显示,带有 GAT 的 G-Retriever 在扎实性、逻辑正确性、一致性、新颖性和相关性方面始终优于基线 GraphRAG 和不带 GAT 的检索方法。基线 GraphRAG 通常提供一般性洞见,但缺乏深度和具体性,导致得分较低。不带 GAT 的检索方法提供了一种平衡的方法,但在提供综合数据和创新视角方面不及 GAT 增强的答案。GAT 的响应因其丰富的引用、细致入微的解释以及经济和环境因素的无缝整合而脱颖而出,是样本集中最可靠和最具洞察力的。
GNN 是图的理想编码器。图注意显著增强了基线 GraphRAG 的能力,尤其是在需要深度图遍历和细致推理的复杂因果查询中,通过以极低的计算成本提炼图中编码的信息。G-Retriever 在需要精确、结构化知识的领域(如科学、法律、医疗)中表现突出,并且在需要多跳推理和上下文权重的复杂查询中表现卓越。
#Microsoft GraphRAG with Global Search as described in https://microsoft.github.io/graphrag/examples_notebooks/global_search/
# Copyright (c) 2024 Microsoft Corporation.
# Licensed under the MIT License.
import os
import torch
import pandas as pd
import networkx as nx
from sentence_transformers import SentenceTransformer
from transformers import AutoTokenizer, AutoModelForCausalLM
from networkx.algorithms.community import asyn_lpa_communities
# Device setup
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Hugging Face LLM wrapper
class LLM:
def __init__(self, model_name, num_params):
self.model_name = model_name
self.num_params = num_params
self.tokenizer = AutoTokenizer.from_pretrained(model_name)
self.model = AutoModelForCausalLM.from_pretrained(model_name).to(device)
def generate(self, prompt, max_length=512, temperature=0.7):
inputs = self.tokenizer(prompt, return_tensors="pt", truncation=True).to(device)
outputs = self.model.generate(
inputs.input_ids,
max_length=max_length,
temperature=temperature,
pad_token_id=self.tokenizer.eos_token_id,
)
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
# Initialize the LLM
llm = LLM(model_name="meta-llama/Llama-2-7b-chat-hf", num_params=7)
# Embedding model
embedding_model = SentenceTransformer('all-MPNet-base-v2')
# Expanded node descriptions
node_descriptions = [
"Climate Change Policies: Policies aimed at reducing greenhouse gas emissions and mitigating climate change effects.",
"Renewable Energy Adoption: Transition to renewable energy sources like solar, wind, and hydroelectric power.",
"Fossil Fuel Consumption: Use of fossil fuels such as coal, oil, and natural gas for energy.",
"Electric Vehicles: Vehicles powered by electric motors using energy stored in rechargeable batteries.",
"Carbon Emissions: Release of carbon dioxide into the atmosphere from various sources.",
"Air Pollution: Contamination of air by harmful substances including gases and particulates.",
"Public Health: Health outcomes of populations influenced by environmental and social factors.",
"Economic Growth: Increase in the market value of goods and services produced by an economy over time.",
"Job Creation: Generation of new employment opportunities in an economy.",
"Energy Efficiency: Using less energy to perform the same task, reducing energy waste.",
"Energy Policy: Government policy regarding the production, distribution, and consumption of energy.",
"International Agreements: Agreements between nations to cooperate on issues like climate change.",
"Technological Innovation: Development of new technologies or improvements to existing ones.",
"Infrastructure Investment: Allocation of funds to build or improve physical infrastructure.",
"Sustainable Agriculture: Farming practices that meet current food needs without compromising future generations.",
"Deforestation: Removal of a forest or stand of trees from land which is then converted to non-forest use.",
"Biodiversity Loss: Decline in the number and variety of species in a given area.",
"Climate Refugees: People forced to leave their homes due to the impacts of climate change.",
"Water Scarcity: Lack of sufficient available water resources to meet the demands within a region.",
"Disaster Risk Management: Strategies to reduce the damage caused by natural disasters.",
]
# Generate node embeddings
node_features = torch.tensor(embedding_model.encode(node_descriptions), dtype=torch.float)
# Expanded relationships (edge_index)
edge_index = torch.tensor([
# Source nodes (from)
[0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 9, 10, 10, 11, 12, 12, 13, 14, 15, 16, 17, 18],
# Target nodes (to)
[1, 3, 9, 11, 19, 2, 8, 13, 4, 5, 6, 2, 12, 5, 6, 6, 7, 7,8,13,14, 7,10, 2,10, 0, 6, 0, 1, 3, 2, 15,16, 17,6, 6]
], dtype=torch.long)
# Build a graph from nodes and edges
def build_graph(node_descriptions, edge_index):
graph = nx.DiGraph()
# Add nodes with descriptions
for i, description in enumerate(node_descriptions):
graph.add_node(i, description=description, embedding=node_features[i])
# Add edges
for source, target in zip(edge_index[0], edge_index[1]):
graph.add_edge(source.item(), target.item())
return graph
graph = build_graph(node_descriptions, edge_index)
# Community detection using Label Propagation (Leiden proxy)
def detect_communities(graph):
communities = list(asyn_lpa_communities(graph, weight="weight"))
return communities
detected_communities = detect_communities(graph)
print(f"Detected {len(detected_communities)} communities.")
# Prepare context from detected communities
def prepare_context(communities, graph):
context = []
for community in communities:
community_text = "\n".join([graph.nodes[node]["description"] for node in community])
context.append(community_text)
return "\n".join(context)
context = prepare_context(detected_communities, graph)
# Process query with the LLM
def process_query_with_llm(query, context, llm):
prompt = f"Query: {query}\nContext:\n{context}\nAnswer:"
return llm.generate(prompt, max_length=512)
# Example query
query = "What are the economic and environmental impacts of transitioning to renewable energy?"
response = process_query_with_llm(query, context, llm)
print("\nGenerated Response:")
print(response)
# #G-Retriever - GraphRAG without GAT
# Usese a Dummy GNN
from sentence_transformers import SentenceTransformer
import torch
from torch_geometric.nn.models import GRetriever
from torch_geometric.nn.nlp import LLM
from torch.nn import Module
import warnings
# Suppress specific warnings (e.g., CPU usage warnings)
warnings.filterwarnings("ignore", category=UserWarning, module="torch_geometric.nn.nlp.llm")
# Define DummyGNN class with out_channels
class DummyGNN(Module):
def __init__(self, out_channels):
super().__init__()
self.out_channels = out_channels # Define the expected attribute
def forward(self, x, edge_index=None, edge_attr=None):
return x # Pass through input without modification
# Initialize Sentence Transformer for embeddings
model = SentenceTransformer('all-MPNet-base-v2')
# Expanded node descriptions with more complexity
node_descriptions = [
"Climate Change Policies: Policies aimed at reducing greenhouse gas emissions and mitigating climate change effects.",
"Renewable Energy Adoption: Transition to renewable energy sources like solar, wind, and hydroelectric power.",
"Fossil Fuel Consumption: Use of fossil fuels such as coal, oil, and natural gas for energy.",
"Electric Vehicles: Vehicles powered by electric motors using energy stored in rechargeable batteries.",
"Carbon Emissions: Release of carbon dioxide into the atmosphere from various sources.",
"Air Pollution: Contamination of air by harmful substances including gases and particulates.",
"Public Health: Health outcomes of populations influenced by environmental and social factors.",
"Economic Growth: Increase in the market value of goods and services produced by an economy over time.",
"Job Creation: Generation of new employment opportunities in an economy.",
"Energy Efficiency: Using less energy to perform the same task, reducing energy waste.",
"Energy Policy: Government policy regarding the production, distribution, and consumption of energy.",
"International Agreements: Agreements between nations to cooperate on issues like climate change.",
"Technological Innovation: Development of new technologies or improvements to existing ones.",
"Infrastructure Investment: Allocation of funds to build or improve physical infrastructure.",
"Sustainable Agriculture: Farming practices that meet current food needs without compromising future generations.",
"Deforestation: Removal of a forest or stand of trees from land which is then converted to non-forest use.",
"Biodiversity Loss: Decline in the number and variety of species in a given area.",
"Climate Refugees: People forced to leave their homes due to the impacts of climate change.",
"Water Scarcity: Lack of sufficient available water resources to meet the demands within a region.",
"Disaster Risk Management: Strategies to reduce the damage caused by natural disasters.",
# Add more nodes if needed to increase complexity
]
# Generate embeddings for the nodes
node_features = torch.tensor(model.encode(node_descriptions), dtype=torch.float)
# Expanded relationships (edge_index) to create a more complex graph
edge_index = torch.tensor([
# Source nodes (from)
[0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 9, 10, 10, 11, 12, 12, 13, 14, 15, 16, 17, 18],
# Target nodes (to)
[1, 3, 9, 11, 19, 2, 8, 13, 4, 5, 6, 2, 12, 5, 6, 6, 7, 7,8,13,14, 7,10, 2,10, 0, 6, 0, 1, 3, 2, 15,16, 17,6, 6]
], dtype=torch.long)
# Batch vector for a single graph
batch = torch.zeros(len(node_descriptions), dtype=torch.long)
# Check if GPU is available and set device accordingly
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Using device: {device}")
# Initialize DummyGNN with out_channels matching the embedding size
dummy_gnn = DummyGNN(out_channels=node_features.size(1)).to(device)
# Initialize LLM
llm = LLM(model_name='meta-llama/Llama-2-7b-chat-hf', num_params=7)
# Move LLM to the appropriate device
llm.to(device)
# Initialize G-Retriever with Dummy GNN
g_retriever = GRetriever(llm=llm, gnn=dummy_gnn, mlp_out_channels=4096)
# Complex query without additional context
query = [
"Evaluate the potential long-term economic and environmental impacts of shifting from fossil fuel consumption to renewable energy adoption, considering factors such as job creation, technological innovation, energy policy, and public health. Additionally, discuss how this transition affects international agreements and climate change policies, and identify potential challenges in infrastructure investment and sustainable agriculture."
]
# Move data to the correct device
node_features = node_features.to(device)
edge_index = edge_index.to(device)
batch = batch.to(device)
# Perform inference without additional context
with torch.no_grad():
subgraph_context = g_retriever.inference(
question=query,
x=node_features, # Node embeddings
edge_index=edge_index, # Complex edge connections
batch=batch,
max_out_tokens=1024
)
# Print results
print("Subgraph context retrieved (Without GNN):", subgraph_context)
#G-Retriever - GraphRAG with GAT
from sentence_transformers import SentenceTransformer
import torch
from torch_geometric.nn import GAT
from torch_geometric.nn.models import GRetriever
from torch_geometric.nn.nlp import LLM
import warnings
# Suppress specific warnings (e.g., CPU usage warnings)
warnings.filterwarnings("ignore", category=UserWarning, module="torch_geometric.nn.nlp.llm")
# Initialize Sentence Transformer for embeddings
model = SentenceTransformer('all-MPNet-base-v2')
# Expanded node descriptions with more complexity
node_descriptions = [
"Climate Change Policies: Policies aimed at reducing greenhouse gas emissions and mitigating climate change effects.",
"Renewable Energy Adoption: Transition to renewable energy sources like solar, wind, and hydroelectric power.",
"Fossil Fuel Consumption: Use of fossil fuels such as coal, oil, and natural gas for energy.",
"Electric Vehicles: Vehicles powered by electric motors using energy stored in rechargeable batteries.",
"Carbon Emissions: Release of carbon dioxide into the atmosphere from various sources.",
"Air Pollution: Contamination of air by harmful substances including gases and particulates.",
"Public Health: Health outcomes of populations influenced by environmental and social factors.",
"Economic Growth: Increase in the market value of goods and services produced by an economy over time.",
"Job Creation: Generation of new employment opportunities in an economy.",
"Energy Efficiency: Using less energy to perform the same task, reducing energy waste.",
"Energy Policy: Government policy regarding the production, distribution, and consumption of energy.",
"International Agreements: Agreements between nations to cooperate on issues like climate change.",
"Technological Innovation: Development of new technologies or improvements to existing ones.",
"Infrastructure Investment: Allocation of funds to build or improve physical infrastructure.",
"Sustainable Agriculture: Farming practices that meet current food needs without compromising future generations.",
"Deforestation: Removal of a forest or stand of trees from land which is then converted to non-forest use.",
"Biodiversity Loss: Decline in the number and variety of species in a given area.",
"Climate Refugees: People forced to leave their homes due to the impacts of climate change.",
"Water Scarcity: Lack of sufficient available water resources to meet the demands within a region.",
"Disaster Risk Management: Strategies to reduce the damage caused by natural disasters.",
# Add more nodes if needed to increase complexity
]
# Generate embeddings for the nodes
node_features = torch.tensor(model.encode(node_descriptions), dtype=torch.float)
# Expanded relationships (edge_index) to create a more complex graph
edge_index = torch.tensor([
# Source nodes (from)
[0, 0, 0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 7, 7, 8, 8, 9, 9, 10, 10, 11, 12, 12, 13, 14, 15, 16, 17, 18],
# Target nodes (to)
[1, 3, 9, 11, 19, 2, 8, 13, 4, 5, 6, 2, 12, 5, 6, 6, 7, 7,8,13,14, 7,10, 2,10, 0, 6, 0, 1, 3, 2, 15,16, 17,6, 6]
], dtype=torch.long)
# Batch vector for a single graph
batch = torch.zeros(len(node_descriptions), dtype=torch.long)
# Check if GPU is available and set device accordingly
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
print(f"Using device: {device}")
# Move data to the correct device
node_features = node_features.to(device)
edge_index = edge_index.to(device)
batch = batch.to(device)
# Initialize GNN
gnn = GAT(
in_channels=768,
hidden_channels=1024,
out_channels=768,
num_layers=4,
heads=8
).to(device) # **Move GNN to device**
# Initialize LLM
llm = LLM(model_name='meta-llama/Llama-2-7b-chat-hf', num_params=7).to(device) # **Move LLM to device**
# Initialize G-Retriever with the real GNN
g_retriever = GRetriever(llm=llm, gnn=gnn, mlp_out_channels=4096)
# Complex query without additional context
query = [
"Evaluate the potential long-term economic and environmental impacts of shifting from fossil fuel consumption to renewable energy adoption, considering factors such as job creation, technological innovation, energy policy, and public health. Additionally, discuss how this transition affects international agreements and climate change policies, and identify potential challenges in infrastructure investment and sustainable agriculture."
]
# Perform inference without additional context
with torch.no_grad():
subgraph_context = g_retriever.inference(
question=query,
x=node_features, # Node embeddings
edge_index=edge_index, # Complex edge connections
batch=batch,
max_out_tokens=1024
)
# Print results
print("Subgraph context retrieved (With GNN):", subgraph_context)
• IMF World Economic Outlook Report, October 2024
• Kojima, Takeshi, et al. [Large Language Models are Zero-Shot Reasoners]. University of Tokyo and Google Research, 2023.
• Edge, D., Trinh, H., Cheng, N., Bradley, J., Chao, A., Mody, A., Truitt, S., Larson, J. (2024). Microsoft Research. Retrieved from Microsoft Strategic Missions and Technologies.
• He, Xiaoxin, et al. [G-Retriever: Retrieval-Augmented Generation for Textual Graph Understanding and Question Answering]. National University of Singapore, University of Notre Dame, Loyola Marymount University, New York University, Meta AI, 2023.
• Veličković, Petar, et al. “[Graph Attention Networks].” University of Cambridge, Centre de Visió per Computador (UAB), and Montréal Institute for Learning Algorithms, 2017.
• Microsoft Research Graph RAG
• PyG 2.6 Release notes
• PyG GRetriver examples
• Microsoft GraphRAG global query sample notebook
• Stanford Stanford Graph Learning Workshop 2024, Session2 GNN’s & LLM’s in PyG by Rishi Piru
• https://github.com/ozgurgulerx/gretriever-gnn
若要了解更多知识图谱或图数据库相关教学,你可以查看公众号的其他文章:
活水智能成立于北京,致力于通过AI教育、AI软件和社群提高知识工作者生产力。中国AIGC产业联盟理事。
活水现有AI线下工作坊等10+门课程,15+AI软件上线,多款产品在研。知识星球中拥有2600+成员,涵盖大厂程序员、公司高管、律师等各类知识工作者。在北、上、广、深、杭、重庆等地均有线下组织。
欢迎加入我们的福利群,每周都有一手信息、优惠券发放、优秀同学心得分享,还有赠书活动~
??????
53AI,企业落地应用大模型首选服务商
产品:大模型应用平台+智能体定制开发+落地咨询服务
承诺:先做场景POC验证,看到效果再签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2025-01-08
使用大语言模型从零构建知识图谱(上)
2025-01-06
搭建一个本地AI知识库需要用到哪些技术栈?
2025-01-04
吴恩达DeepLearning.AI课程系列 - 大模型检索增强生成(四):向量数据库中的检索优化
2025-01-04
实战Milvus 2.5:语义检索VS全文检索VS混合检索
2025-01-04
什么是元数据
2025-01-03
一位海外开发者的 OpenSPG KAG 实践分享
2025-01-03
Knowledge Graph Studio:让知识图谱构建更简单、更智能
2025-01-02
NebulaGraph + LLM 处理风控知识图谱的探索和实践
2025-01-02
2025-01-03
2024-07-17
2024-07-11
2024-08-13
2024-07-13
2024-06-24
2024-06-10
2024-07-12
2024-08-27
2025-01-10
2025-01-06
2025-01-02
2024-12-16
2024-12-10
2024-12-04
2024-12-01
2024-11-30